3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * CiviCRM APIv3 utility functions.
31 * @package CiviCRM_APIv3
35 * Initialize CiviCRM - should be run at the start of each API function.
37 function _civicrm_api3_initialize() {
38 require_once 'CRM/Core/ClassLoader.php';
39 CRM_Core_ClassLoader
::singleton()->register();
40 CRM_Core_Config
::singleton();
44 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
46 * @param array $params
47 * Array of fields to check.
48 * @param array $daoName
49 * String DAO to check for required fields (create functions only).
50 * @param array $keyoptions
51 * List of required fields options. One of the options is required.
53 function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
54 $keys = array(array());
55 foreach ($keyoptions as $key) {
58 civicrm_api3_verify_mandatory($params, $daoName, $keys);
62 * Check mandatory fields are included.
64 * @param array $params
65 * Array of fields to check.
66 * @param array $daoName
67 * String DAO to check for required fields (create functions only).
69 * List of required fields. A value can be an array denoting that either this or that is required.
70 * @param bool $verifyDAO
72 * @throws \API_Exception
74 function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
77 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
78 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
79 if (!is_array($unmatched)) {
84 if (!empty($params['id'])) {
85 $keys = array('version');
88 if (!in_array('version', $keys)) {
89 // required from v3 onwards
93 foreach ($keys as $key) {
97 foreach ($key as $subkey) {
98 if (!array_key_exists($subkey, $params) ||
empty($params[$subkey])) {
99 $optionset[] = $subkey;
102 // as long as there is one match then we don't need to rtn anything
106 if (empty($match) && !empty($optionset)) {
107 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
111 // Disallow empty values except for the number zero.
112 // TODO: create a utility for this since it's needed in many places
113 if (!array_key_exists($key, $params) ||
(empty($params[$key]) && $params[$key] !== 0 && $params[$key] !== '0')) {
118 if (!empty($unmatched)) {
119 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
124 * Create error array.
131 function civicrm_api3_create_error($msg, $data = array()) {
132 $data['is_error'] = 1;
133 $data['error_message'] = $msg;
134 // we will show sql to privileged user only (not sure of a specific
135 // security hole here but seems sensible - perhaps should apply to the trace as well?)
136 if (isset($data['sql']) && CRM_Core_Permission
::check('Administer CiviCRM')) {
137 // Isn't this redundant?
138 $data['debug_information'] = $data['sql'];
147 * Format array in result output style.
149 * @param array|int $values values generated by API operation (the result)
150 * @param array $params
151 * Parameters passed into API call.
152 * @param string $entity
153 * The entity being acted on.
154 * @param string $action
155 * The action passed to the API.
157 * DAO object to be freed here.
158 * @param array $extraReturnValues
159 * Additional values to be added to top level of result array(.
160 * - this param is currently used for legacy behaviour support
164 function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
166 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
167 // TODO: This shouldn't be necessary but this fn sometimes gets called with lowercase entity
168 $entity = _civicrm_api_get_camel_name($entity);
169 $result['is_error'] = 0;
170 //lets set the ['id'] field if it's not set & we know what the entity is
171 if (is_array($values) && $entity && $action != 'getfields') {
172 foreach ($values as $key => $item) {
173 if (empty($item['id']) && !empty($item[$lowercase_entity . "_id"])) {
174 $values[$key]['id'] = $item[$lowercase_entity . "_id"];
176 if (!empty($item['financial_type_id'])) {
177 //4.3 legacy handling
178 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
180 if (!empty($item['next_sched_contribution_date'])) {
181 // 4.4 legacy handling
182 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
187 if (is_array($params) && !empty($params['debug'])) {
188 if (is_string($action) && $action != 'getfields') {
189 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) +
$params);
191 elseif ($action != 'getfields') {
192 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) +
$params);
198 $allFields = array();
199 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array
::value('values', $apiFields))) {
200 $allFields = array_keys($apiFields['values']);
202 $paramFields = array_keys($params);
203 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array(
222 $result['undefined_fields'] = array_merge($undefined);
225 if (is_object($dao)) {
229 $result['version'] = 3;
230 if (is_array($values)) {
231 $result['count'] = (int) count($values);
233 // Convert value-separated strings to array
234 if ($action != 'getfields') {
235 _civicrm_api3_separate_values($values);
238 if ($result['count'] == 1) {
239 list($result['id']) = array_keys($values);
241 elseif (!empty($values['id']) && is_int($values['id'])) {
242 $result['id'] = $values['id'];
246 $result['count'] = !empty($values) ?
1 : 0;
249 if (is_array($values) && isset($params['sequential']) &&
250 $params['sequential'] == 1
252 $result['values'] = array_values($values);
255 $result['values'] = $values;
257 if (!empty($params['options']['metadata'])) {
258 // We've made metadata an array but only supporting 'fields' atm.
259 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
260 $fields = civicrm_api3($entity, 'getfields', array(
261 'action' => substr($action, 0, 3) == 'get' ?
'get' : 'create',
263 $result['metadata']['fields'] = $fields['values'];
266 // Report deprecations.
267 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
268 // Always report "setvalue" action as deprecated.
269 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'setvalue')) {
270 $deprecated = ((array) $deprecated) +
array('setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.');
272 // Always report "update" action as deprecated.
273 if (!is_string($deprecated) && ($action == 'getactions' ||
$action == 'update')) {
274 $deprecated = ((array) $deprecated) +
array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
277 // Metadata-level deprecations or wholesale entity deprecations.
278 if ($entity == 'Entity' ||
$action == 'getactions' ||
is_string($deprecated)) {
279 $result['deprecated'] = $deprecated;
281 // Action-specific deprecations
282 elseif (!empty($deprecated[$action])) {
283 $result['deprecated'] = $deprecated[$action];
286 return array_merge($result, $extraReturnValues);
290 * Load the DAO of the entity.
296 function _civicrm_api3_load_DAO($entity) {
297 $dao = _civicrm_api3_get_DAO($entity);
306 * Return the DAO of the function or Entity.
308 * @param string $name
309 * Either a function of the api (civicrm_{entity}_create or the entity name.
310 * return the DAO name to manipulate this function
311 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
313 * @return mixed|string
315 function _civicrm_api3_get_DAO($name) {
316 if (strpos($name, 'civicrm_api3') !== FALSE) {
317 $last = strrpos($name, '_');
318 // len ('civicrm_api3_') == 13
319 $name = substr($name, 13, $last - 13);
322 $name = _civicrm_api_get_camel_name($name);
324 if ($name == 'Individual' ||
$name == 'Household' ||
$name == 'Organization') {
328 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
330 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
331 if ($name == 'MailingEventQueue') {
332 return 'CRM_Mailing_Event_DAO_Queue';
334 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
335 // but am not confident mailing_recipients is tested so have not tackled.
336 if ($name == 'MailingRecipients') {
337 return 'CRM_Mailing_DAO_Recipients';
339 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
340 if ($name == 'MailingComponent') {
341 return 'CRM_Mailing_DAO_Component';
343 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
344 if ($name == 'AclRole') {
345 return 'CRM_ACL_DAO_EntityRole';
347 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
348 // But this would impact SMS extensions so need to coordinate
349 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
350 if ($name == 'SmsProvider') {
351 return 'CRM_SMS_DAO_Provider';
353 // FIXME: DAO names should follow CamelCase convention
354 if ($name == 'Im' ||
$name == 'Acl') {
355 $name = strtoupper($name);
357 $dao = CRM_Core_DAO_AllCoreTables
::getFullName($name);
358 if ($dao ||
!$name) {
362 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
363 if (file_exists("api/v3/$name.php")) {
364 include_once "api/v3/$name.php";
367 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
368 if (function_exists($daoFn)) {
376 * Return the DAO of the function or Entity.
378 * @param string $name
379 * Is either a function of the api (civicrm_{entity}_create or the entity name.
380 * return the DAO name to manipulate this function
381 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
385 function _civicrm_api3_get_BAO($name) {
386 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
387 if ($name == 'PrintLabel') {
388 return 'CRM_Badge_BAO_Layout';
390 $dao = _civicrm_api3_get_DAO($name);
394 $bao = str_replace("DAO", "BAO", $dao);
395 $file = strtr($bao, '_', '/') . '.php';
396 // Check if this entity actually has a BAO. Fall back on the DAO if not.
397 return stream_resolve_include_path($file) ?
$bao : $dao;
401 * Recursive function to explode value-separated strings into arrays.
405 function _civicrm_api3_separate_values(&$values) {
406 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
407 foreach ($values as $key => & $value) {
408 if (is_array($value)) {
409 _civicrm_api3_separate_values($value);
411 elseif (is_string($value)) {
412 // This is to honor the way case API was originally written.
413 if ($key == 'case_type_id') {
414 $value = trim(str_replace($sp, ',', $value), ',');
416 elseif (strpos($value, $sp) !== FALSE) {
417 $value = explode($sp, trim($value, $sp));
424 * This is a legacy wrapper for api_store_values.
426 * It checks suitable fields using getfields rather than DAO->fields.
428 * Getfields has handling for how to deal with unique names which dao->fields doesn't
430 * Note this is used by BAO type create functions - eg. contribution
432 * @param string $entity
433 * @param array $params
434 * @param array $values
436 function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
437 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
438 $fields = $fields['values'];
439 _civicrm_api3_store_values($fields, $params, $values);
444 * @param array $fields
445 * @param array $params
446 * @param array $values
450 function _civicrm_api3_store_values(&$fields, &$params, &$values) {
453 $keys = array_intersect_key($params, $fields);
454 foreach ($keys as $name => $value) {
455 if ($name !== 'id') {
456 $values[$name] = $value;
464 * Get function for query object api.
466 * This is a simple get function, but it should be usable for any kind of
467 * entity. I created it to work around CRM-16036.
469 * @param string $dao_name
471 * @param array $params
472 * As passed into api get function.
473 * @param bool $isFillUniqueFields
474 * Do we need to ensure unique fields continue to be populated for this api? (backward compatibility).
475 * @param CRM_Utils_SQL_Select|NULL $sqlFragment
479 function _civicrm_api3_get_using_utils_sql($dao_name, $params, $isFillUniqueFields, $sqlFragment) {
481 $dao = new $dao_name();
482 $entity = _civicrm_api_get_entity_name_from_dao($dao);
483 $custom_fields = _civicrm_api3_custom_fields_for_entity($entity);
484 $options = _civicrm_api3_get_options_from_params($params);
486 // Unset $params['options'] if they are api parameters (not options as a fieldname).
487 if (!empty($params['options']) && is_array($params['options'])&& array_intersect(array_keys($params['options']), array_keys($options))) {
488 unset ($params['options']);
491 $entity_field_names = _civicrm_api3_field_names(_civicrm_api3_build_fields_array($dao));
492 $custom_field_names = array();
493 $uniqueAliases = array();
494 $getFieldsResult = civicrm_api3($entity, 'getfields', array('action' => 'get'));
495 $getFieldsResult = $getFieldsResult['values'];
496 foreach ($getFieldsResult as $getFieldKey => $getFieldSpec) {
497 $uniqueAliases[$getFieldKey] = $getFieldSpec['name'];
498 $uniqueAliases[$getFieldSpec['name']] = $getFieldSpec['name'];
501 // $select_fields maps column names to the field names of the result
503 $select_fields = array();
505 // array with elements array('column', 'operator', 'value');
506 $where_clauses = array();
508 // Tables we need to join with to retrieve the custom values.
509 $custom_value_tables = array();
511 // ID's of custom fields that refer to a contact.
512 $contact_reference_field_ids = array();
514 // populate $select_fields
515 $return_all_fields = (empty($options['return']) ||
!is_array($options['return']));
516 $return = $return_all_fields ?
array_fill_keys($entity_field_names, 1) : $options['return'];
519 foreach (array_keys($return) as $field_name) {
520 if (!empty($uniqueAliases[$field_name]) && (CRM_Core_BAO_CustomField
::getKeyID($field_name) == FALSE)) {
521 // 'a.' is an alias for the entity table.
522 $select_fields["a.{$uniqueAliases[$field_name]}"] = $uniqueAliases[$field_name];
527 foreach ($custom_fields as $cf_id => $custom_field) {
528 $field_name = "custom_$cf_id";
529 $custom_field_names[] = $field_name;
530 if ($return_all_fields ||
!empty($options['return'][$field_name])
532 // This is a tested format so we support it.
533 !empty($options['return']['custom'])
535 $table_name = $custom_field["table_name"];
536 $column_name = $custom_field["column_name"];
537 // remember that we will need to join the correct table.
538 if (!in_array($table_name, $custom_value_tables)) {
539 $custom_value_tables[] = $table_name;
541 if ($custom_field["data_type"] != "ContactReference") {
542 // 'ordinary' custom field. We will select the value as custom_XX.
543 $select_fields["$table_name.$column_name"] = $field_name;
546 // contact reference custom field. The ID will be stored in
547 // custom_XX_id. custom_XX will contain the sort name of the
549 $contact_reference_field_ids[] = $cf_id;
550 $select_fields["$table_name.$column_name"] = $field_name . "_id";
551 // We will call the contact table for the join c_XX.
552 $select_fields["c_$cf_id.sort_name"] = $field_name;
556 if (!in_array("a.id", $select_fields)) {
557 // Always select the ID.
558 $select_fields["a.id"] = "id";
561 $query = CRM_Utils_SQL_Select
::from($dao->tableName() . " a");
563 // populate $where_clauses
564 foreach ($params as $key => $value) {
569 if (substr($key, 0, 7) == 'filter.') {
570 // Legacy support for old filter syntax per the test contract.
571 // (Convert the style to the later one & then deal with them).
572 $filterArray = explode('.', $key);
573 $value = array($filterArray[1] => $value);
577 // Legacy support for 'filter's construct.
578 if ($key == 'filters') {
579 foreach ($value as $filterKey => $filterValue) {
580 if (substr($filterKey, -4, 4) == 'high') {
581 $key = substr($filterKey, 0, -5);
582 $value = array('<=' => $filterValue);
585 if (substr($filterKey, -3, 3) == 'low') {
586 $key = substr($filterKey, 0, -4);
587 $value = array('>=' => $filterValue);
590 if ($filterKey == 'is_current' ||
$filterKey == 'isCurrent') {
591 // Is current is almost worth creating as a 'sql filter' in the DAO function since several entities have the
593 $todayStart = date('Ymd000000', strtotime('now'));
594 $todayEnd = date('Ymd235959', strtotime('now'));
595 $query->where(array("(a.start_date <= '$todayStart' OR a.start_date IS NULL) AND (a.end_date >= '$todayEnd' OR
603 if (array_key_exists($key, $getFieldsResult)) {
604 $type = $getFieldsResult[$key]['type'];
605 $key = $getFieldsResult[$key]['name'];
607 if ($key == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
608 // The test contract enforces support of (eg) mailing_group_id if the entity is MailingGroup.
612 if (in_array($key, $entity_field_names)) {
616 elseif (($cf_id = CRM_Core_BAO_CustomField
::getKeyID($key)) != FALSE) {
617 $table_name = $custom_fields[$cf_id]["table_name"];
618 $column_name = $custom_fields[$cf_id]["column_name"];
620 if (!in_array($table_name, $custom_value_tables)) {
621 $custom_value_tables[] = $table_name;
624 // I don't know why I had to specifically exclude 0 as a key - wouldn't the others have caught it?
625 // We normally silently ignore null values passed in - if people want IS_NULL they can use acceptedSqlOperator syntax.
626 if ((!$table_name) ||
empty($key) ||
is_null($value)) {
627 // No valid filter field. This might be a chained call or something.
628 // Just ignore this for the $where_clause.
631 if (!is_array($value)) {
632 $query->where(array("{$table_name}.{$column_name} = @value"), array(
637 // We expect only one element in the array, of the form
638 // "operator" => "rhs".
639 $operator = CRM_Utils_Array
::first(array_keys($value));
640 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
642 "{$table_name}.{$column_name} = @value"), array("@value" => $value)
646 $query->where(CRM_Core_DAO
::createSQLFilter("{$table_name}.{$column_name}", $value, $type));
652 if (!$options['is_count']) {
653 foreach ($select_fields as $column => $alias) {
655 $query = $query->select("!column_$i as !alias_$i", array(
656 "!column_$i" => $column,
657 "!alias_$i" => $alias,
662 $query->select("count(*) as c");
665 // join with custom value tables
666 foreach ($custom_value_tables as $table_name) {
668 $query = $query->join(
670 "LEFT OUTER JOIN !table_name_$i ON !table_name_$i.entity_id = a.id",
671 array("!table_name_$i" => $table_name)
675 // join with contact for contact reference fields
676 foreach ($contact_reference_field_ids as $field_id) {
678 $query = $query->join(
679 "!contact_table_name$i",
680 "LEFT OUTER JOIN civicrm_contact !contact_table_name_$i ON !contact_table_name_$i.id = !values_table_name_$i.!column_name_$i",
682 "!contact_table_name_$i" => "c_$field_id",
683 "!values_table_name_$i" => $custom_fields[$field_id]["table_name"],
684 "!column_name_$i" => $custom_fields[$field_id]["column_name"],
688 foreach ($where_clauses as $clause) {
690 if (substr($clause[1], -4) == "NULL") {
691 $query->where("!columnName_$i !nullThing_$i", array(
692 "!columnName_$i" => $clause[0],
693 "!nullThing_$i" => $clause[1],
697 $query->where("!columnName_$i !operator_$i @value_$i", array(
698 "!columnName_$i" => $clause[0],
699 "!operator_$i" => $clause[1],
700 "@value_$i" => $clause[2],
704 if (!empty($sqlFragment)) {
705 $query->merge($sqlFragment);
709 if (!empty($options['sort'])) {
710 $sort_fields = array();
711 foreach (explode(',', $options['sort']) as $sort_option) {
712 $words = preg_split("/[\s]+/", $sort_option);
713 if (count($words) > 0 && in_array($words[0], array_values($select_fields))) {
715 if (!empty($words[1]) && strtoupper($words[1]) == 'DESC') {
718 $sort_fields[] = $tmp;
721 if (count($sort_fields) > 0) {
722 $query->orderBy(implode(",", $sort_fields));
727 if (!empty($options['limit']) ||
!empty($options['offset'])) {
728 $query->limit($options['limit'], $options['offset']);
731 $result_entities = array();
732 $result_dao = CRM_Core_DAO
::executeQuery($query->toSQL());
734 while ($result_dao->fetch()) {
735 if ($options['is_count']) {
737 return (int) $result_dao->c
;
739 $result_entities[$result_dao->id
] = array();
740 foreach ($select_fields as $column => $alias) {
741 if (property_exists($result_dao, $alias) && $result_dao->$alias != NULL) {
742 $result_entities[$result_dao->id
][$alias] = $result_dao->$alias;
744 // Backward compatibility on fields names.
745 if ($isFillUniqueFields && !empty($getFieldsResult['values'][$column]['uniqueName'])) {
746 $result_entities[$result_dao->id
][$getFieldsResult['values'][$column]['uniqueName']] = $result_dao->$alias;
748 foreach ($getFieldsResult as $returnName => $spec) {
749 if (empty($result_entities[$result_dao->id
][$returnName]) && !empty($result_entities[$result_dao->id
][$spec['name']])) {
750 $result_entities[$result_dao->id
][$returnName] = $result_entities[$result_dao->id
][$spec['name']];
756 return $result_entities;
760 * Returns field names of the given entity fields.
762 * @param array $fields
763 * Fields array to retrieve the field names for.
766 function _civicrm_api3_field_names($fields) {
768 foreach ($fields as $key => $value) {
769 if (!empty($value['name'])) {
770 $result[] = $value['name'];
777 * Returns an array with database information for the custom fields of an
780 * Something similar might already exist in CiviCRM. But I was not
783 * @param string $entity
786 * an array that maps the custom field ID's to table name and
790 * 'table_name' => 'table_name_1',
791 * 'column_name' => 'column_name_1',
792 * 'data_type' => 'data_type_1',
796 function _civicrm_api3_custom_fields_for_entity($entity) {
800 SELECT f.id, f.label, f.data_type,
801 f.html_type, f.is_search_range,
802 f.option_group_id, f.custom_group_id,
803 f.column_name, g.table_name,
804 f.date_format,f.time_format
805 FROM civicrm_custom_field f
806 JOIN civicrm_custom_group g ON f.custom_group_id = g.id
807 WHERE g.is_active = 1
812 '1' => array($entity, 'String'),
815 $dao = CRM_Core_DAO
::executeQuery($query, $params);
816 while ($dao->fetch()) {
817 $result[$dao->id
] = array(
818 'table_name' => $dao->table_name
,
819 'column_name' => $dao->column_name
,
820 'data_type' => $dao->data_type
,
829 * Get function for query object api.
831 * The API supports 2 types of get request. The more complex uses the BAO query object.
832 * This is a generic function for those functions that call it
834 * At the moment only called by contact we should extend to contribution &
835 * others that use the query object. Note that this function passes permission information in.
838 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
842 * @param array $params
843 * As passed into api get or getcount function.
844 * @param array $additional_options
845 * Array of options (so we can modify the filter).
846 * @param bool $getCount
847 * Are we just after the count.
851 function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
852 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
853 // Convert id to e.g. contact_id
854 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
855 $params[$lowercase_entity . '_id'] = $params['id'];
857 unset($params['id']);
859 $options = _civicrm_api3_get_options_from_params($params, TRUE);
861 $inputParams = array_merge(
862 CRM_Utils_Array
::value('input_params', $options, array()),
863 CRM_Utils_Array
::value('input_params', $additional_options, array())
865 $returnProperties = array_merge(
866 CRM_Utils_Array
::value('return', $options, array()),
867 CRM_Utils_Array
::value('return', $additional_options, array())
869 if (empty($returnProperties)) {
870 $returnProperties = NULL;
872 if (!empty($params['check_permissions'])) {
873 // we will filter query object against getfields
874 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
875 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
876 $fields['values'][$lowercase_entity . '_id'] = array();
877 $varsToFilter = array('returnProperties', 'inputParams');
878 foreach ($varsToFilter as $varToFilter) {
879 if (!is_array($
$varToFilter)) {
882 //I was going to throw an exception rather than silently filter out - but
883 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
884 //so we are silently ignoring parts of their request
885 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
886 $
$varToFilter = array_intersect_key($
$varToFilter, $fields['values']);
889 $options = array_merge($options, $additional_options);
890 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
891 $offset = CRM_Utils_Array
::value('offset', $options, NULL);
892 $limit = CRM_Utils_Array
::value('limit', $options, NULL);
893 $smartGroupCache = CRM_Utils_Array
::value('smartGroupCache', $params);
897 $returnProperties = NULL;
900 if (substr($sort, 0, 2) == 'id') {
901 $sort = $lowercase_entity . "_" . $sort;
904 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams);
906 $skipPermissions = !empty($params['check_permissions']) ?
0 : 1;
908 list($entities, $options) = CRM_Contact_BAO_Query
::apiQuery(
920 // only return the count of contacts
928 * Get dao query object based on input params.
930 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
933 * @param array $params
934 * @param string $mode
935 * @param string $entity
938 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
940 function _civicrm_api3_get_query_object($params, $mode, $entity) {
941 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
942 $sort = CRM_Utils_Array
::value('sort', $options, NULL);
943 $offset = CRM_Utils_Array
::value('offset', $options);
944 $rowCount = CRM_Utils_Array
::value('limit', $options);
945 $inputParams = CRM_Utils_Array
::value('input_params', $options, array());
946 $returnProperties = CRM_Utils_Array
::value('return', $options, NULL);
947 if (empty($returnProperties)) {
948 $returnProperties = CRM_Contribute_BAO_Query
::defaultReturnProperties($mode);
951 $newParams = CRM_Contact_BAO_Query
::convertFormValues($inputParams, 0, FALSE, $entity);
952 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
954 empty($params['check_permissions'])
956 list($select, $from, $where, $having) = $query->query();
958 $sql = "$select $from $where $having";
961 $sql .= " ORDER BY $sort ";
963 if (!empty($rowCount)) {
964 $sql .= " LIMIT $offset, $rowCount ";
966 $dao = CRM_Core_DAO
::executeQuery($sql);
967 return array($dao, $query);
971 * Function transfers the filters being passed into the DAO onto the params object.
973 * @deprecated DAO based retrieval is being phased out.
975 * @param CRM_Core_DAO $dao
976 * @param array $params
977 * @param bool $unique
978 * @param array $extraSql
979 * API specific queries eg for event isCurrent would be converted to
980 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
982 * @throws API_Exception
985 function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = array()) {
986 $entity = _civicrm_api_get_entity_name_from_dao($dao);
987 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
988 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
989 //if entity_id is set then treat it as ID (will be overridden by id if set)
990 $params['id'] = $params[$lowercase_entity . "_id"];
992 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
993 $fields = array_intersect(array_keys($allfields), array_keys($params));
995 $options = _civicrm_api3_get_options_from_params($params);
996 //apply options like sort
997 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
999 //accept filters like filter.activity_date_time_high
1000 // std is now 'filters' => ..
1001 if (strstr(implode(',', array_keys($params)), 'filter')) {
1002 if (isset($params['filters']) && is_array($params['filters'])) {
1003 foreach ($params['filters'] as $paramkey => $paramvalue) {
1004 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
1008 foreach ($params as $paramkey => $paramvalue) {
1009 if (strstr($paramkey, 'filter')) {
1010 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
1019 foreach ($fields as $field) {
1020 if (is_array($params[$field])) {
1021 //get the actual fieldname from db
1022 $fieldName = $allfields[$field]['name'];
1023 $where = CRM_Core_DAO
::createSqlFilter($fieldName, $params[$field], 'String');
1024 if (!empty($where)) {
1025 $dao->whereAdd($where);
1030 $daoFieldName = $allfields[$field]['name'];
1031 if (empty($daoFieldName)) {
1032 throw new API_Exception("Failed to determine field name for \"$field\"");
1034 $dao->{$daoFieldName} = $params[$field];
1037 $dao->$field = $params[$field];
1041 if (!empty($extraSql['where'])) {
1042 foreach ($extraSql['where'] as $table => $sqlWhere) {
1043 foreach ($sqlWhere as $where) {
1044 $dao->whereAdd($where);
1048 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
1050 // Ensure 'id' is included.
1051 $options['return']['id'] = TRUE;
1052 $allfields = _civicrm_api3_get_unique_name_array($dao);
1053 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
1054 foreach ($returnMatched as $returnValue) {
1055 $dao->selectAdd($returnValue);
1058 // Not already matched on the field names.
1059 $unmatchedFields = array_diff(
1060 array_keys($options['return']),
1064 $returnUniqueMatched = array_intersect(
1066 // But a match for the field keys.
1067 array_flip($allfields)
1069 foreach ($returnUniqueMatched as $uniqueVal) {
1070 $dao->selectAdd($allfields[$uniqueVal]);
1073 $dao->setApiFilter($params);
1077 * Apply filters (e.g. high, low) to DAO object (prior to find).
1079 * @param string $filterField
1080 * Field name of filter.
1081 * @param string $filterValue
1082 * Field value of filter.
1083 * @param object $dao
1086 function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
1087 if (strstr($filterField, 'high')) {
1088 $fieldName = substr($filterField, 0, -5);
1089 $dao->whereAdd("($fieldName <= $filterValue )");
1091 if (strstr($filterField, 'low')) {
1092 $fieldName = substr($filterField, 0, -4);
1093 $dao->whereAdd("($fieldName >= $filterValue )");
1095 if ($filterField == 'is_current' && $filterValue == 1) {
1096 $todayStart = date('Ymd000000', strtotime('now'));
1097 $todayEnd = date('Ymd235959', strtotime('now'));
1098 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
1099 if (property_exists($dao, 'is_active')) {
1100 $dao->whereAdd('is_active = 1');
1106 * Get sort, limit etc options from the params - supporting old & new formats.
1108 * Get returnProperties for legacy
1110 * @param array $params
1111 * Params array as passed into civicrm_api.
1112 * @param bool $queryObject
1113 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
1114 * for legacy report & return a unique fields array
1116 * @param string $entity
1117 * @param string $action
1119 * @throws API_Exception
1121 * options extracted from params
1123 function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
1124 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
1126 $sort = CRM_Utils_Array
::value('sort', $params, 0);
1127 $sort = CRM_Utils_Array
::value('option.sort', $params, $sort);
1128 $sort = CRM_Utils_Array
::value('option_sort', $params, $sort);
1130 $offset = CRM_Utils_Array
::value('offset', $params, 0);
1131 $offset = CRM_Utils_Array
::value('option.offset', $params, $offset);
1132 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
1133 $offset = CRM_Utils_Array
::value('option_offset', $params, $offset);
1135 $limit = CRM_Utils_Array
::value('rowCount', $params, 25);
1136 $limit = CRM_Utils_Array
::value('option.limit', $params, $limit);
1137 $limit = CRM_Utils_Array
::value('option_limit', $params, $limit);
1139 if (is_array(CRM_Utils_Array
::value('options', $params))) {
1140 // is count is set by generic getcount not user
1141 $is_count = CRM_Utils_Array
::value('is_count', $params['options']);
1142 $offset = CRM_Utils_Array
::value('offset', $params['options'], $offset);
1143 $limit = CRM_Utils_Array
::value('limit', $params['options'], $limit);
1144 $sort = CRM_Utils_Array
::value('sort', $params['options'], $sort);
1147 $returnProperties = array();
1148 // handle the format return =sort_name,display_name...
1149 if (array_key_exists('return', $params)) {
1150 if (is_array($params['return'])) {
1151 $returnProperties = array_fill_keys($params['return'], 1);
1154 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
1155 $returnProperties = array_fill_keys($returnProperties, 1);
1158 if ($entity && $action == 'get') {
1159 if (!empty($returnProperties['id'])) {
1160 $returnProperties[$lowercase_entity . '_id'] = 1;
1161 unset($returnProperties['id']);
1163 switch (trim(strtolower($sort))) {
1167 $sort = str_replace('id', $lowercase_entity . '_id', $sort);
1172 'offset' => CRM_Utils_Rule
::integer($offset) ?
$offset : NULL,
1173 'sort' => CRM_Utils_Rule
::string($sort) ?
$sort : NULL,
1174 'limit' => CRM_Utils_Rule
::integer($limit) ?
$limit : NULL,
1175 'is_count' => $is_count,
1176 'return' => !empty($returnProperties) ?
$returnProperties : array(),
1179 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
1180 throw new API_Exception('invalid string in sort options');
1183 if (!$queryObject) {
1186 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
1187 // if the query object is being used this should be used
1188 $inputParams = array();
1189 $legacyreturnProperties = array();
1191 'sort', 'offset', 'rowCount', 'options', 'return',
1192 'version', 'prettyprint', 'check_permissions', 'sequential',
1194 foreach ($params as $n => $v) {
1195 if (substr($n, 0, 7) == 'return.') {
1196 $legacyreturnProperties[substr($n, 7)] = $v;
1198 elseif ($n == 'id') {
1199 $inputParams[$lowercase_entity . '_id'] = $v;
1201 elseif (in_array($n, $otherVars)) {
1204 $inputParams[$n] = $v;
1205 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
1206 throw new API_Exception('invalid string');
1210 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
1211 $options['input_params'] = $inputParams;
1216 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
1218 * @param array $params
1219 * Params array as passed into civicrm_api.
1220 * @param object $dao
1224 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
1226 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
1227 if (!$options['is_count']) {
1228 if (!empty($options['limit'])) {
1229 $dao->limit((int) $options['offset'], (int) $options['limit']);
1231 if (!empty($options['sort'])) {
1232 $dao->orderBy($options['sort']);
1238 * Build fields array.
1240 * This is the array of fields as it relates to the given DAO
1241 * returns unique fields as keys by default but if set but can return by DB fields
1243 * @param CRM_Core_DAO $bao
1244 * @param bool $unique
1248 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
1249 $fields = $bao->fields();
1251 if (empty($fields['id'])) {
1252 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
1253 $fields['id'] = $fields[$lowercase_entity . '_id'];
1254 unset($fields[$lowercase_entity . '_id']);
1259 foreach ($fields as $field) {
1260 $dbFields[$field['name']] = $field;
1266 * Build fields array.
1268 * This is the array of fields as it relates to the given DAO
1269 * returns unique fields as keys by default but if set but can return by DB fields
1271 * @param CRM_Core_DAO $bao
1275 function _civicrm_api3_get_unique_name_array(&$bao) {
1276 $fields = $bao->fields();
1277 foreach ($fields as $field => $values) {
1278 $uniqueFields[$field] = CRM_Utils_Array
::value('name', $values, $field);
1280 return $uniqueFields;
1284 * Converts an DAO object to an array.
1286 * @deprecated - DAO based retrieval is being phased out.
1288 * @param CRM_Core_DAO $dao
1289 * Object to convert.
1290 * @param array $params
1291 * @param bool $uniqueFields
1292 * @param string $entity
1293 * @param bool $autoFind
1297 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
1299 if (isset($params['options']) && !empty($params['options']['is_count'])) {
1300 return $dao->count();
1305 if ($autoFind && !$dao->find()) {
1309 if (isset($dao->count
)) {
1313 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
1314 while ($dao->fetch()) {
1316 foreach ($fields as $key) {
1317 if (array_key_exists($key, $dao)) {
1318 // not sure on that one
1319 if ($dao->$key !== NULL) {
1320 $tmp[$key] = $dao->$key;
1324 $result[$dao->id
] = $tmp;
1326 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
1327 _civicrm_api3_custom_data_get($result[$dao->id
], $entity, $dao->id
);
1335 * Determine if custom fields need to be retrieved.
1337 * We currently retrieve all custom fields or none at this level so if we know the entity
1338 * && 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
1339 * @todo filter so only required fields are queried
1341 * @param string $entity
1342 * Entity name in CamelCase.
1343 * @param array $params
1347 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1348 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery
::$extendsMap)) {
1351 $options = _civicrm_api3_get_options_from_params($params);
1352 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1353 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1354 if (stristr($returnString, 'custom')) {
1360 * Converts an object to an array.
1362 * @param object $dao
1363 * (reference) object to convert.
1364 * @param array $values
1365 * (reference) array.
1366 * @param array|bool $uniqueFields
1368 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1370 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1371 foreach ($fields as $key => $value) {
1372 if (array_key_exists($key, $dao)) {
1373 $values[$key] = $dao->$key;
1379 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1386 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1387 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1391 * Format custom parameters.
1393 * @param array $params
1394 * @param array $values
1395 * @param string $extends
1396 * Entity that this custom field extends (e.g. contribution, event, contact).
1397 * @param string $entityId
1398 * ID of entity per $extends.
1400 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1401 $values['custom'] = array();
1402 $checkCheckBoxField = FALSE;
1404 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1405 $entity = 'Contact';
1408 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1409 if (!$fields['is_error']) {
1410 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1411 $fields = $fields['values'];
1412 $checkCheckBoxField = TRUE;
1415 foreach ($params as $key => $value) {
1416 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE);
1417 if ($customFieldID && (!is_null($value))) {
1418 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1419 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1422 CRM_Core_BAO_CustomField
::formatCustomField($customFieldID, $values['custom'],
1423 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1430 * Format parameters for create action.
1432 * @param array $params
1435 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1436 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1438 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery
::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1439 if (!array_key_exists($entity, $customFieldEntities)) {
1443 _civicrm_api3_custom_format_params($params, $values, $entity);
1444 $params = array_merge($params, $values);
1448 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1450 * We should look at pushing to BAO function
1451 * 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
1452 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1454 * 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
1455 * don't touch - lots of very cautious code in here
1457 * The resulting array should look like
1463 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1465 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1466 * be fixed in future
1468 * @param mixed $checkboxFieldValue
1469 * @param string $customFieldLabel
1470 * @param string $entity
1472 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1474 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
1475 // We can assume it's pre-formatted.
1478 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1479 if (!empty($options['is_error'])) {
1480 // The check is precautionary - can probably be removed later.
1484 $options = $options['values'];
1486 if (is_array($checkboxFieldValue)) {
1487 foreach ($checkboxFieldValue as $key => $value) {
1488 if (!array_key_exists($key, $options)) {
1489 $validValue = FALSE;
1493 // we have been passed an array that is already in the 'odd' custom field format
1498 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1499 // if the array only has one item we'll treat it like any other string
1500 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1501 $possibleValue = reset($checkboxFieldValue);
1503 if (is_string($checkboxFieldValue)) {
1504 $possibleValue = $checkboxFieldValue;
1506 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1507 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $possibleValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
1510 elseif (is_array($checkboxFieldValue)) {
1511 // so this time around we are considering the values in the array
1512 $possibleValues = $checkboxFieldValue;
1513 $formatValue = TRUE;
1515 elseif (stristr($checkboxFieldValue, ',')) {
1516 $formatValue = TRUE;
1517 //lets see if we should separate it - we do this near the end so we
1518 // ensure we have already checked that the comma is not part of a legitimate match
1519 // and of course, we don't make any changes if we don't now have matches
1520 $possibleValues = explode(',', $checkboxFieldValue);
1523 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1527 foreach ($possibleValues as $index => $possibleValue) {
1528 if (array_key_exists($possibleValue, $options)) {
1529 // 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)
1531 elseif (array_key_exists(trim($possibleValue), $options)) {
1532 $possibleValues[$index] = trim($possibleValue);
1535 $formatValue = FALSE;
1539 $checkboxFieldValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $possibleValues) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1544 * This function ensures that we have the right input parameters.
1548 * This function is only called when $dao is passed into verify_mandatory.
1549 * The practice of passing $dao into verify_mandatory turned out to be
1550 * unsatisfactory as the required fields @ the dao level is so different to the abstract
1551 * api level. Hence the intention is to remove this function
1552 * & the associated param from verify_mandatory
1554 * @param array $params
1555 * Associative array of property name/value.
1556 * pairs to insert in new history.
1557 * @param string $daoName
1558 * @param bool $return
1560 * @daoName string DAO to check params against
1563 * Should the missing fields be returned as an array (core error created as default)
1564 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
1566 function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1567 //@deprecated - see notes
1568 if (isset($params['extends'])) {
1569 if (($params['extends'] == 'Activity' ||
1570 $params['extends'] == 'Phonecall' ||
1571 $params['extends'] == 'Meeting' ||
1572 $params['extends'] == 'Group' ||
1573 $params['extends'] == 'Contribution'
1575 ($params['style'] == 'Tab')
1577 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1581 $dao = new $daoName();
1582 $fields = $dao->fields();
1585 foreach ($fields as $k => $v) {
1586 if ($v['name'] == 'id') {
1590 if (!empty($v['required'])) {
1591 // 0 is a valid input for numbers, CRM-8122
1592 if (!isset($params[$k]) ||
(empty($params[$k]) && !($params[$k] === 0))) {
1598 if (!empty($missing)) {
1599 if (!empty($return)) {
1603 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1611 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1613 * @param string $bao_name
1615 * @param array $params
1617 * @param bool $returnAsSuccess
1618 * Return in api success format.
1619 * @param string $entity
1620 * @param CRM_Utils_SQL_Select|NULL $sql
1621 * Extra SQL bits to add to the query. For filtering current events, this might be:
1622 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1623 * @param bool $uniqueFields
1624 * Should unique field names be returned (for backward compatibility)
1628 function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1630 if ($returnAsSuccess) {
1631 return civicrm_api3_create_success(_civicrm_api3_get_using_utils_sql($bao_name, $params, $uniqueFields, $sql), $params, $entity, 'get');
1634 return _civicrm_api3_get_using_utils_sql($bao_name, $params, $uniqueFields, $sql);
1639 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1641 * @param string $bao_name
1642 * Name of BAO Class.
1643 * @param array $params
1644 * Parameters passed into the api call.
1645 * @param string $entity
1646 * Entity - pass in if entity is non-standard & required $ids array.
1648 * @throws API_Exception
1651 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1652 _civicrm_api3_format_params_for_create($params, $entity);
1653 $args = array(&$params);
1655 $ids = array($entity => CRM_Utils_Array
::value('id', $params));
1659 if (method_exists($bao_name, 'create')) {
1661 $fct_name = $bao_name . '::' . $fct;
1662 $bao = call_user_func_array(array($bao_name, $fct), $args);
1664 elseif (method_exists($bao_name, 'add')) {
1666 $fct_name = $bao_name . '::' . $fct;
1667 $bao = call_user_func_array(array($bao_name, $fct), $args);
1670 $fct_name = '_civicrm_api3_basic_create_fallback';
1671 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1674 if (is_null($bao)) {
1675 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1677 elseif (is_a($bao, 'CRM_Core_Error')) {
1678 //some weird circular thing means the error takes itself as an argument
1679 $msg = $bao->getMessages($bao);
1680 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1681 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1682 // so we need to reset the error object here to avoid getting concatenated errors
1683 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1684 CRM_Core_Error
::singleton()->reset();
1685 throw new API_Exception($msg);
1689 _civicrm_api3_object_to_array($bao, $values[$bao->id
]);
1690 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1695 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1697 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1698 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1700 * @param string $bao_name
1701 * @param array $params
1703 * @throws API_Exception
1705 * @return CRM_Core_DAO|NULL
1706 * An instance of the BAO
1708 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1709 $dao_name = get_parent_class($bao_name);
1710 if ($dao_name === 'CRM_Core_DAO' ||
!$dao_name) {
1711 $dao_name = $bao_name;
1713 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($dao_name);
1714 if (empty($entityName)) {
1715 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1716 'class_name' => $bao_name,
1719 $hook = empty($params['id']) ?
'create' : 'edit';
1721 CRM_Utils_Hook
::pre($hook, $entityName, CRM_Utils_Array
::value('id', $params), $params);
1722 $instance = new $dao_name();
1723 $instance->copyValues($params);
1725 CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
1731 * Function to do a 'standard' api del.
1733 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1735 * @param string $bao_name
1736 * @param array $params
1740 * @throws API_Exception
1742 function _civicrm_api3_basic_delete($bao_name, &$params) {
1744 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1745 $args = array(&$params['id']);
1746 if (method_exists($bao_name, 'del')) {
1747 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1748 if ($bao !== FALSE) {
1749 return civicrm_api3_create_success(TRUE);
1751 throw new API_Exception('Could not delete entity id ' . $params['id']);
1753 elseif (method_exists($bao_name, 'delete')) {
1754 $dao = new $bao_name();
1755 $dao->id
= $params['id'];
1757 while ($dao->fetch()) {
1759 return civicrm_api3_create_success();
1763 throw new API_Exception('Could not delete entity id ' . $params['id']);
1767 throw new API_Exception('no delete method found');
1771 * Get custom data for the given entity & Add it to the returnArray.
1773 * This looks like 'custom_123' = 'custom string' AND
1774 * 'custom_123_1' = 'custom string'
1775 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1777 * @param array $returnArray
1778 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1779 * @param string $entity
1780 * E.g membership, event.
1781 * @param int $entity_id
1782 * @param int $groupID
1783 * Per CRM_Core_BAO_CustomGroup::getTree.
1784 * @param int $subType
1785 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1786 * @param string $subName
1787 * Subtype of entity.
1789 function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1790 $groupTree = CRM_Core_BAO_CustomGroup
::getTree($entity,
1791 CRM_Core_DAO
::$_nullObject,
1800 $groupTree = CRM_Core_BAO_CustomGroup
::formatGroupTree($groupTree, 1, CRM_Core_DAO
::$_nullObject);
1801 $customValues = array();
1802 CRM_Core_BAO_CustomGroup
::setDefaults($groupTree, $customValues);
1803 $fieldInfo = array();
1804 foreach ($groupTree as $set) {
1805 $fieldInfo +
= $set['fields'];
1807 if (!empty($customValues)) {
1808 foreach ($customValues as $key => $val) {
1809 // per standard - return custom_fieldID
1810 $id = CRM_Core_BAO_CustomField
::getKeyID($key);
1811 $returnArray['custom_' . $id] = $val;
1813 //not standard - but some api did this so guess we should keep - cheap as chips
1814 $returnArray[$key] = $val;
1816 // Shim to restore legacy behavior of ContactReference custom fields
1817 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1818 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1819 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1826 * Validate fields being passed into API.
1828 * This function relies on the getFields function working accurately
1829 * for the given API. If error mode is set to TRUE then it will also check
1832 * As of writing only date was implemented.
1834 * @param string $entity
1835 * @param string $action
1836 * @param array $params
1838 * @param array $fields
1839 * Response from getfields all variables are the same as per civicrm_api.
1840 * @param bool $errorMode
1841 * ErrorMode do intensive post fail checks?.
1845 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
1846 //CRM-15792 handle datetime for custom fields below code handles chain api call
1847 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1848 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1849 foreach ($chainApikeys as $key => $value) {
1850 if (is_array($params[$key])) {
1851 $chainApiParams = array_intersect_key($fields, $params[$key]);
1852 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1856 $fields = array_intersect_key($fields, $params);
1857 if (!empty($chainApiParams)) {
1858 $fields = array_merge($fields, $chainApiParams);
1860 foreach ($fields as $fieldName => $fieldInfo) {
1861 switch (CRM_Utils_Array
::value('type', $fieldInfo)) {
1862 case CRM_Utils_Type
::T_INT
:
1863 //field is of type integer
1864 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1867 case CRM_Utils_Type
::T_DATE
:
1868 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1869 case CRM_Utils_Type
::T_TIMESTAMP
:
1870 //field is of type date or datetime
1871 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1872 $dateParams = &$params[$customFields[$fieldName]];
1875 $dateParams = &$params;
1877 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1882 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1885 case CRM_Utils_Type
::T_STRING
:
1886 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1889 case CRM_Utils_Type
::T_MONEY
:
1890 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1891 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1894 foreach ((array) $fieldValue as $fieldvalue) {
1895 if (!CRM_Utils_Rule
::money($fieldvalue) && !empty($fieldvalue)) {
1896 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1902 // intensive checks - usually only called after DB level fail
1903 if (!empty($errorMode) && strtolower($action) == 'create') {
1904 if (!empty($fieldInfo['FKClassName'])) {
1905 if (!empty($fieldValue)) {
1906 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
1908 elseif (!empty($fieldInfo['required'])) {
1909 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
1912 if (!empty($fieldInfo['api.unique'])) {
1913 $params['entity'] = $entity;
1914 _civicrm_api3_validate_unique_key($params, $fieldName);
1921 * Validate date fields being passed into API.
1923 * It currently converts both unique fields and DB field names to a mysql date.
1924 * @todo - probably the unique field handling & the if exists handling is now done before this
1925 * function is reached in the wrapper - can reduce this code down to assume we
1926 * are only checking the passed in field
1928 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1929 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1931 * @param array $params
1932 * Params from civicrm_api.
1933 * @param string $fieldName
1934 * Uniquename of field being checked.
1935 * @param array $fieldInfo
1936 * Array of fields from getfields function.
1940 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1941 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1942 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
1945 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1946 if (!empty($params[$fieldInfo['name']])) {
1947 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1949 if ((CRM_Utils_Array
::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1950 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1954 $params[$fieldName][$op] = $fieldValue;
1957 $params[$fieldName] = $fieldValue;
1962 * Convert date into BAO friendly date.
1964 * We accept 'whatever strtotime accepts'
1966 * @param string $dateValue
1967 * @param string $fieldName
1973 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1974 if (is_array($dateValue)) {
1975 foreach ($dateValue as $key => $value) {
1976 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1980 if (strtotime($dateValue) === FALSE) {
1981 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1983 $format = ($fieldType == CRM_Utils_Type
::T_DATE
) ?
'Ymd000000' : 'YmdHis';
1984 return CRM_Utils_Date
::processDate($dateValue, NULL, FALSE, $format);
1988 * Validate foreign constraint fields being passed into API.
1990 * @param mixed $fieldValue
1991 * @param string $fieldName
1992 * Uniquename of field being checked.
1993 * @param array $fieldInfo
1994 * Array of fields from getfields function.
1996 * @throws \API_Exception
1998 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1999 $daoName = $fieldInfo['FKClassName'];
2000 $dao = new $daoName();
2001 $dao->id
= $fieldValue;
2003 $dao->selectAdd('id');
2004 if (!$dao->find()) {
2005 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
2010 * Validate foreign constraint fields being passed into API.
2012 * @param array $params
2013 * Params from civicrm_api.
2014 * @param string $fieldName
2015 * Uniquename of field being checked.
2019 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
2020 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2021 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2024 $existing = civicrm_api($params['entity'], 'get', array(
2025 'version' => $params['version'],
2026 $fieldName => $fieldValue,
2028 // an entry already exists for this unique field
2029 if ($existing['count'] == 1) {
2030 // question - could this ever be a security issue?
2031 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
2036 * Generic implementation of the "replace" action.
2038 * Replace the old set of entities (matching some given keys) with a new set of
2039 * entities (matching the same keys).
2041 * @note This will verify that 'values' is present, but it does not directly verify
2042 * any other parameters.
2044 * @param string $entity
2046 * @param array $params
2047 * Params from civicrm_api, including:.
2048 * - 'values': an array of records to save
2049 * - all other items: keys which identify new/pre-existing records.
2053 function _civicrm_api3_generic_replace($entity, $params) {
2055 $transaction = new CRM_Core_Transaction();
2057 if (!is_array($params['values'])) {
2058 throw new Exception("Mandatory key(s) missing from params array: values");
2061 // Extract the keys -- somewhat scary, don't think too hard about it
2062 $baseParams = _civicrm_api3_generic_replace_base_params($params);
2064 // Lookup pre-existing records
2065 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
2066 if (civicrm_error($preexisting)) {
2067 $transaction->rollback();
2068 return $preexisting;
2071 // Save the new/updated records
2073 foreach ($params['values'] as $replacement) {
2074 // Sugar: Don't force clients to duplicate the 'key' data
2075 $replacement = array_merge($baseParams, $replacement);
2076 $action = (isset($replacement['id']) ||
isset($replacement[$entity . '_id'])) ?
'update' : 'create';
2077 $create = civicrm_api($entity, $action, $replacement);
2078 if (civicrm_error($create)) {
2079 $transaction->rollback();
2082 foreach ($create['values'] as $entity_id => $entity_value) {
2083 $creates[$entity_id] = $entity_value;
2087 // Remove stale records
2088 $staleIDs = array_diff(
2089 array_keys($preexisting['values']),
2090 array_keys($creates)
2092 foreach ($staleIDs as $staleID) {
2093 $delete = civicrm_api($entity, 'delete', array(
2094 'version' => $params['version'],
2097 if (civicrm_error($delete)) {
2098 $transaction->rollback();
2103 return civicrm_api3_create_success($creates, $params);
2105 catch(PEAR_Exception
$e) {
2106 $transaction->rollback();
2107 return civicrm_api3_create_error($e->getMessage());
2109 catch(Exception
$e) {
2110 $transaction->rollback();
2111 return civicrm_api3_create_error($e->getMessage());
2116 * Replace base parameters.
2118 * @param array $params
2122 function _civicrm_api3_generic_replace_base_params($params) {
2123 $baseParams = $params;
2124 unset($baseParams['values']);
2125 unset($baseParams['sequential']);
2126 unset($baseParams['options']);
2131 * Returns fields allowable by api.
2134 * String Entity to query.
2135 * @param bool $unique
2136 * Index by unique fields?.
2137 * @param array $params
2141 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
2142 $unsetIfEmpty = array(
2149 $dao = _civicrm_api3_get_DAO($entity);
2154 $fields = $d->fields();
2156 // Set html attributes for text fields
2157 foreach ($fields as $name => &$field) {
2158 if (isset($field['html'])) {
2159 $field['html'] +
= (array) $d::makeAttribute($field);
2163 // replace uniqueNames by the normal names as the key
2164 if (empty($unique)) {
2165 foreach ($fields as $name => &$field) {
2166 //getting rid of unused attributes
2167 foreach ($unsetIfEmpty as $attr) {
2168 if (empty($field[$attr])) {
2169 unset($field[$attr]);
2172 if ($name == $field['name']) {
2175 if (array_key_exists($field['name'], $fields)) {
2176 $field['error'] = 'name conflict';
2177 // it should never happen, but better safe than sorry
2180 $fields[$field['name']] = $field;
2181 $fields[$field['name']]['uniqueName'] = $name;
2182 unset($fields[$name]);
2185 // Translate FKClassName to the corresponding api
2186 foreach ($fields as $name => &$field) {
2187 if (!empty($field['FKClassName'])) {
2188 $FKApi = CRM_Core_DAO_AllCoreTables
::getBriefName($field['FKClassName']);
2190 $field['FKApiName'] = $FKApi;
2194 $fields +
= _civicrm_api_get_custom_fields($entity, $params);
2199 * Return an array of fields for a given entity.
2201 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
2204 * @param array $params
2208 function _civicrm_api_get_custom_fields($entity, &$params) {
2209 $entity = _civicrm_api_get_camel_name($entity);
2210 if ($entity == 'Contact') {
2211 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
2212 $entity = CRM_Utils_Array
::value('contact_type', $params);
2214 $customfields = CRM_Core_BAO_CustomField
::getFields($entity,
2217 // we could / should probably test for other subtypes here - e.g. activity_type_id
2218 CRM_Utils_Array
::value('contact_sub_type', $params),
2227 foreach ($customfields as $key => $value) {
2228 // Regular fields have a 'name' property
2229 $value['name'] = 'custom_' . $key;
2230 $value['title'] = $value['label'];
2231 $value['type'] = _getStandardTypeFromCustomDataType($value);
2232 $ret['custom_' . $key] = $value;
2238 * Translate the custom field data_type attribute into a std 'type'.
2240 * @param array $value
2244 function _getStandardTypeFromCustomDataType($value) {
2245 $dataType = $value['data_type'];
2246 //CRM-15792 - If date custom field contains timeformat change type to DateTime
2247 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
2248 $dataType = 'DateTime';
2251 'String' => CRM_Utils_Type
::T_STRING
,
2252 'Int' => CRM_Utils_Type
::T_INT
,
2253 'Money' => CRM_Utils_Type
::T_MONEY
,
2254 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
2255 'Float' => CRM_Utils_Type
::T_FLOAT
,
2256 'Date' => CRM_Utils_Type
::T_DATE
,
2257 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
2258 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
2259 'StateProvince' => CRM_Utils_Type
::T_INT
,
2260 'File' => CRM_Utils_Type
::T_STRING
,
2261 'Link' => CRM_Utils_Type
::T_STRING
,
2262 'ContactReference' => CRM_Utils_Type
::T_INT
,
2263 'Country' => CRM_Utils_Type
::T_INT
,
2265 return $mapping[$dataType];
2270 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
2272 * If multiple aliases the last takes precedence
2274 * Function also swaps unique fields for non-unique fields & vice versa.
2276 * @param $apiRequest
2279 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2280 foreach ($fields as $field => $values) {
2281 $uniqueName = CRM_Utils_Array
::value('uniqueName', $values);
2282 if (!empty($values['api.aliases'])) {
2283 // if aliased field is not set we try to use field alias
2284 if (!isset($apiRequest['params'][$field])) {
2285 foreach ($values['api.aliases'] as $alias) {
2286 if (isset($apiRequest['params'][$alias])) {
2287 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2289 //unset original field nb - need to be careful with this as it may bring inconsistencies
2290 // out of the woodwork but will be implementing only as _spec function extended
2291 unset($apiRequest['params'][$alias]);
2295 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2296 && isset($apiRequest['params'][$values['name']])
2298 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2299 // note that it would make sense to unset the original field here but tests need to be in place first
2300 if ($field != 'domain_version') {
2301 unset($apiRequest['params'][$values['name']]);
2304 if (!isset($apiRequest['params'][$field])
2306 && $field != $uniqueName
2307 && array_key_exists($uniqueName, $apiRequest['params'])
2309 $apiRequest['params'][$field] = CRM_Utils_Array
::value($values['uniqueName'], $apiRequest['params']);
2310 // note that it would make sense to unset the original field here but tests need to be in place first
2317 * Validate integer fields being passed into API.
2319 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2321 * @param array $params
2322 * Params from civicrm_api.
2323 * @param string $fieldName
2324 * Uniquename of field being checked.
2325 * @param array $fieldInfo
2326 * Array of fields from getfields function.
2327 * @param string $entity
2329 * @throws API_Exception
2331 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
2332 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2333 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2337 if (!empty($fieldValue)) {
2338 // if value = 'user_contact_id' (or similar), replace value with contact id
2339 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2340 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2341 if ('unknown-user' === $realContactId) {
2342 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
2344 elseif (is_numeric($realContactId)) {
2345 $fieldValue = $realContactId;
2348 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2349 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2352 // After swapping options, ensure we have an integer(s)
2353 foreach ((array) ($fieldValue) as $value) {
2354 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
2355 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
2359 // Check our field length
2360 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2362 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2363 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
2369 $params[$fieldName][$op] = $fieldValue;
2372 $params[$fieldName] = $fieldValue;
2377 * Determine a contact ID using a string expression.
2379 * @param string $contactIdExpr
2380 * E.g. "user_contact_id" or "@user:username".
2382 * @return int|NULL|'unknown-user'
2384 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2385 // If value = 'user_contact_id' replace value with logged in user id.
2386 if ($contactIdExpr == "user_contact_id") {
2387 return CRM_Core_Session
::getLoggedInContactID();
2389 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2390 $config = CRM_Core_Config
::singleton();
2392 $ufID = $config->userSystem
->getUfId($matches[1]);
2394 return 'unknown-user';
2397 $contactID = CRM_Core_BAO_UFMatch
::getContactId($ufID);
2399 return 'unknown-user';
2408 * Validate html (check for scripting attack).
2410 * @param array $params
2411 * @param string $fieldName
2412 * @param array $fieldInfo
2414 * @throws API_Exception
2416 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2417 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2418 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
2422 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2423 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
2429 * Validate string fields being passed into API.
2431 * @param array $params
2432 * Params from civicrm_api.
2433 * @param string $fieldName
2434 * Uniquename of field being checked.
2435 * @param array $fieldInfo
2436 * Array of fields from getfields function.
2437 * @param string $entity
2439 * @throws API_Exception
2442 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2443 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2444 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System
::isNull($fieldValue)) {
2448 if (!is_array($fieldValue)) {
2449 $fieldValue = (string) $fieldValue;
2452 //@todo what do we do about passed in arrays. For many of these fields
2453 // the missing piece of functionality is separating them to a separated string
2454 // & many save incorrectly. But can we change them wholesale?
2457 foreach ((array) $fieldValue as $value) {
2458 if (!CRM_Utils_Rule
::xssString($fieldValue)) {
2459 throw new Exception('Input contains illegal SCRIPT tag.');
2461 if ($fieldName == 'currency') {
2462 //When using IN operator $fieldValue is a array of currency codes
2463 if (!CRM_Utils_Rule
::currencyCode($value)) {
2464 throw new Exception("Currency not a valid code: $currency");
2469 if (!empty($fieldInfo['pseudoconstant']) ||
!empty($fieldInfo['options'])) {
2470 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2472 // Check our field length
2473 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2474 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2475 2100, array('field' => $fieldName)
2480 $params[$fieldName][$op] = $fieldValue;
2483 $params[$fieldName] = $fieldValue;
2488 * Validate & swap out any pseudoconstants / options.
2490 * @param mixed $fieldValue
2491 * @param string $entity : api entity name
2492 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2493 * @param array $fieldInfo : getfields meta-data
2495 * @throws \API_Exception
2497 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
2498 $options = CRM_Utils_Array
::value('options', $fieldInfo);
2501 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2502 // We need to get the options from the entity the field relates to.
2503 $entity = $fieldInfo['entity'];
2505 $options = civicrm_api($entity, 'getoptions', array(
2507 'field' => $fieldInfo['name'],
2508 'context' => 'validate',
2510 $options = CRM_Utils_Array
::value('values', $options, array());
2513 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2515 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
2516 $fieldValue = CRM_Utils_Array
::explodePadded($fieldValue);
2519 // If passed multiple options, validate each.
2520 if (is_array($fieldValue)) {
2521 foreach ($fieldValue as &$value) {
2522 if (!is_array($value)) {
2523 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2526 // TODO: unwrap the call to implodePadded from the conditional and do it always
2527 // need to verify that this is safe and doesn't break anything though.
2528 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2530 CRM_Utils_Array
::implodePadded($fieldValue);
2534 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2539 * Validate & swap a single option value for a field.
2541 * @param string $value field value
2542 * @param array $options array of options for this field
2543 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2545 * @throws API_Exception
2547 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2548 // If option is a key, no need to translate
2549 // or if no options are avaiable for pseudoconstant 'table' property
2550 if (array_key_exists($value, $options) ||
!$options) {
2554 // Translate value into key
2555 $newValue = array_search($value, $options);
2556 if ($newValue !== FALSE) {
2560 // Case-insensitive matching
2561 $newValue = strtolower($value);
2562 $options = array_map("strtolower", $options);
2563 $newValue = array_search($newValue, $options);
2564 if ($newValue === FALSE) {
2565 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2571 * Returns the canonical name of a field.
2574 * api entity name (string should already be standardized - no camelCase).
2576 * any variation of a field's name (name, unique_name, api.alias).
2578 * @param string $action
2580 * @return bool|string
2581 * FieldName or FALSE if the field does not exist
2583 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2587 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2590 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2593 $result = civicrm_api($entity, 'getfields', array(
2595 'action' => $action,
2597 $meta = $result['values'];
2598 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2599 $fieldName = $fieldName . '_id';
2601 if (isset($meta[$fieldName])) {
2602 return $meta[$fieldName]['name'];
2604 foreach ($meta as $info) {
2605 if ($fieldName == $info['name'] ||
$fieldName == CRM_Utils_Array
::value('uniqueName', $info)) {
2606 return $info['name'];
2608 if (array_search($fieldName, CRM_Utils_Array
::value('api.aliases', $info, array())) !== FALSE) {
2609 return $info['name'];
2612 // Create didn't work, try with get
2613 if ($action == 'create') {
2614 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2620 * Check if the function is deprecated.
2622 * @param string $entity
2623 * @param array $result
2625 * @return string|array|null
2627 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2629 $apiFile = "api/v3/$entity.php";
2630 if (CRM_Utils_File
::isIncludable($apiFile)) {
2631 require_once $apiFile;
2633 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2634 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2635 if (function_exists($fnName)) {
2636 return $fnName($result);
2642 * Get the actual field value.
2644 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2645 * So this function returns the actual field value.
2647 * @param array $params
2648 * @param string $fieldName
2649 * @param string $type
2653 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2654 $fieldValue = CRM_Utils_Array
::value($fieldName, $params);
2657 if (!empty($fieldValue) && is_array($fieldValue) &&
2658 (array_search(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators()) ||
2659 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2661 $op = key($fieldValue);
2662 $fieldValue = CRM_Utils_Array
::value($op, $fieldValue);
2664 return array($fieldValue, $op);
2668 * A generic "get" API based on simple array data. This is comparable to
2669 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2670 * small/mid-size data loaded from external JSON or XML documents.
2673 * @param array $params
2675 * @param array $records
2676 * List of all records.
2677 * @param string $idCol
2678 * The property which defines the ID of a record
2679 * @param array $fields
2680 * List of filterable fields.
2683 * @throws \API_Exception
2685 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) {
2686 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2687 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2688 $offset = CRM_Utils_Array
::value('offset', $options);
2689 $limit = CRM_Utils_Array
::value('limit', $options);
2694 foreach ($records as $record) {
2695 if ($idCol != 'id') {
2696 $record['id'] = $record[$idCol];
2699 foreach ($params as $k => $v) {
2703 if (in_array($k, $fields) && $record[$k] != $v) {
2709 if ($currentOffset >= $offset) {
2710 $matches[$record[$idCol]] = $record;
2712 if ($limit && count($matches) >= $limit) {
2719 $return = CRM_Utils_Array
::value('return', $options, array());
2720 if (!empty($return)) {
2722 $matches = CRM_Utils_Array
::filterColumns($matches, array_keys($return));
2725 return civicrm_api3_create_success($matches, $params);