3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * File for CiviCRM APIv3 utilitity functions
31 * @package CiviCRM_APIv3
32 * @subpackage API_utils
34 * @copyright CiviCRM LLC (c) 2004-2014
35 * @version $Id: utils.php 30879 2010-11-22 15:45:55Z shot $
40 * Initialize CiviCRM - should be run at the start of each API function
42 function _civicrm_api3_initialize() {
43 require_once 'CRM/Core/ClassLoader.php';
44 CRM_Core_ClassLoader
::singleton()->register();
45 CRM_Core_Config
::singleton();
49 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking
51 * @param array $params
52 * Array of fields to check.
53 * @param array $daoName
54 * String DAO to check for required fields (create functions only).
55 * @param array $keyoptions
56 * List of required fields options. One of the options is required.
58 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
59 $keys = array(array());
60 foreach ($keyoptions as $key) {
63 civicrm_api3_verify_mandatory($params, $daoName, $keys);
67 * check mandatory fields are included
69 * @param array $params
70 * Array of fields to check.
71 * @param array $daoName
72 * String DAO to check for required fields (create functions only).
74 * List of required fields. A value can be an array denoting that either this or that is required.
75 * @param bool $verifyDAO
77 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
80 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
81 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
82 if (!is_array($unmatched)) {
87 if (!empty($params['id'])) {
88 $keys = array('version');
91 if (!in_array('version', $keys)) {
92 // required from v3 onwards
96 foreach ($keys as $key) {
100 foreach ($key as $subkey) {
101 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
102 $optionset[] = $subkey;
105 // as long as there is one match then we don't need to rtn anything
109 if (empty($match) && !empty($optionset)) {
110 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
114 // Disallow empty values except for the number zero.
115 // TODO: create a utility for this since it's needed in many places
116 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
121 if (!empty($unmatched)) {
122 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
132 function civicrm_api3_create_error($msg, $data = array()) {
133 $data['is_error'] = 1;
134 $data['error_message'] = $msg;
135 // we will show sql to privileged user only (not sure of a specific
136 // security hole here but seems sensible - perhaps should apply to the trace as well?)
137 if (isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
138 $data['debug_information'] = $data['sql']; // Isn't this redundant?
147 * Format array in result output styple
149 * @param array|int $values values generated by API operation (the result)
150 * @param array $params
151 * Parameters passed into API call.
152 * @param string $entity
153 * The entity being acted on.
154 * @param string $action
155 * The action passed to the API.
157 * DAO object to be freed here.
158 * @param array $extraReturnValues
159 * Additional values to be added to top level of result array(.
160 * - this param is currently used for legacy behaviour support
164 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
166 $result['is_error'] = 0;
167 //lets set the ['id'] field if it's not set & we know what the entity is
168 if (is_array($values) && !empty($entity) && $action != 'getfields') {
169 foreach ($values as $key => $item) {
170 if (empty($item['id']) && !empty($item[$entity . "_id"])) {
171 $values[$key]['id'] = $item[$entity . "_id"];
173 if (!empty($item['financial_type_id'])) {
174 //4.3 legacy handling
175 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
177 if (!empty($item['next_sched_contribution_date'])) {
178 // 4.4 legacy handling
179 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
184 if (is_array($params) && !empty($params['debug'])) {
185 if (is_string($action) && $action != 'getfields') {
186 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
188 elseif ($action != 'getfields') {
189 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
195 $allFields = array();
196 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
197 $allFields = array_keys($apiFields['values']);
199 $paramFields = array_keys($params);
200 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array('action', 'entity', 'debug', 'version', 'check_permissions', 'IDS_request_uri', 'IDS_user_agent', 'return', 'sequential', 'rowCount', 'option_offset', 'option_limit', 'custom', 'option_sort', 'options', 'prettyprint'));
202 $result['undefined_fields'] = array_merge($undefined);
205 if (is_object($dao)) {
209 $result['version'] = 3;
210 if (is_array($values)) {
211 $result['count'] = (int) count($values);
213 // Convert value-separated strings to array
214 _civicrm_api3_separate_values($values);
216 if ($result['count'] == 1) {
217 list($result['id']) = array_keys($values);
219 elseif (!empty($values['id']) && is_int($values['id'])) {
220 $result['id'] = $values['id'];
224 $result['count'] = !empty($values) ?
1 : 0;
227 if (is_array($values) && isset($params['sequential']) &&
228 $params['sequential'] == 1
230 $result['values'] = array_values($values);
233 $result['values'] = $values;
235 if (!empty($params['options']['metadata'])) {
236 // we've made metadata an array but only supporting 'fields' atm
237 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
238 $fields = civicrm_api3($entity, 'getfields', array('action' => substr($action, 0, 3) == 'get' ?
'get' : 'create'));
239 $result['metadata']['fields'] = $fields['values'];
242 // Report deprecations
243 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
244 // Always report "update" action as deprecated
245 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
246 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
249 // Metadata-level deprecations or wholesale entity deprecations
250 if ($entity == 'entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
251 $result['deprecated'] = $deprecated;
253 // Action-specific deprecations
254 elseif (!empty($deprecated[$action])) {
255 $result['deprecated'] = $deprecated[$action];
258 return array_merge($result, $extraReturnValues);
262 * Load the DAO of the entity
266 function _civicrm_api3_load_DAO($entity) {
267 $dao = _civicrm_api3_get_DAO($entity);
276 * return the DAO of the function or Entity
277 * @param string $name
278 * Either a function of the api (civicrm_{entity}_create or the entity name.
279 * return the DAO name to manipulate this function
280 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
281 * @return mixed|string
283 function _civicrm_api3_get_DAO($name) {
284 if (strpos($name, 'civicrm_api3') !== FALSE) {
285 $last = strrpos($name, '_');
286 // len ('civicrm_api3_') == 13
287 $name = substr($name, 13, $last - 13);
290 $name = _civicrm_api_get_camel_name($name, 3);
292 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
296 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
298 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
299 if ($name == 'MailingEventQueue') {
300 return 'CRM_Mailing_Event_DAO_Queue';
302 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
303 // but am not confident mailing_recipients is tested so have not tackled.
304 if ($name == 'MailingRecipients') {
305 return 'CRM_Mailing_DAO_Recipients';
307 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
308 if ($name == 'MailingComponent') {
309 return 'CRM_Mailing_DAO_Component';
311 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
312 if ($name == 'AclRole') {
313 return 'CRM_ACL_DAO_EntityRole';
315 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
316 // But this would impact SMS extensions so need to coordinate
317 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
318 if ($name == 'SmsProvider') {
319 return 'CRM_SMS_DAO_Provider';
321 // FIXME: DAO names should follow CamelCase convention
322 if ($name == 'Im' ||
$name == 'Acl') {
323 $name = strtoupper($name);
325 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
326 if ($dao ||
!$name) {
330 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
331 if (file_exists("api/v3/$name.php")) {
332 include_once "api/v3/$name.php";
335 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
336 if (function_exists($daoFn)) {
344 * return the DAO of the function or Entity
345 * @param string $name
346 * Is either a function of the api (civicrm_{entity}_create or the entity name.
347 * return the DAO name to manipulate this function
348 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
351 function _civicrm_api3_get_BAO($name) {
352 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
353 if ($name == 'PrintLabel') {
354 return 'CRM_Badge_BAO_Layout';
356 $dao = _civicrm_api3_get_DAO($name);
360 $bao = str_replace("DAO", "BAO", $dao);
361 $file = strtr($bao, '_', '/') . '.php';
362 // Check if this entity actually has a BAO. Fall back on the DAO if not.
363 return stream_resolve_include_path($file) ?
$bao : $dao;
367 * Recursive function to explode value-separated strings into arrays
370 function _civicrm_api3_separate_values(&$values) {
371 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
372 foreach ($values as $key => & $value) {
373 if (is_array($value)) {
374 _civicrm_api3_separate_values($value);
376 elseif (is_string($value)) {
377 if ($key == 'case_type_id') {// this is to honor the way case API was originally written
378 $value = trim(str_replace($sp, ',', $value), ',');
380 elseif (strpos($value, $sp) !== FALSE) {
381 $value = explode($sp, trim($value, $sp));
388 * This is a legacy wrapper for api_store_values which will check the suitable fields using getfields
389 * rather than DAO->fields
391 * Getfields has handling for how to deal with uniquenames which dao->fields doesn't
393 * Note this is used by BAO type create functions - eg. contribution
394 * @param string $entity
395 * @param array $params
396 * @param array $values
398 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
399 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
400 $fields = $fields['values'];
401 _civicrm_api3_store_values($fields, $params, $values);
405 * @param array $fields
406 * @param array $params
407 * @param array $values
411 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
414 $keys = array_intersect_key($params, $fields);
415 foreach ($keys as $name => $value) {
416 if ($name !== 'id') {
417 $values[$name] = $value;
425 * The API supports 2 types of get requestion. The more complex uses the BAO query object.
426 * This is a generic function for those functions that call it
428 * At the moment only called by contact we should extend to contribution &
429 * others that use the query object. Note that this function passes permission information in.
432 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
435 * @param array $params
436 * As passed into api get or getcount function.
437 * @param array $additional_options
438 * Array of options (so we can modify the filter).
439 * @param bool $getCount
440 * Are we just after the count.
444 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
446 // Convert id to e.g. contact_id
447 if (empty($params[$entity . '_id']) && isset($params['id'])) {
448 $params[$entity . '_id'] = $params['id'];
450 unset($params['id']);
452 $options = _civicrm_api3_get_options_from_params($params, TRUE);
454 $inputParams = array_merge(
455 CRM_Utils_Array
::value('input_params', $options, array()),
456 CRM_Utils_Array
::value('input_params', $additional_options, array())
458 $returnProperties = array_merge(
459 CRM_Utils_Array
::value('return', $options, array()),
460 CRM_Utils_Array
::value('return', $additional_options, array())
462 if (empty($returnProperties)) {
463 $returnProperties = NULL;
465 if (!empty($params['check_permissions'])) {
466 // we will filter query object against getfields
467 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
468 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
469 $fields['values'][$entity . '_id'] = array();
470 $varsToFilter = array('returnProperties', 'inputParams');
471 foreach ($varsToFilter as $varToFilter) {
472 if (!is_array($
$varToFilter)) {
475 //I was going to throw an exception rather than silently filter out - but
476 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
477 //so we are silently ignoring parts of their request
478 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
479 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
482 $options = array_merge($options, $additional_options);
483 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
484 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
485 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
486 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
490 $returnProperties = NULL;
493 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
494 foreach ($newParams as &$newParam) {
495 if ($newParam[1] == '=' && is_array($newParam[2])) {
496 // we may be looking at an attempt to use the 'IN' style syntax
497 // @todo at time of writing only 'IN' & 'NOT IN' are supported for the array style syntax
498 $sqlFilter = CRM_Core_DAO
::createSqlFilter($newParam[0], $params[$newParam[0]], 'String', NULL, TRUE);
500 $newParam[1] = key($newParam[2]);
501 $newParam[2] = $sqlFilter;
507 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
509 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
521 // only return the count of contacts
529 * get dao query object based on input params
530 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
533 * @param array $params
534 * @param string $mode
535 * @param string $entity
537 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
539 function _civicrm_api3_get_query_object($params, $mode, $entity) {
540 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
541 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
542 $offset = CRM_Utils_Array
::value('offset', $options);
543 $rowCount = CRM_Utils_Array
::value('limit', $options);
544 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
545 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
546 if (empty($returnProperties)) {
547 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
550 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
551 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
553 empty($params['check_permissions'])
555 list($select, $from, $where, $having) = $query->query();
557 $sql = "$select $from $where $having";
560 $sql .= " ORDER BY $sort ";
562 if (!empty($rowCount)) {
563 $sql .= " LIMIT $offset, $rowCount ";
565 $dao = CRM_Core_DAO
::executeQuery($sql);
566 return array($dao, $query);
570 * Function transfers the filters being passed into the DAO onto the params object
571 * @param CRM_Core_DAO $dao
572 * @param array $params
573 * @param bool $unique
574 * @param string $entity
576 * @throws API_Exception
579 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $entity) {
580 $entity = substr($dao->__table
, 8);
581 if (!empty($params[$entity . "_id"]) && empty($params['id'])) {
582 //if entity_id is set then treat it as ID (will be overridden by id if set)
583 $params['id'] = $params[$entity . "_id"];
585 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
586 $fields = array_intersect(array_keys($allfields), array_keys($params));
588 $options = _civicrm_api3_get_options_from_params($params);
589 //apply options like sort
590 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
592 //accept filters like filter.activity_date_time_high
593 // std is now 'filters' => ..
594 if (strstr(implode(',', array_keys($params)), 'filter')) {
595 if (isset($params['filters']) && is_array($params['filters'])) {
596 foreach ($params['filters'] as $paramkey => $paramvalue) {
597 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
601 foreach ($params as $paramkey => $paramvalue) {
602 if (strstr($paramkey, 'filter')) {
603 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
612 foreach ($fields as $field) {
613 if (is_array($params[$field])) {
614 //get the actual fieldname from db
615 $fieldName = $allfields[$field]['name'];
616 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
617 if (!empty($where)) {
618 $dao->whereAdd($where);
623 $daoFieldName = $allfields[$field]['name'];
624 if (empty($daoFieldName)) {
625 throw new API_Exception("Failed to determine field name for \"$field\"");
627 $dao->{$daoFieldName} = $params[$field];
630 $dao->$field = $params[$field];
634 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
636 $options['return']['id'] = TRUE;// ensure 'id' is included
637 $allfields = _civicrm_api3_get_unique_name_array($dao);
638 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
639 foreach ($returnMatched as $returnValue) {
640 $dao->selectAdd($returnValue);
643 $unmatchedFields = array_diff(// not already matched on the field names
644 array_keys($options['return']),
648 $returnUniqueMatched = array_intersect(
650 array_flip($allfields)// but a match for the field keys
652 foreach ($returnUniqueMatched as $uniqueVal) {
653 $dao->selectAdd($allfields[$uniqueVal]);
656 $dao->setApiFilter($params);
660 * Apply filters (e.g. high, low) to DAO object (prior to find)
661 * @param string $filterField
662 * Field name of filter.
663 * @param string $filterValue
664 * Field value of filter.
668 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
669 if (strstr($filterField, 'high')) {
670 $fieldName = substr($filterField, 0, -5);
671 $dao->whereAdd("($fieldName <= $filterValue )");
673 if (strstr($filterField, 'low')) {
674 $fieldName = substr($filterField, 0, -4);
675 $dao->whereAdd("($fieldName >= $filterValue )");
677 if ($filterField == 'is_current' && $filterValue == 1) {
678 $todayStart = date('Ymd000000', strtotime('now'));
679 $todayEnd = date('Ymd235959', strtotime('now'));
680 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
681 if (property_exists($dao, 'is_active')) {
682 $dao->whereAdd('is_active = 1');
688 * Get sort, limit etc options from the params - supporting old & new formats.
689 * get returnproperties for legacy
691 * @param array $params
692 * Params array as passed into civicrm_api.
693 * @param bool $queryObject
694 * Is this supporting a queryobject api (e.g contact) - if so we support more options.
695 * for legacy report & return a unique fields array
697 * @param string $entity
698 * @param string $action
700 * @throws API_Exception
702 * options extracted from params
704 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
706 $sort = CRM_Utils_Array
::value('sort', $params, 0);
707 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
708 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
710 $offset = CRM_Utils_Array
::value('offset', $params, 0);
711 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
712 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
713 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
715 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
716 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
717 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
719 if (is_array(CRM_Utils_Array
::value('options', $params))) {
720 // is count is set by generic getcount not user
721 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
722 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
723 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
724 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
727 $returnProperties = array();
728 // handle the format return =sort_name,display_name...
729 if (array_key_exists('return', $params)) {
730 if (is_array($params['return'])) {
731 $returnProperties = array_fill_keys($params['return'], 1);
734 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
735 $returnProperties = array_fill_keys($returnProperties, 1);
738 if ($entity && $action == 'get') {
739 if (!empty($returnProperties['id'])) {
740 $returnProperties[$entity . '_id'] = 1;
741 unset($returnProperties['id']);
743 switch (trim(strtolower($sort))) {
747 $sort = str_replace('id', $entity . '_id', $sort);
752 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
753 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
754 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
755 'is_count' => $is_count,
756 'return' => !empty($returnProperties) ?
$returnProperties : array(),
759 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
760 throw new API_Exception('invalid string in sort options');
766 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
767 // if the queryobject is being used this should be used
768 $inputParams = array();
769 $legacyreturnProperties = array();
771 'sort', 'offset', 'rowCount', 'options', 'return',
773 foreach ($params as $n => $v) {
774 if (substr($n, 0, 7) == 'return.') {
775 $legacyreturnProperties[substr($n, 7)] = $v;
777 elseif ($n == 'id') {
778 $inputParams[$entity . '_id'] = $v;
780 elseif (in_array($n, $otherVars)) {
783 $inputParams[$n] = $v;
784 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
785 throw new API_Exception('invalid string');
789 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
790 $options['input_params'] = $inputParams;
795 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find)
797 * @param array $params
798 * Params array as passed into civicrm_api.
803 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
805 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
806 if (!$options['is_count']) {
807 if (!empty($options['limit'])) {
808 $dao->limit((int) $options['offset'], (int) $options['limit']);
810 if (!empty($options['sort'])) {
811 $dao->orderBy($options['sort']);
817 * build fields array. This is the array of fields as it relates to the given DAO
818 * returns unique fields as keys by default but if set but can return by DB fields
820 * @param CRM_Core_DAO $bao
821 * @param bool $unique
825 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
826 $fields = $bao->fields();
828 if (empty($fields['id'])) {
829 $entity = _civicrm_api_get_entity_name_from_dao($bao);
830 $fields['id'] = $fields[$entity . '_id'];
831 unset($fields[$entity . '_id']);
836 foreach ($fields as $field) {
837 $dbFields[$field['name']] = $field;
843 * build fields array. This is the array of fields as it relates to the given DAO
844 * returns unique fields as keys by default but if set but can return by DB fields
846 * @param CRM_Core_DAO $bao
850 function _civicrm_api3_get_unique_name_array(&$bao) {
851 $fields = $bao->fields();
852 foreach ($fields as $field => $values) {
853 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
855 return $uniqueFields;
859 * Converts an DAO object to an array
861 * @param CRM_Core_DAO $dao
863 * @param array $params
864 * @param bool $uniqueFields
865 * @param string $entity
866 * @param bool $autoFind
870 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
872 if (isset($params['options']) && !empty($params['options']['is_count'])) {
873 return $dao->count();
878 if ($autoFind && !$dao->find()) {
882 if (isset($dao->count
)) {
886 $fields = array_keys(_civicrm_api3_build_fields_array($dao, $uniqueFields));
888 while ($dao->fetch()) {
890 foreach ($fields as $key) {
891 if (array_key_exists($key, $dao)) {
892 // not sure on that one
893 if ($dao->$key !== NULL) {
894 $tmp[$key] = $dao->$key;
898 $result[$dao->id
] = $tmp;
900 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
901 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
909 * We currently retrieve all custom fields or none at this level so if we know the entity
910 * && 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
911 * @todo filter so only required fields are queried
913 * @param string $entity
914 * Entity name in CamelCase.
915 * @param array $params
919 function _civicrm_api3_custom_fields_are_required($entity, $params) {
920 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
923 $options = _civicrm_api3_get_options_from_params($params);
924 //we check for possibility of 'custom' => 1 as well as specific custom fields
925 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
926 if (stristr($returnString, 'custom')) {
931 * Converts an object to an array
934 * (reference) object to convert.
935 * @param array $values
937 * @param array|bool $uniqueFields
939 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
941 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
942 foreach ($fields as $key => $value) {
943 if (array_key_exists($key, $dao)) {
944 $values[$key] = $dao->$key;
950 * Wrapper for _civicrm_object_to_array when api supports unique fields
955 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
956 return _civicrm_api3_object_to_array($dao, $values, TRUE);
961 * @param array $params
962 * @param array $values
963 * @param string $extends
964 * Entity that this custom field extends (e.g. contribution, event, contact).
965 * @param string $entityId
966 * ID of entity per $extends.
968 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
969 $values['custom'] = array();
970 $checkCheckBoxField = FALSE;
972 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
976 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
977 if (!$fields['is_error']) {
978 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
979 $fields = $fields['values'];
980 $checkCheckBoxField = TRUE;
983 foreach ($params as $key => $value) {
984 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
985 if ($customFieldID && (!is_null($value))) {
986 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
987 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
990 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
991 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
998 * @param array $params
1001 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1002 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1004 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1005 if (!array_key_exists($entity, $customFieldEntities)) {
1009 _civicrm_api3_custom_format_params($params, $values, $entity);
1010 $params = array_merge($params, $values);
1014 * we can't rely on downstream to add separators to checkboxes so we'll check here. We should look at pushing to BAO function
1015 * 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
1016 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1018 * 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
1019 * don't touch - lots of very cautious code in here
1021 * The resulting array should look like
1027 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1029 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1030 * be fixed in future
1032 * @param $checkboxFieldValue
1033 * @param $customFieldLabel
1037 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1039 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1040 // we can assume it's pre-formatted
1043 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1044 if (!empty($options['is_error'])) {
1045 //the check is precautionary - can probably be removed later
1049 $options = $options['values'];
1051 if (is_array($checkboxFieldValue)) {
1052 foreach ($checkboxFieldValue as $key => $value) {
1053 if (!array_key_exists($key, $options)) {
1054 $validValue = FALSE;
1058 // we have been passed an array that is already in the 'odd' custom field format
1063 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1064 // if the array only has one item we'll treat it like any other string
1065 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1066 $possibleValue = reset($checkboxFieldValue);
1068 if (is_string($checkboxFieldValue)) {
1069 $possibleValue = $checkboxFieldValue;
1071 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1072 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1075 elseif (is_array($checkboxFieldValue)) {
1076 // so this time around we are considering the values in the array
1077 $possibleValues = $checkboxFieldValue;
1078 $formatValue = TRUE;
1080 elseif (stristr($checkboxFieldValue, ',')) {
1081 $formatValue = TRUE;
1082 //lets see if we should separate it - we do this near the end so we
1083 // ensure we have already checked that the comma is not part of a legitimate match
1084 // and of course, we don't make any changes if we don't now have matches
1085 $possibleValues = explode(',', $checkboxFieldValue);
1088 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1092 foreach ($possibleValues as $index => $possibleValue) {
1093 if (array_key_exists($possibleValue, $options)) {
1094 // 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)
1096 elseif (array_key_exists(trim($possibleValue), $options)) {
1097 $possibleValues[$index] = trim($possibleValue);
1100 $formatValue = FALSE;
1104 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1110 * This function ensures that we have the right input parameters
1112 * This function is only called when $dao is passed into verify_mandatory.
1113 * The practice of passing $dao into verify_mandatory turned out to be
1114 * unsatisfactory as the required fields @ the dao level is so diffent to the abstract
1115 * api level. Hence the intention is to remove this function
1116 * & the associated param from viery_mandatory
1118 * @param array $params
1119 * Associative array of property name/value.
1120 * pairs to insert in new history.
1121 * @param string $daoName
1122 * @param bool $return
1124 * @daoName string DAO to check params agains
1127 * Sshould the missing fields be returned as an array (core error created as default)
1128 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1130 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1131 //@deprecated - see notes
1132 if (isset($params['extends'])) {
1133 if (($params['extends'] == 'Activity' ||
1134 $params['extends'] == 'Phonecall' ||
1135 $params['extends'] == 'Meeting' ||
1136 $params['extends'] == 'Group' ||
1137 $params['extends'] == 'Contribution'
1139 ($params['style'] == 'Tab')
1141 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1145 $dao = new $daoName();
1146 $fields = $dao->fields();
1149 foreach ($fields as $k => $v) {
1150 if ($v['name'] == 'id') {
1154 if (!empty($v['required'])) {
1155 // 0 is a valid input for numbers, CRM-8122
1156 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1162 if (!empty($missing)) {
1163 if (!empty($return)) {
1167 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1175 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this
1177 * @param string $bao_name
1179 * @param array $params
1181 * @param bool $returnAsSuccess
1182 * Return in api success format.
1183 * @param string $entity
1187 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "") {
1188 $bao = new $bao_name();
1189 _civicrm_api3_dao_set_filter($bao, $params, TRUE, $entity);
1190 if ($returnAsSuccess) {
1191 return civicrm_api3_create_success(_civicrm_api3_dao_to_array($bao, $params, FALSE, $entity), $params, $entity, 'get');
1194 return _civicrm_api3_dao_to_array($bao, $params, FALSE, $entity, 'get');
1199 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this
1201 * @param string $bao_name
1202 * Name of BAO Class.
1203 * @param array $params
1204 * Parameters passed into the api call.
1205 * @param string $entity
1206 * Entity - pass in if entity is non-standard & required $ids array.
1208 * @throws API_Exception
1211 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1212 _civicrm_api3_format_params_for_create($params, $entity);
1213 $args = array(&$params);
1214 if (!empty($entity)) {
1215 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1219 if (method_exists($bao_name, 'create')) {
1221 $fct_name = $bao_name . '::' . $fct;
1222 $bao = call_user_func_array(array($bao_name, $fct), $args);
1224 elseif (method_exists($bao_name, 'add')) {
1226 $fct_name = $bao_name . '::' . $fct;
1227 $bao = call_user_func_array(array($bao_name, $fct), $args);
1230 $fct_name = '_civicrm_api3_basic_create_fallback';
1231 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1234 if (is_null($bao)) {
1235 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1237 elseif (is_a($bao, 'CRM_Core_Error')) {
1238 //some wierd circular thing means the error takes itself as an argument
1239 $msg = $bao->getMessages($bao);
1240 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1241 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1242 // so we need to reset the error object here to avoid getting concatenated errors
1243 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1244 CRM_Core_Error
::singleton()->reset();
1245 throw new API_Exception($msg);
1249 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1250 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1255 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1257 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1258 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1260 * @param string $bao_name
1261 * @param array $params
1263 * @throws API_Exception
1264 * @return CRM_Core_DAO|NULL an instance of the BAO
1266 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1267 $dao_name = get_parent_class($bao_name);
1268 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1269 $dao_name = $bao_name;
1271 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1272 if (empty($entityName)) {
1273 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1274 'class_name' => $bao_name,
1277 $hook = empty($params['id']) ?
'create' : 'edit';
1279 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1280 $instance = new $dao_name();
1281 $instance->copyValues($params);
1283 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1289 * Function to do a 'standard' api del - when the api is only doing a $bao::del then use this
1290 * if api::del doesn't exist it will try DAO delete method
1292 * @param string $bao_name
1293 * @param array $params
1297 * @throws API_Exception
1299 function _civicrm_api3_basic_delete($bao_name, &$params) {
1301 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1302 $args = array(&$params['id']);
1303 if (method_exists($bao_name, 'del')) {
1304 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1305 if ($bao !== FALSE) {
1306 return civicrm_api3_create_success(TRUE);
1308 throw new API_Exception('Could not delete entity id ' . $params['id']);
1310 elseif (method_exists($bao_name, 'delete')) {
1311 $dao = new $bao_name();
1312 $dao->id
= $params['id'];
1314 while ($dao->fetch()) {
1316 return civicrm_api3_create_success();
1320 throw new API_Exception('Could not delete entity id ' . $params['id']);
1324 throw new API_Exception('no delete method found');
1328 * Get custom data for the given entity & Add it to the returnArray as 'custom_123' = 'custom string' AND 'custom_123_1' = 'custom string'
1329 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1331 * @param array $returnArray
1332 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1333 * @param string $entity
1334 * E.g membership, event.
1335 * @param int $entity_id
1336 * @param int $groupID
1337 * Per CRM_Core_BAO_CustomGroup::getTree.
1338 * @param int $subType
1339 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1340 * @param string $subName
1341 * Subtype of entity.
1343 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1344 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1345 CRM_Core_DAO
::$_nullObject,
1351 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1352 $customValues = array();
1353 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1354 $fieldInfo = array();
1355 foreach ($groupTree as $set) {
1356 $fieldInfo +
= $set['fields'];
1358 if (!empty($customValues)) {
1359 foreach ($customValues as $key => $val) {
1360 // per standard - return custom_fieldID
1361 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1362 $returnArray['custom_' . $id] = $val;
1364 //not standard - but some api did this so guess we should keep - cheap as chips
1365 $returnArray[$key] = $val;
1367 // Shim to restore legacy behavior of ContactReference custom fields
1368 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1369 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1370 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1377 * Validate fields being passed into API. This function relies on the getFields function working accurately
1378 * for the given API. If error mode is set to TRUE then it will also check
1381 * As of writing only date was implemented.
1382 * @param string $entity
1383 * @param string $action
1384 * @param array $params
1386 * @param array $fields
1387 * Response from getfields all variables are the same as per civicrm_api.
1388 * @param bool $errorMode
1389 * ErrorMode do intensive post fail checks?.
1392 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1393 $fields = array_intersect_key($fields, $params);
1394 foreach ($fields as $fieldName => $fieldInfo) {
1395 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1396 case CRM_Utils_Type
::T_INT
:
1397 //field is of type integer
1398 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1403 case CRM_Utils_Type
::T_TIMESTAMP
:
1404 //field is of type date or datetime
1405 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1410 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1413 case CRM_Utils_Type
::T_STRING
:
1414 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1417 case CRM_Utils_Type
::T_MONEY
:
1418 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1419 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1422 foreach ((array) $fieldValue as $fieldvalue) {
1423 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1424 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1430 // intensive checks - usually only called after DB level fail
1431 if (!empty($errorMode) && strtolower($action) == 'create') {
1432 if (!empty($fieldInfo['FKClassName'])) {
1433 if (!empty($fieldValue)) {
1434 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1436 elseif (!empty($fieldInfo['required'])) {
1437 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1440 if (!empty($fieldInfo['api.unique'])) {
1441 $params['entity'] = $entity;
1442 _civicrm_api3_validate_unique_key($params, $fieldName);
1449 * Validate date fields being passed into API.
1450 * It currently converts both unique fields and DB field names to a mysql date.
1451 * @todo - probably the unique field handling & the if exists handling is now done before this
1452 * function is reached in the wrapper - can reduce this code down to assume we
1453 * are only checking the passed in field
1455 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1456 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1458 * @param array $params
1459 * Params from civicrm_api.
1460 * @param string $fieldName
1461 * Uniquename of field being checked.
1462 * @param array $fieldInfo
1463 * Array of fields from getfields function.
1466 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1467 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1468 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1471 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1472 if (!empty($params[$fieldInfo['name']])) {
1473 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1475 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1476 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1480 $params[$fieldName][$op] = $fieldValue;
1483 $params[$fieldName] = $fieldValue;
1488 * convert date into BAO friendly date
1489 * we accept 'whatever strtotime accepts'
1491 * @param string $dateValue
1492 * @param string $fieldName
1498 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1499 if (is_array($dateValue)) {
1500 foreach ($dateValue as $key => $value) {
1501 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1505 if (strtotime($dateValue) === FALSE) {
1506 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1508 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1509 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1513 * Validate foreign constraint fields being passed into API.
1515 * @param mixed $fieldValue
1516 * @param string $fieldName
1517 * Uniquename of field being checked.
1518 * @param array $fieldInfo
1519 * Array of fields from getfields function.
1520 * @throws \API_Exception
1522 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1523 $daoName = $fieldInfo['FKClassName'];
1524 $dao = new $daoName();
1525 $dao->id
= $fieldValue;
1527 $dao->selectAdd('id');
1528 if (!$dao->find()) {
1529 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1534 * Validate foreign constraint fields being passed into API.
1536 * @param array $params
1537 * Params from civicrm_api.
1538 * @param string $fieldName
1539 * Uniquename of field being checked.
1542 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1543 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1544 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1547 $existing = civicrm_api($params['entity'], 'get', array(
1548 'version' => $params['version'],
1549 $fieldName => $fieldValue,
1551 // an entry already exists for this unique field
1552 if ($existing['count'] == 1) {
1553 // question - could this ever be a security issue?
1554 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1559 * Generic implementation of the "replace" action.
1561 * Replace the old set of entities (matching some given keys) with a new set of
1562 * entities (matching the same keys).
1564 * Note: This will verify that 'values' is present, but it does not directly verify
1565 * any other parameters.
1567 * @param string $entity
1569 * @param array $params
1570 * Params from civicrm_api, including:.
1571 * - 'values': an array of records to save
1572 * - all other items: keys which identify new/pre-existing records
1575 function _civicrm_api3_generic_replace($entity, $params) {
1577 $transaction = new CRM_Core_Transaction();
1579 if (!is_array($params['values'])) {
1580 throw new Exception("Mandatory key(s) missing from params array: values");
1583 // Extract the keys -- somewhat scary, don't think too hard about it
1584 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1586 // Lookup pre-existing records
1587 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1588 if (civicrm_error($preexisting)) {
1589 $transaction->rollback();
1590 return $preexisting;
1593 // Save the new/updated records
1595 foreach ($params['values'] as $replacement) {
1596 // Sugar: Don't force clients to duplicate the 'key' data
1597 $replacement = array_merge($baseParams, $replacement);
1598 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1599 $create = civicrm_api($entity, $action, $replacement);
1600 if (civicrm_error($create)) {
1601 $transaction->rollback();
1604 foreach ($create['values'] as $entity_id => $entity_value) {
1605 $creates[$entity_id] = $entity_value;
1609 // Remove stale records
1610 $staleIDs = array_diff(
1611 array_keys($preexisting['values']),
1612 array_keys($creates)
1614 foreach ($staleIDs as $staleID) {
1615 $delete = civicrm_api($entity, 'delete', array(
1616 'version' => $params['version'],
1619 if (civicrm_error($delete)) {
1620 $transaction->rollback();
1625 return civicrm_api3_create_success($creates, $params);
1627 catch(PEAR_Exception
$e) {
1628 $transaction->rollback();
1629 return civicrm_api3_create_error($e->getMessage());
1631 catch(Exception
$e) {
1632 $transaction->rollback();
1633 return civicrm_api3_create_error($e->getMessage());
1638 * @param array $params
1642 function _civicrm_api3_generic_replace_base_params($params) {
1643 $baseParams = $params;
1644 unset($baseParams['values']);
1645 unset($baseParams['sequential']);
1646 unset($baseParams['options']);
1651 * returns fields allowable by api
1654 * String Entity to query.
1655 * @param bool $unique
1656 * Index by unique fields?.
1657 * @param array $params
1661 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1662 $unsetIfEmpty = array('dataPattern', 'headerPattern', 'default', 'export', 'import');
1663 $dao = _civicrm_api3_get_DAO($entity);
1668 $fields = $d->fields();
1669 // replace uniqueNames by the normal names as the key
1670 if (empty($unique)) {
1671 foreach ($fields as $name => &$field) {
1672 //getting rid of unused attributes
1673 foreach ($unsetIfEmpty as $attr) {
1674 if (empty($field[$attr])) {
1675 unset($field[$attr]);
1678 if ($name == $field['name']) {
1681 if (array_key_exists($field['name'], $fields)) {
1682 $field['error'] = 'name conflict';
1683 // it should never happen, but better safe than sorry
1686 $fields[$field['name']] = $field;
1687 $fields[$field['name']]['uniqueName'] = $name;
1688 unset($fields[$name]);
1691 // Translate FKClassName to the corresponding api
1692 foreach ($fields as $name => &$field) {
1693 if (!empty($field['FKClassName'])) {
1694 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1696 $field['FKApiName'] = $FKApi;
1700 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1705 * Return an array of fields for a given entity - this is the same as the BAO function but
1706 * fields are prefixed with 'custom_' to represent api params
1708 * @param array $params
1711 function _civicrm_api_get_custom_fields($entity, &$params) {
1712 $entity = _civicrm_api_get_camel_name($entity);
1713 if ($entity == 'Contact') {
1714 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1715 $entity = CRM_Utils_Array
::value('contact_type', $params);
1717 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1720 // we could / should probably test for other subtypes here - e.g. activity_type_id
1721 CRM_Utils_Array
::value('contact_sub_type', $params),
1730 foreach ($customfields as $key => $value) {
1731 // Regular fields have a 'name' property
1732 $value['name'] = 'custom_' . $key;
1733 $value['title'] = $value['label'];
1734 $value['type'] = _getStandardTypeFromCustomDataType($value['data_type']);
1735 $ret['custom_' . $key] = $value;
1741 * Translate the custom field data_type attribute into a std 'type'
1745 function _getStandardTypeFromCustomDataType($dataType) {
1747 'String' => CRM_Utils_Type
::T_STRING
,
1748 'Int' => CRM_Utils_Type
::T_INT
,
1749 'Money' => CRM_Utils_Type
::T_MONEY
,
1750 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1751 'Float' => CRM_Utils_Type
::T_FLOAT
,
1752 'Date' => CRM_Utils_Type
::T_DATE
,
1753 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1754 'StateProvince' => CRM_Utils_Type
::T_INT
,
1755 'File' => CRM_Utils_Type
::T_STRING
,
1756 'Link' => CRM_Utils_Type
::T_STRING
,
1757 'ContactReference' => CRM_Utils_Type
::T_INT
,
1758 'Country' => CRM_Utils_Type
::T_INT
,
1760 return $mapping[$dataType];
1765 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't
1766 * If multiple aliases the last takes precedence
1768 * Function also swaps unique fields for non-unique fields & vice versa.
1769 * @param $apiRequest
1772 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
1773 foreach ($fields as $field => $values) {
1774 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
1775 if (!empty($values['api.aliases'])) {
1776 // if aliased field is not set we try to use field alias
1777 if (!isset($apiRequest['params'][$field])) {
1778 foreach ($values['api.aliases'] as $alias) {
1779 if (isset($apiRequest['params'][$alias])) {
1780 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
1782 //unset original field nb - need to be careful with this as it may bring inconsistencies
1783 // out of the woodwork but will be implementing only as _spec function extended
1784 unset($apiRequest['params'][$alias]);
1788 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
1789 && isset($apiRequest['params'][$values['name']])
1791 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
1792 // note that it would make sense to unset the original field here but tests need to be in place first
1794 if (!isset($apiRequest['params'][$field])
1796 && $field != $uniqueName
1797 && array_key_exists($uniqueName, $apiRequest['params'])
1799 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
1800 // note that it would make sense to unset the original field here but tests need to be in place first
1807 * Validate integer fields being passed into API.
1808 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user
1810 * @param array $params
1811 * Params from civicrm_api.
1812 * @param string $fieldName
1813 * Uniquename of field being checked.
1814 * @param array $fieldInfo
1815 * Array of fields from getfields function.
1816 * @param string $entity
1817 * @throws API_Exception
1819 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
1820 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1821 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1825 if (!empty($fieldValue)) {
1826 // if value = 'user_contact_id' (or similar), replace value with contact id
1827 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
1828 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
1829 if ('unknown-user' === $realContactId) {
1830 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
1832 elseif (is_numeric($realContactId)) {
1833 $fieldValue = $realContactId;
1836 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1837 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1840 // After swapping options, ensure we have an integer(s)
1841 foreach ((array) ($fieldValue) as $value) {
1842 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
1843 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
1847 // Check our field length
1848 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
1850 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
1851 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
1857 $params[$fieldName][$op] = $fieldValue;
1860 $params[$fieldName] = $fieldValue;
1865 * Determine a contact ID using a string expression
1867 * @param string $contactIdExpr
1868 * E.g. "user_contact_id" or "@user:username".
1869 * @return int|NULL|'unknown-user'
1871 function _civicrm_api3_resolve_contactID($contactIdExpr) {
1872 //if value = 'user_contact_id' replace value with logged in user id
1873 if ($contactIdExpr == "user_contact_id") {
1874 return CRM_Core_Session
::getLoggedInContactID();
1876 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
1877 $config = CRM_Core_Config
::singleton();
1879 $ufID = $config->userSystem
->getUfId($matches[1]);
1881 return 'unknown-user';
1884 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
1886 return 'unknown-user';
1895 * Validate html (check for scripting attack)
1896 * @param array $params
1897 * @param string $fieldName
1898 * @param array $fieldInfo
1900 * @throws API_Exception
1902 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
1903 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1904 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
1908 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
1909 throw new API_Exception('Illegal characters in input (potential scripting attack)', array("field" => $fieldName, "error_code" => "xss"));
1915 * Validate string fields being passed into API.
1916 * @param array $params
1917 * Params from civicrm_api.
1918 * @param string $fieldName
1919 * Uniquename of field being checked.
1920 * @param array $fieldInfo
1921 * Array of fields from getfields function.
1922 * @param string $entity
1923 * @throws API_Exception
1926 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
1927 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1928 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
1932 if (!is_array($fieldValue)) {
1933 $fieldValue = (string) $fieldValue;
1936 //@todo what do we do about passed in arrays. For many of these fields
1937 // the missing piece of functionality is separating them to a separated string
1938 // & many save incorrectly. But can we change them wholesale?
1941 foreach ((array) $fieldValue as $value) {
1942 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
1943 throw new Exception('Illegal characters in input (potential scripting attack)');
1945 if ($fieldName == 'currency') {
1946 //When using IN operator $fieldValue is a array of currency codes
1947 if (!CRM_Utils_Rule
::currencyCode($value)) {
1948 throw new Exception("Currency not a valid code: $currency");
1953 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
1954 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
1956 // Check our field length
1957 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
1958 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
1959 2100, array('field' => $fieldName)
1964 $params[$fieldName][$op] = $fieldValue;
1967 $params[$fieldName] = $fieldValue;
1972 * Validate & swap out any pseudoconstants / options
1974 * @param mixed $fieldValue
1975 * @param string $entity : api entity name
1976 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
1977 * @param array $fieldInfo : getfields meta-data
1978 * @throws \API_Exception
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
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);