3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * CiviCRM APIv3 utility functions.
31 * @package CiviCRM_APIv3
35 * Initialize CiviCRM - should be run at the start of each API function.
37 function _civicrm_api3_initialize() {
38 require_once 'CRM/Core/ClassLoader.php';
39 CRM_Core_ClassLoader
::singleton()->register();
40 CRM_Core_Config
::singleton();
44 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
46 * @param array $params
47 * Array of fields to check.
48 * @param array $daoName
49 * String DAO to check for required fields (create functions only).
50 * @param array $keyoptions
51 * List of required fields options. One of the options is required.
53 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
54 $keys = array(array());
55 foreach ($keyoptions as $key) {
58 civicrm_api3_verify_mandatory($params, $daoName, $keys);
62 * Check mandatory fields are included.
64 * @param array $params
65 * Array of fields to check.
66 * @param array $daoName
67 * String DAO to check for required fields (create functions only).
69 * List of required fields. A value can be an array denoting that either this or that is required.
70 * @param bool $verifyDAO
72 * @throws \API_Exception
74 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
77 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
78 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
79 if (!is_array($unmatched)) {
84 if (!empty($params['id'])) {
85 $keys = array('version');
88 if (!in_array('version', $keys)) {
89 // required from v3 onwards
93 foreach ($keys as $key) {
97 foreach ($key as $subkey) {
98 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
99 $optionset[] = $subkey;
102 // as long as there is one match then we don't need to rtn anything
106 if (empty($match) && !empty($optionset)) {
107 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
111 // Disallow empty values except for the number zero.
112 // TODO: create a utility for this since it's needed in many places
113 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
118 if (!empty($unmatched)) {
119 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
124 * Create error array.
131 function civicrm_api3_create_error($msg, $data = array()) {
132 $data['is_error'] = 1;
133 $data['error_message'] = $msg;
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'])) {
138 if (CRM_Core_Permission
::check('Administer CiviCRM') || CIVICRM_UF
== 'UnitTests') {
139 // Isn't this redundant?
140 $data['debug_information'] = $data['sql'];
150 * Format array in result output style.
152 * @param array|int $values values generated by API operation (the result)
153 * @param array $params
154 * Parameters passed into API call.
155 * @param string $entity
156 * The entity being acted on.
157 * @param string $action
158 * The action passed to the API.
160 * DAO object to be freed here.
161 * @param array $extraReturnValues
162 * Additional values to be added to top level of result array(.
163 * - this param is currently used for legacy behaviour support
167 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
169 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
170 // TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity
171 $entity = _civicrm_api_get_camel_name($entity);
172 $result['is_error'] = 0;
173 //lets set the ['id'] field if it's not set & we know what the entity is
174 if (is_array($values) && $entity && $action != 'getfields') {
175 foreach ($values as $key => $item) {
176 if (empty($item['id']) && !empty($item[$lowercase_entity . "_id"])) {
177 $values[$key]['id'] = $item[$lowercase_entity . "_id"];
179 if (!empty($item['financial_type_id'])) {
180 //4.3 legacy handling
181 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
183 if (!empty($item['next_sched_contribution_date'])) {
184 // 4.4 legacy handling
185 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
190 if (is_array($params) && !empty($params['debug'])) {
191 if (is_string($action) && $action != 'getfields') {
192 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
194 elseif ($action != 'getfields') {
195 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
201 $allFields = array();
202 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
203 $allFields = array_keys($apiFields['values']);
205 $paramFields = array_keys($params);
206 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array(
225 $result['undefined_fields'] = array_merge($undefined);
228 if (is_object($dao)) {
232 $result['version'] = 3;
233 if (is_array($values)) {
234 $result['count'] = (int) count($values);
236 // Convert value-separated strings to array
237 if ($action != 'getfields') {
238 _civicrm_api3_separate_values($values);
241 if ($result['count'] == 1) {
242 list($result['id']) = array_keys($values);
244 elseif (!empty($values['id']) && is_int($values['id'])) {
245 $result['id'] = $values['id'];
249 $result['count'] = !empty($values) ?
1 : 0;
252 if (is_array($values) && isset($params['sequential']) &&
253 $params['sequential'] == 1
255 $result['values'] = array_values($values);
258 $result['values'] = $values;
260 if (!empty($params['options']['metadata'])) {
261 // We've made metadata an array but only supporting 'fields' atm.
262 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
263 $fields = civicrm_api3($entity, 'getfields', array(
264 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
266 $result['metadata']['fields'] = $fields['values'];
269 // Report deprecations.
270 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
271 // Always report "setvalue" action as deprecated.
272 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'setvalue')) {
273 $deprecated = ((array) $deprecated) +
array('setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.');
275 // Always report "update" action as deprecated.
276 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
277 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
280 // Metadata-level deprecations or wholesale entity deprecations.
281 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
282 $result['deprecated'] = $deprecated;
284 // Action-specific deprecations
285 elseif (!empty($deprecated[$action])) {
286 $result['deprecated'] = $deprecated[$action];
289 return array_merge($result, $extraReturnValues);
293 * Load the DAO of the entity.
299 function _civicrm_api3_load_DAO($entity) {
300 $dao = _civicrm_api3_get_DAO($entity);
309 * Return the DAO of the function or Entity.
311 * @param string $name
312 * Either a function of the api (civicrm_{entity}_create or the entity name.
313 * return the DAO name to manipulate this function
314 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
316 * @return mixed|string
318 function _civicrm_api3_get_DAO($name) {
319 if (strpos($name, 'civicrm_api3') !== FALSE) {
320 $last = strrpos($name, '_');
321 // len ('civicrm_api3_') == 13
322 $name = substr($name, 13, $last - 13);
325 $name = _civicrm_api_get_camel_name($name);
327 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
331 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
333 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
334 if ($name == 'MailingEventQueue') {
335 return 'CRM_Mailing_Event_DAO_Queue';
337 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
338 // but am not confident mailing_recipients is tested so have not tackled.
339 if ($name == 'MailingRecipients') {
340 return 'CRM_Mailing_DAO_Recipients';
342 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
343 if ($name == 'MailingComponent') {
344 return 'CRM_Mailing_DAO_Component';
346 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
347 if ($name == 'AclRole') {
348 return 'CRM_ACL_DAO_EntityRole';
350 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
351 // But this would impact SMS extensions so need to coordinate
352 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
353 if ($name == 'SmsProvider') {
354 return 'CRM_SMS_DAO_Provider';
356 // FIXME: DAO names should follow CamelCase convention
357 if ($name == 'Im' ||
$name == 'Acl') {
358 $name = strtoupper($name);
360 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
361 if ($dao ||
!$name) {
365 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
366 if (file_exists("api/v3/$name.php")) {
367 include_once "api/v3/$name.php";
370 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
371 if (function_exists($daoFn)) {
379 * Return the BAO name of the function or Entity.
381 * @param string $name
382 * Is either a function of the api (civicrm_{entity}_create or the entity name.
383 * return the DAO name to manipulate this function
384 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
388 function _civicrm_api3_get_BAO($name) {
389 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
390 if ($name == 'PrintLabel') {
391 return 'CRM_Badge_BAO_Layout';
393 $dao = _civicrm_api3_get_DAO($name);
397 $bao = str_replace("DAO", "BAO", $dao);
398 $file = strtr($bao, '_', '/') . '.php';
399 // Check if this entity actually has a BAO. Fall back on the DAO if not.
400 return stream_resolve_include_path($file) ?
$bao : $dao;
404 * Recursive function to explode value-separated strings into arrays.
408 function _civicrm_api3_separate_values(&$values) {
409 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
410 foreach ($values as $key => & $value) {
411 if (is_array($value)) {
412 _civicrm_api3_separate_values($value);
414 elseif (is_string($value)) {
415 // This is to honor the way case API was originally written.
416 if ($key == 'case_type_id') {
417 $value = trim(str_replace($sp, ',', $value), ',');
419 elseif (strpos($value, $sp) !== FALSE) {
420 $value = explode($sp, trim($value, $sp));
427 * This is a legacy wrapper for api_store_values.
429 * It checks suitable fields using getfields rather than DAO->fields.
431 * Getfields has handling for how to deal with unique names which dao->fields doesn't
433 * Note this is used by BAO type create functions - eg. contribution
435 * @param string $entity
436 * @param array $params
437 * @param array $values
439 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
440 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
441 $fields = $fields['values'];
442 _civicrm_api3_store_values($fields, $params, $values);
447 * @param array $fields
448 * @param array $params
449 * @param array $values
453 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
456 $keys = array_intersect_key($params, $fields);
457 foreach ($keys as $name => $value) {
458 if ($name !== 'id') {
459 $values[$name] = $value;
467 * Returns field names of the given entity fields.
469 * @param array $fields
470 * Fields array to retrieve the field names for.
473 function _civicrm_api3_field_names($fields) {
475 foreach ($fields as $key => $value) {
476 if (!empty($value['name'])) {
477 $result[] = $value['name'];
484 * Returns an array with database information for the custom fields of an
487 * Something similar might already exist in CiviCRM. But I was not
490 * @param string $entity
493 * an array that maps the custom field ID's to table name and
497 * 'table_name' => 'table_name_1',
498 * 'column_name' => 'column_name_1',
499 * 'data_type' => 'data_type_1',
503 function _civicrm_api3_custom_fields_for_entity($entity) {
507 SELECT f.id, f.label, f.data_type,
508 f.html_type, f.is_search_range,
509 f.option_group_id, f.custom_group_id,
510 f.column_name, g.table_name,
511 f.date_format,f.time_format
512 FROM civicrm_custom_field f
513 JOIN civicrm_custom_group g ON f.custom_group_id = g.id
514 WHERE g.is_active = 1
519 '1' => array($entity, 'String'),
522 $dao = CRM_Core_DAO
::executeQuery($query, $params);
523 while ($dao->fetch()) {
524 $result[$dao->id
] = array(
525 'table_name' => $dao->table_name
,
526 'column_name' => $dao->column_name
,
527 'data_type' => $dao->data_type
,
536 * Get function for query object api.
538 * The API supports 2 types of get request. The more complex uses the BAO query object.
539 * This is a generic function for those functions that call it
541 * At the moment only called by contact we should extend to contribution &
542 * others that use the query object. Note that this function passes permission information in.
545 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
549 * @param array $params
550 * As passed into api get or getcount function.
551 * @param array $additional_options
552 * Array of options (so we can modify the filter).
553 * @param bool $getCount
554 * Are we just after the count.
556 * This basically correlates to the component.
557 * @param null|array $defaultReturnProperties
558 * Default return properties for the entity
559 * (used if return not set - but don't do that - set return!).
562 * @throws API_Exception
564 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL, $mode = 1, $defaultReturnProperties = NULL) {
565 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
566 // Convert id to e.g. contact_id
567 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
568 $params[$lowercase_entity . '_id'] = $params['id'];
570 unset($params['id']);
572 $options = _civicrm_api3_get_options_from_params($params, TRUE);
574 $inputParams = array_merge(
575 CRM_Utils_Array
::value('input_params', $options, array()),
576 CRM_Utils_Array
::value('input_params', $additional_options, array())
578 $returnProperties = array_merge(
579 CRM_Utils_Array
::value('return', $options, array()),
580 CRM_Utils_Array
::value('return', $additional_options, array())
582 if (empty($returnProperties)) {
583 $returnProperties = $defaultReturnProperties;
585 if (!empty($params['check_permissions'])) {
586 // we will filter query object against getfields
587 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
588 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
589 $fields['values'][$lowercase_entity . '_id'] = array();
590 $varsToFilter = array('returnProperties', 'inputParams');
591 foreach ($varsToFilter as $varToFilter) {
592 if (!is_array($
$varToFilter)) {
595 //I was going to throw an exception rather than silently filter out - but
596 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
597 //so we are silently ignoring parts of their request
598 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
599 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
602 $options = array_merge($options, $additional_options);
603 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
604 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
605 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
606 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
610 $returnProperties = NULL;
613 if (substr($sort, 0, 2) == 'id') {
614 $sort = $lowercase_entity . "_" . $sort;
617 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
619 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
621 list($entities) = CRM_Contact_BAO_Query
::apiQuery(
639 * Get dao query object based on input params.
641 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
644 * @param array $params
645 * @param string $mode
646 * @param string $entity
649 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
651 function _civicrm_api3_get_query_object($params, $mode, $entity) {
652 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
653 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
654 $offset = CRM_Utils_Array
::value('offset', $options);
655 $rowCount = CRM_Utils_Array
::value('limit', $options);
656 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
657 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
658 if (empty($returnProperties)) {
659 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
662 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
663 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
665 empty($params['check_permissions'])
667 list($select, $from, $where, $having) = $query->query();
669 $sql = "$select $from $where $having";
672 $sql .= " ORDER BY $sort ";
674 if (!empty($rowCount)) {
675 $sql .= " LIMIT $offset, $rowCount ";
677 $dao = CRM_Core_DAO
::executeQuery($sql);
678 return array($dao, $query);
682 * Function transfers the filters being passed into the DAO onto the params object.
684 * @deprecated DAO based retrieval is being phased out.
686 * @param CRM_Core_DAO $dao
687 * @param array $params
688 * @param bool $unique
689 * @param array $extraSql
690 * API specific queries eg for event isCurrent would be converted to
691 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
693 * @throws API_Exception
696 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = array()) {
697 $entity = _civicrm_api_get_entity_name_from_dao($dao);
698 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
699 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
700 //if entity_id is set then treat it as ID (will be overridden by id if set)
701 $params['id'] = $params[$lowercase_entity . "_id"];
703 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
704 $fields = array_intersect(array_keys($allfields), array_keys($params));
706 $options = _civicrm_api3_get_options_from_params($params);
707 //apply options like sort
708 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
710 //accept filters like filter.activity_date_time_high
711 // std is now 'filters' => ..
712 if (strstr(implode(',', array_keys($params)), 'filter')) {
713 if (isset($params['filters']) && is_array($params['filters'])) {
714 foreach ($params['filters'] as $paramkey => $paramvalue) {
715 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
719 foreach ($params as $paramkey => $paramvalue) {
720 if (strstr($paramkey, 'filter')) {
721 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
730 foreach ($fields as $field) {
731 if (is_array($params[$field])) {
732 //get the actual fieldname from db
733 $fieldName = $allfields[$field]['name'];
734 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
735 if (!empty($where)) {
736 $dao->whereAdd($where);
741 $daoFieldName = $allfields[$field]['name'];
742 if (empty($daoFieldName)) {
743 throw new API_Exception("Failed to determine field name for \"$field\"");
745 $dao->{$daoFieldName} = $params[$field];
748 $dao->$field = $params[$field];
752 if (!empty($extraSql['where'])) {
753 foreach ($extraSql['where'] as $table => $sqlWhere) {
754 foreach ($sqlWhere as $where) {
755 $dao->whereAdd($where);
759 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
761 // Ensure 'id' is included.
762 $options['return']['id'] = TRUE;
763 $allfields = _civicrm_api3_get_unique_name_array($dao);
764 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
765 foreach ($returnMatched as $returnValue) {
766 $dao->selectAdd($returnValue);
769 // Not already matched on the field names.
770 $unmatchedFields = array_diff(
771 array_keys($options['return']),
775 $returnUniqueMatched = array_intersect(
777 // But a match for the field keys.
778 array_flip($allfields)
780 foreach ($returnUniqueMatched as $uniqueVal) {
781 $dao->selectAdd($allfields[$uniqueVal]);
784 $dao->setApiFilter($params);
788 * Apply filters (e.g. high, low) to DAO object (prior to find).
790 * @param string $filterField
791 * Field name of filter.
792 * @param string $filterValue
793 * Field value of filter.
797 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
798 if (strstr($filterField, 'high')) {
799 $fieldName = substr($filterField, 0, -5);
800 $dao->whereAdd("($fieldName <= $filterValue )");
802 if (strstr($filterField, 'low')) {
803 $fieldName = substr($filterField, 0, -4);
804 $dao->whereAdd("($fieldName >= $filterValue )");
806 if ($filterField == 'is_current' && $filterValue == 1) {
807 $todayStart = date('Ymd000000', strtotime('now'));
808 $todayEnd = date('Ymd235959', strtotime('now'));
809 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
810 if (property_exists($dao, 'is_active')) {
811 $dao->whereAdd('is_active = 1');
817 * Get sort, limit etc options from the params - supporting old & new formats.
819 * Get returnProperties for legacy
821 * @param array $params
822 * Params array as passed into civicrm_api.
823 * @param bool $queryObject
824 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
825 * for legacy report & return a unique fields array
827 * @param string $entity
828 * @param string $action
830 * @throws API_Exception
832 * options extracted from params
834 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
835 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
837 $sort = CRM_Utils_Array
::value('sort', $params, 0);
838 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
839 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
841 $offset = CRM_Utils_Array
::value('offset', $params, 0);
842 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
843 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
844 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
846 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
847 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
848 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
850 if (is_array(CRM_Utils_Array
::value('options', $params))) {
851 // is count is set by generic getcount not user
852 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
853 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
854 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
855 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
858 $returnProperties = array();
859 // handle the format return =sort_name,display_name...
860 if (array_key_exists('return', $params)) {
861 if (is_array($params['return'])) {
862 $returnProperties = array_fill_keys($params['return'], 1);
865 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
866 $returnProperties = array_fill_keys($returnProperties, 1);
869 if ($entity && $action == 'get') {
870 if (!empty($returnProperties['id'])) {
871 $returnProperties[$lowercase_entity . '_id'] = 1;
872 unset($returnProperties['id']);
874 switch (trim(strtolower($sort))) {
878 $sort = str_replace('id', $lowercase_entity . '_id', $sort);
883 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
884 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
885 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
886 'is_count' => $is_count,
887 'return' => !empty($returnProperties) ?
$returnProperties : array(),
890 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
891 throw new API_Exception('invalid string in sort options');
897 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
898 // if the query object is being used this should be used
899 $inputParams = array();
900 $legacyreturnProperties = array();
902 'sort', 'offset', 'rowCount', 'options', 'return',
903 'version', 'prettyprint', 'check_permissions', 'sequential',
905 foreach ($params as $n => $v) {
906 if (substr($n, 0, 7) == 'return.') {
907 $legacyreturnProperties[substr($n, 7)] = $v;
909 elseif ($n == 'id') {
910 $inputParams[$lowercase_entity . '_id'] = $v;
912 elseif (in_array($n, $otherVars)) {
915 $inputParams[$n] = $v;
916 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
917 throw new API_Exception('invalid string');
921 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
922 $options['input_params'] = $inputParams;
927 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
929 * @param array $params
930 * Params array as passed into civicrm_api.
935 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
937 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
938 if (!$options['is_count']) {
939 if (!empty($options['limit'])) {
940 $dao->limit((int) $options['offset'], (int) $options['limit']);
942 if (!empty($options['sort'])) {
943 $dao->orderBy($options['sort']);
949 * Build fields array.
951 * This is the array of fields as it relates to the given DAO
952 * returns unique fields as keys by default but if set but can return by DB fields
954 * @param CRM_Core_DAO $bao
955 * @param bool $unique
959 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
960 $fields = $bao->fields();
962 if (empty($fields['id'])) {
963 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
964 $fields['id'] = $fields[$lowercase_entity . '_id'];
965 unset($fields[$lowercase_entity . '_id']);
970 foreach ($fields as $field) {
971 $dbFields[$field['name']] = $field;
977 * Build fields array.
979 * This is the array of fields as it relates to the given DAO
980 * returns unique fields as keys by default but if set but can return by DB fields
982 * @param CRM_Core_DAO $bao
986 function _civicrm_api3_get_unique_name_array(&$bao) {
987 $fields = $bao->fields();
988 foreach ($fields as $field => $values) {
989 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
991 return $uniqueFields;
995 * Converts an DAO object to an array.
997 * @deprecated - DAO based retrieval is being phased out.
999 * @param CRM_Core_DAO $dao
1000 * Object to convert.
1001 * @param array $params
1002 * @param bool $uniqueFields
1003 * @param string $entity
1004 * @param bool $autoFind
1008 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
1010 if (isset($params['options']) && !empty($params['options']['is_count'])) {
1011 return $dao->count();
1016 if ($autoFind && !$dao->find()) {
1020 if (isset($dao->count
)) {
1024 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
1025 while ($dao->fetch()) {
1027 foreach ($fields as $key) {
1028 if (array_key_exists($key, $dao)) {
1029 // not sure on that one
1030 if ($dao->$key !== NULL) {
1031 $tmp[$key] = $dao->$key;
1035 $result[$dao->id
] = $tmp;
1037 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1038 _civicrm_api3_custom_data_get($result[$dao->id
], $params['check_permissions'], $entity, $dao->id
);
1046 * Determine if custom fields need to be retrieved.
1048 * We currently retrieve all custom fields or none at this level so if we know the entity
1049 * && 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
1050 * @todo filter so only required fields are queried
1052 * @param string $entity
1053 * Entity name in CamelCase.
1054 * @param array $params
1058 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1059 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1062 $options = _civicrm_api3_get_options_from_params($params);
1063 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1064 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1065 if (stristr($returnString, 'custom')) {
1071 * Converts an object to an array.
1073 * @param object $dao
1074 * (reference) object to convert.
1075 * @param array $values
1076 * (reference) array.
1077 * @param array|bool $uniqueFields
1079 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1081 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1082 foreach ($fields as $key => $value) {
1083 if (array_key_exists($key, $dao)) {
1084 $values[$key] = $dao->$key;
1090 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1097 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1098 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1102 * Format custom parameters.
1104 * @param array $params
1105 * @param array $values
1106 * @param string $extends
1107 * Entity that this custom field extends (e.g. contribution, event, contact).
1108 * @param string $entityId
1109 * ID of entity per $extends.
1111 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1112 $values['custom'] = array();
1113 $checkCheckBoxField = FALSE;
1115 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1116 $entity = 'Contact';
1119 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1120 if (!$fields['is_error']) {
1121 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1122 $fields = $fields['values'];
1123 $checkCheckBoxField = TRUE;
1126 foreach ($params as $key => $value) {
1127 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1128 if ($customFieldID && (!is_null($value))) {
1129 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1130 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1133 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1134 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1141 * Format parameters for create action.
1143 * @param array $params
1146 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1147 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1149 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1150 if (!array_key_exists($entity, $customFieldEntities)) {
1154 _civicrm_api3_custom_format_params($params, $values, $entity);
1155 $params = array_merge($params, $values);
1159 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1161 * We should look at pushing to BAO function
1162 * 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
1163 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1165 * 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
1166 * don't touch - lots of very cautious code in here
1168 * The resulting array should look like
1174 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1176 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1177 * be fixed in future
1179 * @param mixed $checkboxFieldValue
1180 * @param string $customFieldLabel
1181 * @param string $entity
1183 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1185 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1186 // We can assume it's pre-formatted.
1189 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1190 if (!empty($options['is_error'])) {
1191 // The check is precautionary - can probably be removed later.
1195 $options = $options['values'];
1197 if (is_array($checkboxFieldValue)) {
1198 foreach ($checkboxFieldValue as $key => $value) {
1199 if (!array_key_exists($key, $options)) {
1200 $validValue = FALSE;
1204 // we have been passed an array that is already in the 'odd' custom field format
1209 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1210 // if the array only has one item we'll treat it like any other string
1211 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1212 $possibleValue = reset($checkboxFieldValue);
1214 if (is_string($checkboxFieldValue)) {
1215 $possibleValue = $checkboxFieldValue;
1217 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1218 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1221 elseif (is_array($checkboxFieldValue)) {
1222 // so this time around we are considering the values in the array
1223 $possibleValues = $checkboxFieldValue;
1224 $formatValue = TRUE;
1226 elseif (stristr($checkboxFieldValue, ',')) {
1227 $formatValue = TRUE;
1228 //lets see if we should separate it - we do this near the end so we
1229 // ensure we have already checked that the comma is not part of a legitimate match
1230 // and of course, we don't make any changes if we don't now have matches
1231 $possibleValues = explode(',', $checkboxFieldValue);
1234 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1238 foreach ($possibleValues as $index => $possibleValue) {
1239 if (array_key_exists($possibleValue, $options)) {
1240 // 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)
1242 elseif (array_key_exists(trim($possibleValue), $options)) {
1243 $possibleValues[$index] = trim($possibleValue);
1246 $formatValue = FALSE;
1250 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1255 * This function ensures that we have the right input parameters.
1259 * This function is only called when $dao is passed into verify_mandatory.
1260 * The practice of passing $dao into verify_mandatory turned out to be
1261 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1262 * api level. Hence the intention is to remove this function
1263 * & the associated param from verify_mandatory
1265 * @param array $params
1266 * Associative array of property name/value.
1267 * pairs to insert in new history.
1268 * @param string $daoName
1269 * @param bool $return
1271 * @daoName string DAO to check params against
1274 * Should the missing fields be returned as an array (core error created as default)
1275 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1277 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1278 //@deprecated - see notes
1279 if (isset($params['extends'])) {
1280 if (($params['extends'] == 'Activity' ||
1281 $params['extends'] == 'Phonecall' ||
1282 $params['extends'] == 'Meeting' ||
1283 $params['extends'] == 'Group' ||
1284 $params['extends'] == 'Contribution'
1286 ($params['style'] == 'Tab')
1288 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1292 $dao = new $daoName();
1293 $fields = $dao->fields();
1296 foreach ($fields as $k => $v) {
1297 if ($v['name'] == 'id') {
1301 if (!empty($v['required'])) {
1302 // 0 is a valid input for numbers, CRM-8122
1303 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1309 if (!empty($missing)) {
1310 if (!empty($return)) {
1314 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1322 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1324 * @param string $bao_name
1326 * @param array $params
1328 * @param bool $returnAsSuccess
1329 * Return in api success format.
1330 * @param string $entity
1331 * @param CRM_Utils_SQL_Select|NULL $sql
1332 * Extra SQL bits to add to the query. For filtering current events, this might be:
1333 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1334 * @param bool $uniqueFields
1335 * Should unique field names be returned (for backward compatibility)
1339 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1340 $query = new \Civi\API\
SelectQuery($bao_name, $params, $uniqueFields);
1341 $query->merge($sql);
1342 $result = $query->run();
1343 if ($returnAsSuccess) {
1344 return civicrm_api3_create_success($result, $params, $entity, 'get');
1350 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1352 * @param string $bao_name
1353 * Name of BAO Class.
1354 * @param array $params
1355 * Parameters passed into the api call.
1356 * @param string $entity
1357 * Entity - pass in if entity is non-standard & required $ids array.
1359 * @throws API_Exception
1360 * @throws \Civi\API\Exception\UnauthorizedException
1363 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1364 _civicrm_api3_check_edit_permissions($bao_name, $params);
1365 _civicrm_api3_format_params_for_create($params, $entity);
1366 $args = array(&$params);
1368 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1372 if (method_exists($bao_name, 'create')) {
1374 $fct_name = $bao_name . '::' . $fct;
1375 $bao = call_user_func_array(array($bao_name, $fct), $args);
1377 elseif (method_exists($bao_name, 'add')) {
1379 $fct_name = $bao_name . '::' . $fct;
1380 $bao = call_user_func_array(array($bao_name, $fct), $args);
1383 $fct_name = '_civicrm_api3_basic_create_fallback';
1384 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1387 if (is_null($bao)) {
1388 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1390 elseif (is_a($bao, 'CRM_Core_Error')) {
1391 //some weird circular thing means the error takes itself as an argument
1392 $msg = $bao->getMessages($bao);
1393 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1394 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1395 // so we need to reset the error object here to avoid getting concatenated errors
1396 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1397 CRM_Core_Error
::singleton()->reset();
1398 throw new API_Exception($msg);
1402 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1403 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1408 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1410 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1411 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1413 * @param string $bao_name
1414 * @param array $params
1416 * @throws API_Exception
1418 * @return CRM_Core_DAO|NULL
1419 * An instance of the BAO
1421 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1422 $dao_name = get_parent_class($bao_name);
1423 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1424 $dao_name = $bao_name;
1426 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1427 if (empty($entityName)) {
1428 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1429 'class_name' => $bao_name,
1432 $hook = empty($params['id']) ?
'create' : 'edit';
1434 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1435 $instance = new $dao_name();
1436 $instance->copyValues($params);
1438 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1444 * Function to do a 'standard' api del.
1446 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1448 * @param string $bao_name
1449 * @param array $params
1453 * @throws API_Exception
1454 * @throws \Civi\API\Exception\UnauthorizedException
1456 function _civicrm_api3_basic_delete($bao_name, &$params) {
1457 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1458 _civicrm_api3_check_edit_permissions($bao_name, array('id' => $params['id']));
1459 $args = array(&$params['id']);
1460 if (method_exists($bao_name, 'del')) {
1461 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1462 if ($bao !== FALSE) {
1463 return civicrm_api3_create_success(TRUE);
1465 throw new API_Exception('Could not delete entity id ' . $params['id']);
1467 elseif (method_exists($bao_name, 'delete')) {
1468 $dao = new $bao_name();
1469 $dao->id
= $params['id'];
1471 while ($dao->fetch()) {
1473 return civicrm_api3_create_success();
1477 throw new API_Exception('Could not delete entity id ' . $params['id']);
1481 throw new API_Exception('no delete method found');
1485 * Get custom data for the given entity & Add it to the returnArray.
1487 * This looks like 'custom_123' = 'custom string' AND
1488 * 'custom_123_1' = 'custom string'
1489 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1491 * @param array $returnArray
1492 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1493 * @param string $entity
1494 * E.g membership, event.
1495 * @param int $entity_id
1496 * @param int $groupID
1497 * Per CRM_Core_BAO_CustomGroup::getTree.
1498 * @param int $subType
1499 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1500 * @param string $subName
1501 * Subtype of entity.
1503 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1504 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1515 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1516 $customValues = array();
1517 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1518 $fieldInfo = array();
1519 foreach ($groupTree as $set) {
1520 $fieldInfo +
= $set['fields'];
1522 if (!empty($customValues)) {
1523 foreach ($customValues as $key => $val) {
1524 // per standard - return custom_fieldID
1525 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1526 $returnArray['custom_' . $id] = $val;
1528 //not standard - but some api did this so guess we should keep - cheap as chips
1529 $returnArray[$key] = $val;
1531 // Shim to restore legacy behavior of ContactReference custom fields
1532 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1533 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1534 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1541 * Validate fields being passed into API.
1543 * This function relies on the getFields function working accurately
1544 * for the given API.
1546 * As of writing only date was implemented.
1548 * @param string $entity
1549 * @param string $action
1550 * @param array $params
1552 * @param array $fields
1553 * Response from getfields all variables are the same as per civicrm_api.
1557 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1558 //CRM-15792 handle datetime for custom fields below code handles chain api call
1559 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1560 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1561 foreach ($chainApikeys as $key => $value) {
1562 if (is_array($params[$key])) {
1563 $chainApiParams = array_intersect_key($fields, $params[$key]);
1564 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1568 $fields = array_intersect_key($fields, $params);
1569 if (!empty($chainApiParams)) {
1570 $fields = array_merge($fields, $chainApiParams);
1572 foreach ($fields as $fieldName => $fieldInfo) {
1573 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1574 case CRM_Utils_Type
::T_INT
:
1575 //field is of type integer
1576 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1579 case CRM_Utils_Type
::T_DATE
:
1580 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1581 case CRM_Utils_Type
::T_TIMESTAMP
:
1582 //field is of type date or datetime
1583 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1584 $dateParams = &$params[$customFields[$fieldName]];
1587 $dateParams = &$params;
1589 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1592 case CRM_Utils_Type
::T_TEXT
:
1594 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1597 case CRM_Utils_Type
::T_STRING
:
1598 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1601 case CRM_Utils_Type
::T_MONEY
:
1602 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1603 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1606 foreach ((array) $fieldValue as $fieldvalue) {
1607 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1608 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1617 * Validate foreign key values of fields being passed into API.
1619 * This function relies on the getFields function working accurately
1620 * for the given API.
1622 * @param string $entity
1623 * @param string $action
1624 * @param array $params
1626 * @param array $fields
1627 * Response from getfields all variables are the same as per civicrm_api.
1631 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1632 // intensive checks - usually only called after DB level fail
1633 foreach ($fields as $fieldName => $fieldInfo) {
1634 if (!empty($fieldInfo['FKClassName'])) {
1635 if (!empty($params[$fieldName])) {
1636 _civicrm_api3_validate_constraint($params[$fieldName], $fieldName, $fieldInfo);
1638 elseif (!empty($fieldInfo['required'])) {
1639 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report.");
1642 if (!empty($fieldInfo['api.unique'])) {
1643 $params['entity'] = $entity;
1644 _civicrm_api3_validate_unique_key($params, $fieldName);
1650 * Validate date fields being passed into API.
1652 * It currently converts both unique fields and DB field names to a mysql date.
1653 * @todo - probably the unique field handling & the if exists handling is now done before this
1654 * function is reached in the wrapper - can reduce this code down to assume we
1655 * are only checking the passed in field
1657 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1658 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1660 * @param array $params
1661 * Params from civicrm_api.
1662 * @param string $fieldName
1663 * Uniquename of field being checked.
1664 * @param array $fieldInfo
1665 * Array of fields from getfields function.
1669 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1670 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1671 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1674 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1675 if (!empty($params[$fieldInfo['name']])) {
1676 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1678 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1679 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1683 $params[$fieldName][$op] = $fieldValue;
1686 $params[$fieldName] = $fieldValue;
1691 * Convert date into BAO friendly date.
1693 * We accept 'whatever strtotime accepts'
1695 * @param string $dateValue
1696 * @param string $fieldName
1702 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1703 if (is_array($dateValue)) {
1704 foreach ($dateValue as $key => $value) {
1705 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1709 if (strtotime($dateValue) === FALSE) {
1710 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1712 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1713 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1717 * Validate foreign constraint fields being passed into API.
1719 * @param mixed $fieldValue
1720 * @param string $fieldName
1721 * Uniquename of field being checked.
1722 * @param array $fieldInfo
1723 * Array of fields from getfields function.
1725 * @throws \API_Exception
1727 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1728 $daoName = $fieldInfo['FKClassName'];
1729 $dao = new $daoName();
1730 $dao->id
= $fieldValue;
1732 $dao->selectAdd('id');
1733 if (!$dao->find()) {
1734 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1739 * Validate foreign constraint fields being passed into API.
1741 * @param array $params
1742 * Params from civicrm_api.
1743 * @param string $fieldName
1744 * Uniquename of field being checked.
1748 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1749 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1750 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1753 $existing = civicrm_api($params['entity'], 'get', array(
1754 'version' => $params['version'],
1755 $fieldName => $fieldValue,
1757 // an entry already exists for this unique field
1758 if ($existing['count'] == 1) {
1759 // question - could this ever be a security issue?
1760 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1765 * Generic implementation of the "replace" action.
1767 * Replace the old set of entities (matching some given keys) with a new set of
1768 * entities (matching the same keys).
1770 * @note This will verify that 'values' is present, but it does not directly verify
1771 * any other parameters.
1773 * @param string $entity
1775 * @param array $params
1776 * Params from civicrm_api, including:.
1777 * - 'values': an array of records to save
1778 * - all other items: keys which identify new/pre-existing records.
1782 function _civicrm_api3_generic_replace($entity, $params) {
1784 $transaction = new CRM_Core_Transaction();
1786 if (!is_array($params['values'])) {
1787 throw new Exception("Mandatory key(s) missing from params array: values");
1790 // Extract the keys -- somewhat scary, don't think too hard about it
1791 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1793 // Lookup pre-existing records
1794 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1795 if (civicrm_error($preexisting)) {
1796 $transaction->rollback();
1797 return $preexisting;
1800 // Save the new/updated records
1802 foreach ($params['values'] as $replacement) {
1803 // Sugar: Don't force clients to duplicate the 'key' data
1804 $replacement = array_merge($baseParams, $replacement);
1805 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
1806 $create = civicrm_api($entity, $action, $replacement);
1807 if (civicrm_error($create)) {
1808 $transaction->rollback();
1811 foreach ($create['values'] as $entity_id => $entity_value) {
1812 $creates[$entity_id] = $entity_value;
1816 // Remove stale records
1817 $staleIDs = array_diff(
1818 array_keys($preexisting['values']),
1819 array_keys($creates)
1821 foreach ($staleIDs as $staleID) {
1822 $delete = civicrm_api($entity, 'delete', array(
1823 'version' => $params['version'],
1826 if (civicrm_error($delete)) {
1827 $transaction->rollback();
1832 return civicrm_api3_create_success($creates, $params);
1834 catch(PEAR_Exception
$e) {
1835 $transaction->rollback();
1836 return civicrm_api3_create_error($e->getMessage());
1838 catch(Exception
$e) {
1839 $transaction->rollback();
1840 return civicrm_api3_create_error($e->getMessage());
1845 * Replace base parameters.
1847 * @param array $params
1851 function _civicrm_api3_generic_replace_base_params($params) {
1852 $baseParams = $params;
1853 unset($baseParams['values']);
1854 unset($baseParams['sequential']);
1855 unset($baseParams['options']);
1860 * Returns fields allowable by api.
1863 * String Entity to query.
1864 * @param bool $unique
1865 * Index by unique fields?.
1866 * @param array $params
1870 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1871 $unsetIfEmpty = array(
1878 $dao = _civicrm_api3_get_DAO($entity);
1883 $fields = $d->fields();
1885 // Set html attributes for text fields
1886 foreach ($fields as $name => &$field) {
1887 if (isset($field['html'])) {
1888 $field['html'] +
= (array) $d::makeAttribute($field);
1892 // replace uniqueNames by the normal names as the key
1893 if (empty($unique)) {
1894 foreach ($fields as $name => &$field) {
1895 //getting rid of unused attributes
1896 foreach ($unsetIfEmpty as $attr) {
1897 if (empty($field[$attr])) {
1898 unset($field[$attr]);
1901 if ($name == $field['name']) {
1904 if (array_key_exists($field['name'], $fields)) {
1905 $field['error'] = 'name conflict';
1906 // it should never happen, but better safe than sorry
1909 $fields[$field['name']] = $field;
1910 $fields[$field['name']]['uniqueName'] = $name;
1911 unset($fields[$name]);
1914 // Translate FKClassName to the corresponding api
1915 foreach ($fields as $name => &$field) {
1916 if (!empty($field['FKClassName'])) {
1917 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
1919 $field['FKApiName'] = $FKApi;
1923 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
1928 * Return an array of fields for a given entity.
1930 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1933 * @param array $params
1937 function _civicrm_api_get_custom_fields($entity, &$params) {
1938 $entity = _civicrm_api_get_camel_name($entity);
1939 if ($entity == 'Contact') {
1940 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1941 $entity = CRM_Utils_Array
::value('contact_type', $params);
1943 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
1946 // we could / should probably test for other subtypes here - e.g. activity_type_id
1947 CRM_Utils_Array
::value('contact_sub_type', $params),
1956 foreach ($customfields as $key => $value) {
1957 // Regular fields have a 'name' property
1958 $value['name'] = 'custom_' . $key;
1959 $value['title'] = $value['label'];
1960 $value['type'] = _getStandardTypeFromCustomDataType($value);
1961 $ret['custom_' . $key] = $value;
1967 * Translate the custom field data_type attribute into a std 'type'.
1969 * @param array $value
1973 function _getStandardTypeFromCustomDataType($value) {
1974 $dataType = $value['data_type'];
1975 //CRM-15792 - If date custom field contains timeformat change type to DateTime
1976 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
1977 $dataType = 'DateTime';
1980 'String' => CRM_Utils_Type
::T_STRING
,
1981 'Int' => CRM_Utils_Type
::T_INT
,
1982 'Money' => CRM_Utils_Type
::T_MONEY
,
1983 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
1984 'Float' => CRM_Utils_Type
::T_FLOAT
,
1985 'Date' => CRM_Utils_Type
::T_DATE
,
1986 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
1987 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
1988 'StateProvince' => CRM_Utils_Type
::T_INT
,
1989 'File' => CRM_Utils_Type
::T_STRING
,
1990 'Link' => CRM_Utils_Type
::T_STRING
,
1991 'ContactReference' => CRM_Utils_Type
::T_INT
,
1992 'Country' => CRM_Utils_Type
::T_INT
,
1994 return $mapping[$dataType];
1999 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
2001 * If multiple aliases the last takes precedence
2003 * Function also swaps unique fields for non-unique fields & vice versa.
2005 * @param $apiRequest
2008 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2009 foreach ($fields as $field => $values) {
2010 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2011 if (!empty($values['api.aliases'])) {
2012 // if aliased field is not set we try to use field alias
2013 if (!isset($apiRequest['params'][$field])) {
2014 foreach ($values['api.aliases'] as $alias) {
2015 if (isset($apiRequest['params'][$alias])) {
2016 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2018 //unset original field nb - need to be careful with this as it may bring inconsistencies
2019 // out of the woodwork but will be implementing only as _spec function extended
2020 unset($apiRequest['params'][$alias]);
2024 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2025 && isset($apiRequest['params'][$values['name']])
2027 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2028 // note that it would make sense to unset the original field here but tests need to be in place first
2029 if ($field != 'domain_version') {
2030 unset($apiRequest['params'][$values['name']]);
2033 if (!isset($apiRequest['params'][$field])
2035 && $field != $uniqueName
2036 && array_key_exists($uniqueName, $apiRequest['params'])
2038 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2039 // note that it would make sense to unset the original field here but tests need to be in place first
2046 * Validate integer fields being passed into API.
2048 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2050 * @param array $params
2051 * Params from civicrm_api.
2052 * @param string $fieldName
2053 * Uniquename of field being checked.
2054 * @param array $fieldInfo
2055 * Array of fields from getfields function.
2056 * @param string $entity
2058 * @throws API_Exception
2060 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
2061 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2062 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2066 if (!empty($fieldValue)) {
2067 // if value = 'user_contact_id' (or similar), replace value with contact id
2068 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2069 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2070 if ('unknown-user' === $realContactId) {
2071 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
2073 elseif (is_numeric($realContactId)) {
2074 $fieldValue = $realContactId;
2077 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2078 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2081 // After swapping options, ensure we have an integer(s)
2082 foreach ((array) ($fieldValue) as $value) {
2083 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
2084 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
2088 // Check our field length
2089 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2091 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2092 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
2098 $params[$fieldName][$op] = $fieldValue;
2101 $params[$fieldName] = $fieldValue;
2106 * Determine a contact ID using a string expression.
2108 * @param string $contactIdExpr
2109 * E.g. "user_contact_id" or "@user:username".
2111 * @return int|NULL|'unknown-user'
2113 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2114 // If value = 'user_contact_id' replace value with logged in user id.
2115 if ($contactIdExpr == "user_contact_id") {
2116 return CRM_Core_Session
::getLoggedInContactID();
2118 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2119 $config = CRM_Core_Config
::singleton();
2121 $ufID = $config->userSystem
->getUfId($matches[1]);
2123 return 'unknown-user';
2126 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2128 return 'unknown-user';
2137 * Validate html (check for scripting attack).
2139 * @param array $params
2140 * @param string $fieldName
2141 * @param array $fieldInfo
2143 * @throws API_Exception
2145 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2146 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2147 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2151 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2152 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
2158 * Validate string fields being passed into API.
2160 * @param array $params
2161 * Params from civicrm_api.
2162 * @param string $fieldName
2163 * Uniquename of field being checked.
2164 * @param array $fieldInfo
2165 * Array of fields from getfields function.
2166 * @param string $entity
2168 * @throws API_Exception
2171 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2172 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2173 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2177 if (!is_array($fieldValue)) {
2178 $fieldValue = (string) $fieldValue;
2181 //@todo what do we do about passed in arrays. For many of these fields
2182 // the missing piece of functionality is separating them to a separated string
2183 // & many save incorrectly. But can we change them wholesale?
2186 foreach ((array) $fieldValue as $value) {
2187 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2188 throw new Exception('Input contains illegal SCRIPT tag.');
2190 if ($fieldName == 'currency') {
2191 //When using IN operator $fieldValue is a array of currency codes
2192 if (!CRM_Utils_Rule
::currencyCode($value)) {
2193 throw new Exception("Currency not a valid code: $currency");
2198 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2199 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2201 // Check our field length
2202 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2203 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2204 2100, array('field' => $fieldName)
2209 $params[$fieldName][$op] = $fieldValue;
2212 $params[$fieldName] = $fieldValue;
2217 * Validate & swap out any pseudoconstants / options.
2219 * @param mixed $fieldValue
2220 * @param string $entity : api entity name
2221 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2222 * @param array $fieldInfo : getfields meta-data
2224 * @throws \API_Exception
2226 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2227 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2230 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2231 // We need to get the options from the entity the field relates to.
2232 $entity = $fieldInfo['entity'];
2234 $options = civicrm_api($entity, 'getoptions', array(
2236 'field' => $fieldInfo['name'],
2237 'context' => 'validate',
2239 $options = CRM_Utils_Array
::value('values', $options, array());
2242 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2244 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2245 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2248 // If passed multiple options, validate each.
2249 if (is_array($fieldValue)) {
2250 foreach ($fieldValue as &$value) {
2251 if (!is_array($value)) {
2252 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2255 // TODO: unwrap the call to implodePadded from the conditional and do it always
2256 // need to verify that this is safe and doesn't break anything though.
2257 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2259 CRM_Utils_Array
::implodePadded($fieldValue);
2263 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2268 * Validate & swap a single option value for a field.
2270 * @param string $value field value
2271 * @param array $options array of options for this field
2272 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2274 * @throws API_Exception
2276 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2277 // If option is a key, no need to translate
2278 // or if no options are avaiable for pseudoconstant 'table' property
2279 if (array_key_exists($value, $options) ||
!$options) {
2283 // Translate value into key
2284 $newValue = array_search($value, $options);
2285 if ($newValue !== FALSE) {
2289 // Case-insensitive matching
2290 $newValue = strtolower($value);
2291 $options = array_map("strtolower", $options);
2292 $newValue = array_search($newValue, $options);
2293 if ($newValue === FALSE) {
2294 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2300 * Returns the canonical name of a field.
2303 * api entity name (string should already be standardized - no camelCase).
2305 * any variation of a field's name (name, unique_name, api.alias).
2307 * @param string $action
2309 * @return bool|string
2310 * FieldName or FALSE if the field does not exist
2312 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2316 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2319 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2322 $result = civicrm_api($entity, 'getfields', array(
2324 'action' => $action,
2326 $meta = $result['values'];
2327 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2328 $fieldName = $fieldName . '_id';
2330 if (isset($meta[$fieldName])) {
2331 return $meta[$fieldName]['name'];
2333 foreach ($meta as $info) {
2334 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2335 return $info['name'];
2337 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2338 return $info['name'];
2341 // Create didn't work, try with get
2342 if ($action == 'create') {
2343 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2349 * Check if the function is deprecated.
2351 * @param string $entity
2352 * @param array $result
2354 * @return string|array|null
2356 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2358 $apiFile = "api/v3/$entity.php";
2359 if (CRM_Utils_File
::isIncludable($apiFile)) {
2360 require_once $apiFile;
2362 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2363 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2364 if (function_exists($fnName)) {
2365 return $fnName($result);
2371 * Get the actual field value.
2373 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2374 * So this function returns the actual field value.
2376 * @param array $params
2377 * @param string $fieldName
2378 * @param string $type
2382 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2383 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2386 if (!empty($fieldValue) && is_array($fieldValue) &&
2387 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2388 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2390 $op = key($fieldValue);
2391 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2393 return array($fieldValue, $op);
2397 * A generic "get" API based on simple array data. This is comparable to
2398 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2399 * small/mid-size data loaded from external JSON or XML documents.
2402 * @param array $params
2404 * @param array $records
2405 * List of all records.
2406 * @param string $idCol
2407 * The property which defines the ID of a record
2408 * @param array $fields
2409 * List of filterable fields.
2412 * @throws \API_Exception
2414 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) {
2415 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2416 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2417 $offset = CRM_Utils_Array
::value('offset', $options);
2418 $limit = CRM_Utils_Array
::value('limit', $options);
2423 foreach ($records as $record) {
2424 if ($idCol != 'id') {
2425 $record['id'] = $record[$idCol];
2428 foreach ($params as $k => $v) {
2432 if (in_array($k, $fields) && $record[$k] != $v) {
2438 if ($currentOffset >= $offset) {
2439 $matches[$record[$idCol]] = $record;
2441 if ($limit && count($matches) >= $limit) {
2448 $return = CRM_Utils_Array
::value('return', $options, array());
2449 if (!empty($return)) {
2451 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2454 return civicrm_api3_create_success($matches, $params);
2458 * @param string $bao_name
2459 * @param array $params
2460 * @throws \Civi\API\Exception\UnauthorizedException
2462 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2463 // For lack of something more clever, here's a whitelist of entities whos permissions
2464 // are inherited from a contact record.
2465 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2466 $contactEntities = array(
2467 'CRM_Core_BAO_Email',
2468 'CRM_Core_BAO_Phone',
2469 'CRM_Core_BAO_Address',
2471 'CRM_Core_BAO_Website',
2473 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2474 $cid = !empty($params['contact_id']) ?
$params['contact_id'] : CRM_Core_DAO
::getFieldValue($bao_name, $params['id'], 'contact_id');
2475 if (!CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
2476 throw new \Civi\API\Exception\
UnauthorizedException('Permission denied to modify contact record');