3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2014
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
40 * Initialize CiviCRM - should be run at the start of each API function
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader
::singleton()->register();
45 CRM_Core_Config
::singleton();
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
51 * @param array $params
52 * Array of fields to check.
53 * @param array $daoName
54 * String DAO to check for required fields (create functions only).
55 * @param array $keyoptions
56 * List of required fields options. One of the options is required.
59 * or throws error if there the required fields not present
62 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
63 $keys = array(array());
64 foreach ($keyoptions as $key) {
67 civicrm_api3_verify_mandatory($params, $daoName, $keys);
71 * check mandatory fields are included
73 * @param array $params
74 * Array of fields to check.
75 * @param array $daoName
76 * String DAO to check for required fields (create functions only).
78 * List of required fields. A value can be an array denoting that either this or that is required.
79 * @param bool $verifyDAO
81 * @throws API_Exception
83 * or throws error if there the required fields not present
85 * @todo see notes on _civicrm_api3_check_required_fields regarding removing $daoName param
87 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
90 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
91 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
92 if (!is_array($unmatched)) {
97 if (!empty($params['id'])) {
98 $keys = array('version');
101 if (!in_array('version', $keys)) {
102 // required from v3 onwards
106 foreach ($keys as $key) {
107 if (is_array($key)) {
109 $optionset = array();
110 foreach ($key as $subkey) {
111 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
112 $optionset[] = $subkey;
115 // as long as there is one match then we don't need to rtn anything
119 if (empty($match) && !empty($optionset)) {
120 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
124 // Disallow empty values except for the number zero.
125 // TODO: create a utility for this since it's needed in many places
126 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
131 if (!empty($unmatched)) {
132 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
140 * @throws API_Exception
144 function civicrm_api3_create_error($msg, $data = array()) {
145 $data['is_error'] = 1;
146 $data['error_message'] = $msg;
147 // we will show sql to privileged user only (not sure of a specific
148 // security hole here but seems sensible - perhaps should apply to the trace as well?)
149 if (isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
150 $data['debug_information'] = $data['sql']; // Isn't this redundant?
159 * Format array in result output styple
161 * @param array|int $values values generated by API operation (the result)
162 * @param array $params
163 * Parameters passed into API call.
164 * @param string $entity
165 * The entity being acted on.
166 * @param string $action
167 * The action passed to the API.
169 * DAO object to be freed here.
170 * @param array $extraReturnValues
171 * Additional values to be added to top level of result array(.
172 * - this param is currently used for legacy behaviour support
176 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
178 $result['is_error'] = 0;
179 //lets set the ['id'] field if it's not set & we know what the entity is
180 if (is_array($values) && !empty($entity) && $action != 'getfields') {
181 foreach ($values as $key => $item) {
182 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
183 $values[$key]['id'] = $item[$entity . "_id"];
185 if (!empty($item['financial_type_id'])) {
186 //4.3 legacy handling
187 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
189 if (!empty($item['next_sched_contribution_date'])) {
190 // 4.4 legacy handling
191 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
196 if (is_array($params) && !empty($params['debug'])) {
197 if (is_string($action) && $action != 'getfields') {
198 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
200 elseif ($action != 'getfields') {
201 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
207 $allFields = array();
208 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
209 $allFields = array_keys($apiFields['values']);
211 $paramFields = array_keys($params);
212 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array('action', 'entity', 'debug', 'version', 'check_permissions', 'IDS_request_uri', 'IDS_user_agent', 'return', 'sequential', 'rowCount', 'option_offset', 'option_limit', 'custom', 'option_sort', 'options', 'prettyprint'));
214 $result['undefined_fields'] = array_merge($undefined);
217 if (is_object($dao)) {
221 $result['version'] = 3;
222 if (is_array($values)) {
223 $result['count'] = (int) count($values);
225 // Convert value-separated strings to array
226 _civicrm_api3_separate_values($values);
228 if ($result['count'] == 1) {
229 list($result['id']) = array_keys($values);
231 elseif (!empty($values['id']) && is_int($values['id'])) {
232 $result['id'] = $values['id'];
236 $result['count'] = !empty($values) ?
1 : 0;
239 if (is_array($values) && isset($params['sequential']) &&
240 $params['sequential'] == 1
242 $result['values'] = array_values($values);
245 $result['values'] = $values;
247 if (!empty($params['options']['metadata'])) {
248 // we've made metadata an array but only supporting 'fields' atm
249 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
250 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
251 $result['metadata']['fields'] = $fields['values'];
254 // Report deprecations
255 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
256 // Always report "update" action as deprecated
257 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
258 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
261 // Metadata-level deprecations or wholesale entity deprecations
262 if ($entity == 'entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
263 $result['deprecated'] = $deprecated;
265 // Action-specific deprecations
266 elseif (!empty($deprecated[$action])) {
267 $result['deprecated'] = $deprecated[$action];
270 return array_merge($result, $extraReturnValues);
274 * Load the DAO of the entity
276 function _civicrm_api3_load_DAO($entity) {
277 $dao = _civicrm_api3_get_DAO($entity);
286 * return the DAO of the function or Entity
287 * @param string $name
288 * Either a function of the api (civicrm_{entity}_create or the entity name.
289 * return the DAO name to manipulate this function
290 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
291 * @return mixed|string
293 function _civicrm_api3_get_DAO($name) {
294 if (strpos($name, 'civicrm_api3') !== FALSE) {
295 $last = strrpos($name, '_');
296 // len ('civicrm_api3_') == 13
297 $name = substr($name, 13, $last - 13);
300 $name = _civicrm_api_get_camel_name($name, 3);
302 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
306 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
308 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
309 if ($name == 'MailingEventQueue') {
310 return 'CRM_Mailing_Event_DAO_Queue';
312 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
313 // but am not confident mailing_recipients is tested so have not tackled.
314 if ($name == 'MailingRecipients') {
315 return 'CRM_Mailing_DAO_Recipients';
317 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
318 if ($name == 'MailingComponent') {
319 return 'CRM_Mailing_DAO_Component';
321 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
322 if ($name == 'AclRole') {
323 return 'CRM_ACL_DAO_EntityRole';
325 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
326 // But this would impact SMS extensions so need to coordinate
327 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
328 if ($name == 'SmsProvider') {
329 return 'CRM_SMS_DAO_Provider';
331 // FIXME: DAO names should follow CamelCase convention
332 if ($name == 'Im' ||
$name == 'Acl') {
333 $name = strtoupper($name);
335 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
336 if ($dao ||
!$name) {
340 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
341 if (file_exists("api/v3/$name.php")) {
342 include_once "api/v3/$name.php";
345 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
346 if (function_exists($daoFn)) {
354 * return the DAO of the function or Entity
355 * @param string $name
356 * Is either a function of the api (civicrm_{entity}_create or the entity name.
357 * return the DAO name to manipulate this function
358 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
361 function _civicrm_api3_get_BAO($name) {
362 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
363 if ($name == 'PrintLabel') {
364 return 'CRM_Badge_BAO_Layout';
366 $dao = _civicrm_api3_get_DAO($name);
370 $bao = str_replace("DAO", "BAO", $dao);
371 $file = strtr($bao, '_', '/') . '.php';
372 // Check if this entity actually has a BAO. Fall back on the DAO if not.
373 return stream_resolve_include_path($file) ?
$bao : $dao;
377 * Recursive function to explode value-separated strings into arrays
380 function _civicrm_api3_separate_values(&$values) {
381 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
382 foreach ($values as $key => & $value) {
383 if (is_array($value)) {
384 _civicrm_api3_separate_values($value);
386 elseif (is_string($value)) {
387 if ($key == 'case_type_id') {// this is to honor the way case API was originally written
388 $value = trim(str_replace($sp, ',', $value), ',');
390 elseif (strpos($value, $sp) !== FALSE) {
391 $value = explode($sp, trim($value, $sp));
398 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
399 * rather than DAO->fields
401 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
403 * Note this is used by BAO type create functions - eg. contribution
404 * @param string $entity
405 * @param array $params
406 * @param array $values
408 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
409 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
410 $fields = $fields['values'];
411 _civicrm_api3_store_values($fields, $params, $values);
415 * @param array $fields
416 * @param array $params
417 * @param array $values
421 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
424 $keys = array_intersect_key($params, $fields);
425 foreach ($keys as $name => $value) {
426 if ($name !== 'id') {
427 $values[$name] = $value;
435 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
436 * This is a generic function for those functions that call it
438 * At the moment only called by contact we should extend to contribution &
439 * others that use the query object. Note that this function passes permission information in.
442 * * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
445 * @param array $params
446 * As passed into api get or getcount function.
447 * @param array $additional_options
448 * Array of options (so we can modify the filter).
449 * @param bool $getCount
450 * Are we just after the count.
454 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
456 // Convert id to e.g. contact_id
457 if (empty($params[$entity . '_id']) && isset($params['id'])) {
458 $params[$entity . '_id'] = $params['id'];
460 unset($params['id']);
462 $options = _civicrm_api3_get_options_from_params($params, TRUE);
464 $inputParams = array_merge(
465 CRM_Utils_Array
::value('input_params', $options, array()),
466 CRM_Utils_Array
::value('input_params', $additional_options, array())
468 $returnProperties = array_merge(
469 CRM_Utils_Array
::value('return', $options, array()),
470 CRM_Utils_Array
::value('return', $additional_options, array())
472 if (empty($returnProperties)) {
473 $returnProperties = NULL;
475 if (!empty($params['check_permissions'])) {
476 // we will filter query object against getfields
477 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
478 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
479 $fields['values'][$entity . '_id'] = array();
480 $varsToFilter = array('returnProperties', 'inputParams');
481 foreach ($varsToFilter as $varToFilter) {
482 if (!is_array($
$varToFilter)) {
485 //I was going to throw an exception rather than silently filter out - but
486 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
487 //so we are silently ignoring parts of their request
488 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
489 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
492 $options = array_merge($options, $additional_options);
493 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
494 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
495 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
496 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
500 $returnProperties = NULL;
503 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
504 foreach ($newParams as &$newParam) {
505 if ($newParam[1] == '=' && is_array($newParam[2])) {
506 // we may be looking at an attempt to use the 'IN' style syntax
507 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
508 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
510 $newParam[1] = key($newParam[2]);
511 $newParam[2] = $sqlFilter;
517 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
519 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
530 if ($getCount) { // only return the count of contacts
538 * get dao query object based on input params
539 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
542 * @param array $params
543 * @param string $mode
544 * @param string $entity
545 * @return CRM_Core_DAO
548 function _civicrm_api3_get_query_object($params, $mode, $entity) {
549 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
550 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
551 $offset = CRM_Utils_Array
::value('offset', $options);
552 $rowCount = CRM_Utils_Array
::value('limit', $options);
553 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
554 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
555 if (empty($returnProperties)) {
556 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
559 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
560 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
562 empty($params['check_permissions'])
564 list($select, $from, $where, $having) = $query->query();
566 $sql = "$select $from $where $having";
569 $sql .= " ORDER BY $sort ";
571 if (!empty($rowCount)) {
572 $sql .= " LIMIT $offset, $rowCount ";
574 $dao = CRM_Core_DAO
::executeQuery($sql);
575 return array($dao, $query);
579 * Function transfers the filters being passed into the DAO onto the params object
580 * @param CRM_Core_DAO $dao
581 * @param array $params
582 * @param bool $unique
583 * @param string $entity
585 * @throws API_Exception
588 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
589 $entity = substr($dao->__table
, 8);
590 if (!empty($params[$entity . "_id"]) && empty($params['id'])) {
591 //if entity_id is set then treat it as ID (will be overridden by id if set)
592 $params['id'] = $params[$entity . "_id"];
594 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
595 $fields = array_intersect(array_keys($allfields), array_keys($params));
597 $options = _civicrm_api3_get_options_from_params($params);
598 //apply options like sort
599 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
601 //accept filters like filter.activity_date_time_high
602 // std is now 'filters' => ..
603 if (strstr(implode(',', array_keys($params)), 'filter')) {
604 if (isset($params['filters']) && is_array($params['filters'])) {
605 foreach ($params['filters'] as $paramkey => $paramvalue) {
606 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
610 foreach ($params as $paramkey => $paramvalue) {
611 if (strstr($paramkey, 'filter')) {
612 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
621 foreach ($fields as $field) {
622 if (is_array($params[$field])) {
623 //get the actual fieldname from db
624 $fieldName = $allfields[$field]['name'];
625 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
626 if (!empty($where)) {
627 $dao->whereAdd($where);
632 $daoFieldName = $allfields[$field]['name'];
633 if (empty($daoFieldName)) {
634 throw new API_Exception("Failed to determine field name for \"$field\"");
636 $dao->{$daoFieldName} = $params[$field];
639 $dao->$field = $params[$field];
643 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
645 $options['return']['id'] = TRUE;// ensure 'id' is included
646 $allfields = _civicrm_api3_get_unique_name_array($dao);
647 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
648 foreach ($returnMatched as $returnValue) {
649 $dao->selectAdd($returnValue);
652 $unmatchedFields = array_diff(// not already matched on the field names
653 array_keys($options['return']),
657 $returnUniqueMatched = array_intersect(
659 array_flip($allfields)// but a match for the field keys
661 foreach ($returnUniqueMatched as $uniqueVal) {
662 $dao->selectAdd($allfields[$uniqueVal]);
665 $dao->setApiFilter($params);
669 * Apply filters (e.g. high, low) to DAO object (prior to find)
670 * @param string $filterField
671 * Field name of filter.
672 * @param string $filterValue
673 * Field value of filter.
677 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
678 if (strstr($filterField, 'high')) {
679 $fieldName = substr($filterField, 0, -5);
680 $dao->whereAdd("($fieldName <= $filterValue )");
682 if (strstr($filterField, 'low')) {
683 $fieldName = substr($filterField, 0, -4);
684 $dao->whereAdd("($fieldName >= $filterValue )");
686 if ($filterField == 'is_current' && $filterValue == 1) {
687 $todayStart = date('Ymd000000', strtotime('now'));
688 $todayEnd = date('Ymd235959', strtotime('now'));
689 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
690 if (property_exists($dao, 'is_active')) {
691 $dao->whereAdd('is_active = 1');
697 * Get sort, limit etc options from the params - supporting old & new formats.
698 * get returnproperties for legacy
700 * @param array $params
701 * Params array as passed into civicrm_api.
702 * @param bool $queryObject
703 * Is this supporting a queryobject api (e.g contact) - if so we support more options.
704 * for legacy report & return a unique fields array
706 * @param string $entity
707 * @param string $action
709 * @throws API_Exception
711 * options extracted from params
713 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
715 $sort = CRM_Utils_Array
::value('sort', $params, 0);
716 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
717 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
719 $offset = CRM_Utils_Array
::value('offset', $params, 0);
720 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
721 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
722 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
724 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
725 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
726 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
728 if (is_array(CRM_Utils_Array
::value('options', $params))) {
729 // is count is set by generic getcount not user
730 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
731 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
732 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
733 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
736 $returnProperties = array();
737 // handle the format return =sort_name,display_name...
738 if (array_key_exists('return', $params)) {
739 if (is_array($params['return'])) {
740 $returnProperties = array_fill_keys($params['return'], 1);
743 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
744 $returnProperties = array_fill_keys($returnProperties, 1);
747 if ($entity && $action == 'get') {
748 if (!empty($returnProperties['id'])) {
749 $returnProperties[$entity . '_id'] = 1;
750 unset($returnProperties['id']);
752 switch (trim(strtolower($sort))) {
756 $sort = str_replace('id', $entity . '_id', $sort);
761 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
762 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
763 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
764 'is_count' => $is_count,
765 'return' => !empty($returnProperties) ?
$returnProperties : array(),
768 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
769 throw new API_Exception('invalid string in sort options');
775 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
776 // if the queryobject is being used this should be used
777 $inputParams = array();
778 $legacyreturnProperties = array();
780 'sort', 'offset', 'rowCount', 'options', 'return',
782 foreach ($params as $n => $v) {
783 if (substr($n, 0, 7) == 'return.') {
784 $legacyreturnProperties[substr($n, 7)] = $v;
786 elseif ($n == 'id') {
787 $inputParams[$entity . '_id'] = $v;
789 elseif (in_array($n, $otherVars)) {
792 $inputParams[$n] = $v;
793 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
794 throw new API_Exception('invalid string');
798 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
799 $options['input_params'] = $inputParams;
804 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
806 * @param array $params
807 * Params array as passed into civicrm_api.
812 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
814 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
815 if (!$options['is_count']) {
816 if (!empty($options['limit'])) {
817 $dao->limit((int) $options['offset'], (int) $options['limit']);
819 if (!empty($options['sort'])) {
820 $dao->orderBy($options['sort']);
826 * build fields array. This is the array of fields as it relates to the given DAO
827 * returns unique fields as keys by default but if set but can return by DB fields
829 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
830 $fields = $bao->fields();
832 if (empty($fields['id'])) {
833 $entity = _civicrm_api_get_entity_name_from_dao($bao);
834 $fields['id'] = $fields[$entity . '_id'];
835 unset($fields[$entity . '_id']);
840 foreach ($fields as $field) {
841 $dbFields[$field['name']] = $field;
847 * build fields array. This is the array of fields as it relates to the given DAO
848 * returns unique fields as keys by default but if set but can return by DB fields
849 * @param CRM_Core_BAO $bao
853 function _civicrm_api3_get_unique_name_array(&$bao) {
854 $fields = $bao->fields();
855 foreach ($fields as $field => $values) {
856 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
858 return $uniqueFields;
862 * Converts an DAO object to an array
864 * @param CRM_Core_DAO $dao
866 * @param array $params
867 * @param bool $uniqueFields
868 * @param string $entity
869 * @param bool $autoFind
876 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
878 if (isset($params['options']) && !empty($params['options']['is_count'])) {
879 return $dao->count();
884 if ($autoFind && !$dao->find()) {
888 if (isset($dao->count
)) {
892 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
894 while ($dao->fetch()) {
896 foreach ($fields as $key) {
897 if (array_key_exists($key, $dao)) {
898 // not sure on that one
899 if ($dao->$key !== NULL) {
900 $tmp[$key] = $dao->$key;
904 $result[$dao->id
] = $tmp;
906 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
907 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
915 * We currently retrieve all custom fields or none at this level so if we know the entity
916 * && 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
917 * @todo filter so only required fields are queried
919 * @param array $params
920 * @param string $entity
921 * Entity name in CamelCase.
925 function _civicrm_api3_custom_fields_are_required($entity, $params) {
926 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
929 $options = _civicrm_api3_get_options_from_params($params);
930 //we check for possibility of 'custom' => 1 as well as specific custom fields
931 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
932 if (stristr($returnString, 'custom')) {
937 * Converts an object to an array
940 * (reference) object to convert.
941 * @param array $values
943 * @param array|bool $uniqueFields
949 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
951 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
952 foreach ($fields as $key => $value) {
953 if (array_key_exists($key, $dao)) {
954 $values[$key] = $dao->$key;
960 * Wrapper for _civicrm_object_to_array when api supports unique fields
962 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
963 return _civicrm_api3_object_to_array($dao, $values, TRUE);
968 * @param array $params
969 * @param array $values
970 * @param string $extends
971 * Entity that this custom field extends (e.g. contribution, event, contact).
972 * @param string $entityId
973 * ID of entity per $extends.
975 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
976 $values['custom'] = array();
977 $checkCheckBoxField = FALSE;
979 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
983 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
984 if (!$fields['is_error']) {
985 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
986 $fields = $fields['values'];
987 $checkCheckBoxField = TRUE;
990 foreach ($params as $key => $value) {
991 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
992 if ($customFieldID && (!is_null($value))) {
993 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
994 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
997 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
998 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1005 * @param array $params
1008 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1009 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1011 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1012 if (!array_key_exists($entity, $customFieldEntities)) {
1016 _civicrm_api3_custom_format_params($params, $values, $entity);
1017 $params = array_merge($params, $values);
1021 * we can't rely on downstream to add separators to checkboxes so we'll check here. We should look at pushing to BAO function
1022 * 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
1023 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1025 * 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
1026 * don't touch - lots of very cautious code in here
1028 * The resulting array should look like
1034 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1036 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1037 * be fixed in future
1039 * @param $checkboxFieldValue
1040 * @param $customFieldLabel
1044 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1046 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1047 // we can assume it's pre-formatted
1050 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1051 if (!empty($options['is_error'])) {
1052 //the check is precautionary - can probably be removed later
1056 $options = $options['values'];
1058 if (is_array($checkboxFieldValue)) {
1059 foreach ($checkboxFieldValue as $key => $value) {
1060 if (!array_key_exists($key, $options)) {
1061 $validValue = FALSE;
1065 // we have been passed an array that is already in the 'odd' custom field format
1070 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1071 // if the array only has one item we'll treat it like any other string
1072 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1073 $possibleValue = reset($checkboxFieldValue);
1075 if (is_string($checkboxFieldValue)) {
1076 $possibleValue = $checkboxFieldValue;
1078 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1079 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1082 elseif (is_array($checkboxFieldValue)) {
1083 // so this time around we are considering the values in the array
1084 $possibleValues = $checkboxFieldValue;
1085 $formatValue = TRUE;
1087 elseif (stristr($checkboxFieldValue, ',')) {
1088 $formatValue = TRUE;
1089 //lets see if we should separate it - we do this near the end so we
1090 // ensure we have already checked that the comma is not part of a legitimate match
1091 // and of course, we don't make any changes if we don't now have matches
1092 $possibleValues = explode(',', $checkboxFieldValue);
1095 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1099 foreach ($possibleValues as $index => $possibleValue) {
1100 if (array_key_exists($possibleValue, $options)) {
1101 // 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)
1103 elseif (array_key_exists(trim($possibleValue), $options)) {
1104 $possibleValues[$index] = trim($possibleValue);
1107 $formatValue = FALSE;
1111 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1117 * This function ensures that we have the right input parameters
1119 * This function is only called when $dao is passed into verify_mandatory.
1120 * The practice of passing $dao into verify_mandatory turned out to be
1121 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
1122 * api level. Hence the intention is to remove this function
1123 * & the associated param from viery_mandatory
1125 * @param array $params
1126 * Associative array of property name/value.
1127 * pairs to insert in new history.
1128 * @param string $daoName
1129 * @param bool $return
1131 * @daoName string DAO to check params agains
1134 * Sshould the missing fields be returned as an array (core error created as default)
1135 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1138 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1139 //@deprecated - see notes
1140 if (isset($params['extends'])) {
1141 if (($params['extends'] == 'Activity' ||
1142 $params['extends'] == 'Phonecall' ||
1143 $params['extends'] == 'Meeting' ||
1144 $params['extends'] == 'Group' ||
1145 $params['extends'] == 'Contribution'
1147 ($params['style'] == 'Tab')
1149 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1153 $dao = new $daoName();
1154 $fields = $dao->fields();
1157 foreach ($fields as $k => $v) {
1158 if ($v['name'] == 'id') {
1162 if (!empty($v['required'])) {
1163 // 0 is a valid input for numbers, CRM-8122
1164 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1170 if (!empty($missing)) {
1171 if (!empty($return)) {
1175 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1183 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1185 * @param string $bao_name
1187 * @param array $params
1189 * @param bool $returnAsSuccess
1190 * Return in api success format.
1191 * @param string $entity
1195 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1196 $bao = new $bao_name();
1197 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1198 if ($returnAsSuccess) {
1199 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1202 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1207 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1209 * @param string $bao_name
1210 * Name of BAO Class.
1211 * @param array $params
1212 * Parameters passed into the api call.
1213 * @param string $entity
1214 * Entity - pass in if entity is non-standard & required $ids array.
1216 * @throws API_Exception
1219 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1220 _civicrm_api3_format_params_for_create($params, $entity);
1221 $args = array(&$params);
1222 if (!empty($entity)) {
1223 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1227 if (method_exists($bao_name, 'create')) {
1229 $fct_name = $bao_name . '::' . $fct;
1230 $bao = call_user_func_array(array($bao_name, $fct), $args);
1232 elseif (method_exists($bao_name, 'add')) {
1234 $fct_name = $bao_name . '::' . $fct;
1235 $bao = call_user_func_array(array($bao_name, $fct), $args);
1238 $fct_name = '_civicrm_api3_basic_create_fallback';
1239 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1242 if (is_null($bao)) {
1243 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1245 elseif (is_a($bao, 'CRM_Core_Error')) {
1246 //some wierd circular thing means the error takes itself as an argument
1247 $msg = $bao->getMessages($bao);
1248 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1249 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1250 // so we need to reset the error object here to avoid getting concatenated errors
1251 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1252 CRM_Core_Error
::singleton()->reset();
1253 throw new API_Exception($msg);
1257 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1258 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1263 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1265 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1266 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1268 * @param string $bao_name
1269 * @param array $params
1271 * @throws API_Exception
1272 * @return CRM_Core_DAO|NULL an instance of the BAO
1274 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1275 $dao_name = get_parent_class($bao_name);
1276 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1277 $dao_name = $bao_name;
1279 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1280 if (empty($entityName)) {
1281 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1282 'class_name' => $bao_name,
1285 $hook = empty($params['id']) ?
'create' : 'edit';
1287 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1288 $instance = new $dao_name();
1289 $instance->copyValues($params);
1291 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1297 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1298 * if api::del doesn't exist it will try DAO delete method
1300 * @param string $bao_name
1301 * @param array $params
1305 * @throws API_Exception
1307 function _civicrm_api3_basic_delete($bao_name, &$params) {
1309 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1310 $args = array(&$params['id']);
1311 if (method_exists($bao_name, 'del')) {
1312 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1313 if ($bao !== FALSE) {
1314 return civicrm_api3_create_success(TRUE);
1316 throw new API_Exception('Could not delete entity id ' . $params['id']);
1318 elseif (method_exists($bao_name, 'delete')) {
1319 $dao = new $bao_name();
1320 $dao->id
= $params['id'];
1322 while ($dao->fetch()) {
1324 return civicrm_api3_create_success();
1328 throw new API_Exception('Could not delete entity id ' . $params['id']);
1332 throw new API_Exception('no delete method found');
1336 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1337 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1339 * @param array $returnArray
1340 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1341 * @param string $entity
1342 * E.g membership, event.
1343 * @param int $entity_id
1344 * @param int $groupID
1345 * Per CRM_Core_BAO_CustomGroup::getTree.
1346 * @param int $subType
1347 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1348 * @param string $subName
1349 * Subtype of entity.
1351 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1352 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1353 CRM_Core_DAO
::$_nullObject,
1359 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1360 $customValues = array();
1361 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1362 $fieldInfo = array();
1363 foreach ($groupTree as $set) {
1364 $fieldInfo +
= $set['fields'];
1366 if (!empty($customValues)) {
1367 foreach ($customValues as $key => $val) {
1368 // per standard - return custom_fieldID
1369 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1370 $returnArray['custom_' . $id] = $val;
1372 //not standard - but some api did this so guess we should keep - cheap as chips
1373 $returnArray[$key] = $val;
1375 // Shim to restore legacy behavior of ContactReference custom fields
1376 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1377 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1378 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1385 * Validate fields being passed into API. This function relies on the getFields function working accurately
1386 * for the given API. If error mode is set to TRUE then it will also check
1389 * As of writing only date was implemented.
1390 * @param string $entity
1391 * @param string $action
1392 * @param array $params
1394 * @param array $fields
1395 * Response from getfields all variables are the same as per civicrm_api.
1396 * @param bool $errorMode
1397 * ErrorMode do intensive post fail checks?.
1400 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1401 $fields = array_intersect_key($fields, $params);
1402 foreach ($fields as $fieldName => $fieldInfo) {
1403 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1404 case CRM_Utils_Type
::T_INT
:
1405 //field is of type integer
1406 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1411 case CRM_Utils_Type
::T_TIMESTAMP
:
1412 //field is of type date or datetime
1413 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1417 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1420 case CRM_Utils_Type
::T_STRING
:
1421 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1424 case CRM_Utils_Type
::T_MONEY
:
1425 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1426 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1429 foreach((array)$fieldValue as $fieldvalue) {
1430 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1431 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1437 // intensive checks - usually only called after DB level fail
1438 if (!empty($errorMode) && strtolower($action) == 'create') {
1439 if (!empty($fieldInfo['FKClassName'])) {
1440 if (!empty($fieldValue)) {
1441 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1443 elseif (!empty($fieldInfo['required'])) {
1444 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1447 if (!empty($fieldInfo['api.unique'])) {
1448 $params['entity'] = $entity;
1449 _civicrm_api3_validate_uniquekey($params, $fieldName, $fieldInfo);
1456 * Validate date fields being passed into API.
1457 * It currently converts both unique fields and DB field names to a mysql date.
1458 * @todo - probably the unique field handling & the if exists handling is now done before this
1459 * function is reached in the wrapper - can reduce this code down to assume we
1460 * are only checking the passed in field
1462 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1463 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1465 * @param array $params
1466 * Params from civicrm_api.
1467 * @param string $fieldName
1468 * Uniquename of field being checked.
1469 * @param array $fieldInfo
1470 * Array of fields from getfields function.
1473 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1474 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1475 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1478 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1479 if (!empty($params[$fieldInfo['name']])) {
1480 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1482 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1483 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1487 $params[$fieldName][$op] = $fieldValue;
1490 $params[$fieldName] = $fieldValue;
1495 * convert date into BAO friendly date
1496 * we accept 'whatever strtotime accepts'
1498 * @param string $dateValue
1499 * @param string $fieldName
1505 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1506 if (is_array($dateValue)) {
1507 foreach ($dateValue as $key => $value) {
1508 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1512 if (strtotime($dateValue) === FALSE) {
1513 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1515 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1516 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1520 * Validate foreign constraint fields being passed into API.
1522 * @param array $params
1523 * Params from civicrm_api.
1524 * @param string $fieldName
1525 * Uniquename of field being checked.
1526 * @param array $fieldInfo
1527 * Array of fields from getfields function.
1530 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1531 $dao = new $fieldInfo['FKClassName'];
1532 $dao->id
= $fieldValue;
1534 $dao->selectAdd('id');
1535 if (!$dao->find()) {
1536 throw new Exception("$fieldName is not valid : " . $fieldValue);
1541 * Validate foreign constraint fields being passed into API.
1543 * @param array $params
1544 * Params from civicrm_api.
1545 * @param string $fieldName
1546 * Uniquename of field being checked.
1548 * Array of fields from getfields function.
1551 function _civicrm_api3_validate_uniquekey(&$params, &$fieldName, &$fieldInfo) {
1552 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1553 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1556 $existing = civicrm_api($params['entity'], 'get', array(
1557 'version' => $params['version'],
1558 $fieldName => $fieldValue,
1560 // an entry already exists for this unique field
1561 if ($existing['count'] == 1) {
1562 // question - could this ever be a security issue?
1563 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1568 * Generic implementation of the "replace" action.
1570 * Replace the old set of entities (matching some given keys) with a new set of
1571 * entities (matching the same keys).
1573 * Note: This will verify that 'values' is present, but it does not directly verify
1574 * any other parameters.
1576 * @param string $entity
1578 * @param array $params
1579 * Params from civicrm_api, including:.
1580 * - 'values': an array of records to save
1581 * - all other items: keys which identify new/pre-existing records
1584 function _civicrm_api3_generic_replace($entity, $params) {
1586 $transaction = new CRM_Core_Transaction();
1588 if (!is_array($params['values'])) {
1589 throw new Exception("Mandatory key(s) missing from params array: values");
1592 // Extract the keys -- somewhat scary, don't think too hard about it
1593 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1595 // Lookup pre-existing records
1596 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1597 if (civicrm_error($preexisting)) {
1598 $transaction->rollback();
1599 return $preexisting;
1602 // Save the new/updated records
1604 foreach ($params['values'] as $replacement) {
1605 // Sugar: Don't force clients to duplicate the 'key' data
1606 $replacement = array_merge($baseParams, $replacement);
1607 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1608 $create = civicrm_api($entity, $action, $replacement);
1609 if (civicrm_error($create)) {
1610 $transaction->rollback();
1613 foreach ($create['values'] as $entity_id => $entity_value) {
1614 $creates[$entity_id] = $entity_value;
1618 // Remove stale records
1619 $staleIDs = array_diff(
1620 array_keys($preexisting['values']),
1621 array_keys($creates)
1623 foreach ($staleIDs as $staleID) {
1624 $delete = civicrm_api($entity, 'delete', array(
1625 'version' => $params['version'],
1628 if (civicrm_error($delete)) {
1629 $transaction->rollback();
1634 return civicrm_api3_create_success($creates, $params);
1636 catch(PEAR_Exception
$e) {
1637 $transaction->rollback();
1638 return civicrm_api3_create_error($e->getMessage());
1640 catch(Exception
$e) {
1641 $transaction->rollback();
1642 return civicrm_api3_create_error($e->getMessage());
1647 * @param array $params
1651 function _civicrm_api3_generic_replace_base_params($params) {
1652 $baseParams = $params;
1653 unset($baseParams['values']);
1654 unset($baseParams['sequential']);
1655 unset($baseParams['options']);
1660 * returns fields allowable by api
1663 * String Entity to query.
1664 * @param bool $unique
1665 * Index by unique fields?.
1666 * @param array $params
1670 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1671 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1672 $dao = _civicrm_api3_get_DAO($entity);
1677 $fields = $d->fields();
1678 // replace uniqueNames by the normal names as the key
1679 if (empty($unique)) {
1680 foreach ($fields as $name => &$field) {
1681 //getting rid of unused attributes
1682 foreach ($unsetIfEmpty as $attr) {
1683 if (empty($field[$attr])) {
1684 unset($field[$attr]);
1687 if ($name == $field['name']) {
1690 if (array_key_exists($field['name'], $fields)) {
1691 $field['error'] = 'name conflict';
1692 // it should never happen, but better safe than sorry
1695 $fields[$field['name']] = $field;
1696 $fields[$field['name']]['uniqueName'] = $name;
1697 unset($fields[$name]);
1700 // Translate FKClassName to the corresponding api
1701 foreach ($fields as $name => &$field) {
1702 if (!empty($field['FKClassName'])) {
1703 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1705 $field['FKApiName'] = $FKApi;
1709 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1714 * Return an array of fields for a given entity - this is the same as the BAO function but
1715 * fields are prefixed with 'custom_' to represent api params
1717 function _civicrm_api_get_custom_fields($entity, &$params) {
1718 $entity = _civicrm_api_get_camel_name($entity);
1719 if ($entity == 'Contact') {
1720 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1721 $entity = CRM_Utils_Array
::value('contact_type', $params);
1723 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1726 // we could / should probably test for other subtypes here - e.g. activity_type_id
1727 CRM_Utils_Array
::value('contact_sub_type', $params),
1736 foreach ($customfields as $key => $value) {
1737 // Regular fields have a 'name' property
1738 $value['name'] = 'custom_' . $key;
1739 $value['title'] = $value['label'];
1740 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1741 $ret['custom_' . $key] = $value;
1746 * Translate the custom field data_type attribute into a std 'type'
1748 function _getStandardTypeFromCustomDataType($dataType) {
1750 'String' => CRM_Utils_Type
::T_STRING
,
1751 'Int' => CRM_Utils_Type
::T_INT
,
1752 'Money' => CRM_Utils_Type
::T_MONEY
,
1753 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1754 'Float' => CRM_Utils_Type
::T_FLOAT
,
1755 'Date' => CRM_Utils_Type
::T_DATE
,
1756 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1757 'StateProvince' => CRM_Utils_Type
::T_INT
,
1758 'File' => CRM_Utils_Type
::T_STRING
,
1759 'Link' => CRM_Utils_Type
::T_STRING
,
1760 'ContactReference' => CRM_Utils_Type
::T_INT
,
1761 'Country' => CRM_Utils_Type
::T_INT
,
1763 return $mapping[$dataType];
1768 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1769 * If multiple aliases the last takes precedence
1771 * Function also swaps unique fields for non-unique fields & vice versa.
1773 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1774 foreach ($fields as $field => $values) {
1775 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1776 if (!empty($values['api.aliases'])) {
1777 // if aliased field is not set we try to use field alias
1778 if (!isset($apiRequest['params'][$field])) {
1779 foreach ($values['api.aliases'] as $alias) {
1780 if (isset($apiRequest['params'][$alias])) {
1781 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1783 //unset original field nb - need to be careful with this as it may bring inconsistencies
1784 // out of the woodwork but will be implementing only as _spec function extended
1785 unset($apiRequest['params'][$alias]);
1789 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1790 && isset($apiRequest['params'][$values['name']])
1792 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1793 // note that it would make sense to unset the original field here but tests need to be in place first
1795 if (!isset($apiRequest['params'][$field])
1797 && $field != $uniqueName
1798 && array_key_exists($uniqueName, $apiRequest['params'])
1801 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1802 // note that it would make sense to unset the original field here but tests need to be in place first
1809 * Validate integer fields being passed into API.
1810 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user
1812 * @param array $params
1813 * Params from civicrm_api.
1814 * @param string $fieldName
1815 * Uniquename of field being checked.
1816 * @param array $fieldInfo
1817 * Array of fields from getfields function.
1818 * @param string $entity
1819 * @throws API_Exception
1821 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1822 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1823 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1827 if (!empty($fieldValue)) {
1828 // if value = 'user_contact_id' (or similar), replace value with contact id
1829 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1830 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1831 if ('unknown-user' === $realContactId) {
1832 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName,"type"=>"integer"));
1833 } elseif (is_numeric($realContactId)) {
1834 $fieldValue = $realContactId;
1837 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1838 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1841 // After swapping options, ensure we have an integer(s)
1842 foreach ((array) ($fieldValue) as $value) {
1843 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1844 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1848 // Check our field length
1849 if(is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1851 throw new API_Exception( $fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1852 2100, array('field' => $fieldName, "max_length"=>$fieldInfo['maxlength'])
1858 $params[$fieldName][$op] = $fieldValue;
1861 $params[$fieldName] = $fieldValue;
1866 * Determine a contact ID using a string expression
1868 * @param string $contactIdExpr
1869 * E.g. "user_contact_id" or "@user:username".
1870 * @return int|NULL|'unknown-user'
1872 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1873 //if value = 'user_contact_id' replace value with logged in user id
1874 if ($contactIdExpr == "user_contact_id") {
1875 return CRM_Core_Session
::getLoggedInContactID();
1877 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1878 $config = CRM_Core_Config
::singleton();
1880 $ufID = $config->userSystem
->getUfId($matches[1]);
1882 return 'unknown-user';
1885 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1887 return 'unknown-user';
1896 * Validate html (check for scripting attack)
1897 * @param array $params
1898 * @param string $fieldName
1899 * @param array $fieldInfo
1901 * @throws API_Exception
1903 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1904 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1905 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
1909 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
1910 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field"=>$fieldName,"error_code"=>"xss"));
1916 * Validate string fields being passed into API.
1917 * @param array $params
1918 * Params from civicrm_api.
1919 * @param string $fieldName
1920 * Uniquename of field being checked.
1921 * @param array $fieldInfo
1922 * Array of fields from getfields function.
1923 * @param string $entity
1924 * @throws API_Exception
1927 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1928 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1929 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
1933 if (!is_array($fieldValue)) {
1934 $fieldValue = (string) $fieldValue;
1937 //@todo what do we do about passed in arrays. For many of these fields
1938 // the missing piece of functionality is separating them to a separated string
1939 // & many save incorrectly. But can we change them wholesale?
1942 foreach ((array) $fieldValue as $value) {
1943 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
1944 throw new Exception('Illegal characters in input (potential scripting attack)');
1946 if ($fieldName == 'currency') {
1947 //When using IN operator $fieldValue is a array of currency codes
1948 if (!CRM_Utils_Rule
::currencyCode($value)) {
1949 throw new Exception("Currency not a valid code: $currency");
1954 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1955 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1957 // Check our field length
1958 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
1959 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1960 2100, array('field' => $fieldName)
1965 $params[$fieldName][$op] = $fieldValue;
1968 $params[$fieldName] = $fieldValue;
1973 * Validate & swap out any pseudoconstants / options
1975 * @param array $params: api parameters
1976 * @param string $entity: api entity name
1977 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
1978 * @param array $fieldInfo: getfields meta-data
1980 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
1981 $options = CRM_Utils_Array
::value('options', $fieldInfo);
1984 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
1985 // we need to get the options from the entity the field relates to
1986 $entity = $fieldInfo['entity'];
1988 $options = civicrm_api($entity, 'getoptions', array('version' => 3, 'field' => $fieldInfo['name'], 'context' => 'validate'));
1989 $options = CRM_Utils_Array
::value('values', $options, array());
1992 // If passed a value-separated string, explode to an array, then re-implode after matching values
1994 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
1995 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
1998 // If passed multiple options, validate each
1999 if (is_array($fieldValue)) {
2000 foreach ($fieldValue as &$value) {
2001 if (!is_array($value)) {
2002 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2005 // TODO: unwrap the call to implodePadded from the conditional and do it always
2006 // need to verify that this is safe and doesn't break anything though.
2007 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2009 CRM_Utils_Array
::implodePadded($fieldValue);
2013 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2018 * Validate & swap a single option value for a field
2020 * @param string $value: field value
2021 * @param array $options: array of options for this field
2022 * @param string $fieldName: field name used in api call (not necessarily the canonical name)
2023 * @throws API_Exception
2025 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2026 // If option is a key, no need to translate
2027 // or if no options are avaiable for pseudoconstant 'table' property
2028 if (array_key_exists($value, $options) ||
!$options) {
2032 // Translate value into key
2033 $newValue = array_search($value, $options);
2034 if ($newValue !== FALSE) {
2038 // Case-insensitive matching
2039 $newValue = strtolower($value);
2040 $options = array_map("strtolower", $options);
2041 $newValue = array_search($newValue, $options);
2042 if ($newValue === FALSE) {
2043 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2049 * Returns the canonical name of a field
2052 * api entity name (string should already be standardized - no camelCase).
2054 * any variation of a field's name (name, unique_name, api.alias).
2056 * @return bool|string
2057 * fieldName or FALSE if the field does not exist
2059 function _civicrm_api3_api_resolve_alias($entity, $fieldName) {
2060 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2063 if ($fieldName == "{$entity}_id") {
2066 $result = civicrm_api($entity, 'getfields', array(
2068 'action' => 'create',
2070 $meta = $result['values'];
2071 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2072 $fieldName = $fieldName . '_id';
2074 if (isset($meta[$fieldName])) {
2075 return $meta[$fieldName]['name'];
2077 foreach ($meta as $info) {
2078 if ($fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2079 return $info['name'];
2081 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2082 return $info['name'];
2089 * @param string $entity
2090 * @param array $result
2091 * @return string|array|null
2093 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2095 $apiFile = 'api/v3/' . _civicrm_api_get_camel_name($entity) . '.php';
2096 if (CRM_Utils_File
::isIncludable($apiFile)) {
2097 require_once $apiFile;
2099 $entity = _civicrm_api_get_entity_name_from_camel($entity);
2100 $fnName = "_civicrm_api3_{$entity}_deprecation";
2101 if (function_exists($fnName)) {
2102 return $fnName($result);
2108 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2109 * So this function returns the actual field value
2111 * @param array $params
2112 * @param string $fieldName
2113 * @return string|int|boolean|date|null
2115 function _civicrm_api3_field_value_check(&$params, $fieldName) {
2116 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2119 if (!empty($fieldValue) && is_array($fieldValue) && array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators())) {
2120 $op = key($fieldValue);
2121 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2123 return array($fieldValue, $op);