CRM-17275 Import - allow contact WITH external identifier to match one without
[civicrm-core.git] / api / v3 / utils.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
81621fee 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
b081365f 29 * CiviCRM APIv3 utility functions.
6a488035
TO
30 *
31 * @package CiviCRM_APIv3
6a488035
TO
32 */
33
34/**
61fe4988 35 * Initialize CiviCRM - should be run at the start of each API function.
6a488035
TO
36 */
37function _civicrm_api3_initialize() {
22fd1690
ARW
38 require_once 'CRM/Core/ClassLoader.php';
39 CRM_Core_ClassLoader::singleton()->register();
40 CRM_Core_Config::singleton();
41}
6a488035 42
11e09c59 43/**
61fe4988 44 * Wrapper Function for civicrm_verify_mandatory to make it simple to pass either / or fields for checking.
6a488035 45 *
cf470720
TO
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.
6a488035 52 */
35671d00 53function civicrm_api3_verify_one_mandatory($params, $daoName = NULL, $keyoptions = array()) {
6a488035
TO
54 $keys = array(array());
55 foreach ($keyoptions as $key) {
56 $keys[0][] = $key;
57 }
58 civicrm_api3_verify_mandatory($params, $daoName, $keys);
59}
60
11e09c59 61/**
61fe4988 62 * Check mandatory fields are included.
6a488035 63 *
cf470720
TO
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).
68 * @param array $keys
69 * List of required fields. A value can be an array denoting that either this or that is required.
6a488035 70 * @param bool $verifyDAO
cd5823ae
EM
71 *
72 * @throws \API_Exception
6a488035 73 */
27b9f49a 74function civicrm_api3_verify_mandatory($params, $daoName = NULL, $keys = array(), $verifyDAO = TRUE) {
6a488035
TO
75
76 $unmatched = array();
77 if ($daoName != NULL && $verifyDAO && empty($params['id'])) {
78 $unmatched = _civicrm_api3_check_required_fields($params, $daoName, TRUE);
79 if (!is_array($unmatched)) {
80 $unmatched = array();
81 }
82 }
83
84 if (!empty($params['id'])) {
85 $keys = array('version');
86 }
87 else {
88 if (!in_array('version', $keys)) {
89 // required from v3 onwards
90 $keys[] = 'version';
91 }
92 }
93 foreach ($keys as $key) {
94 if (is_array($key)) {
95 $match = 0;
96 $optionset = array();
97 foreach ($key as $subkey) {
98 if (!array_key_exists($subkey, $params) || empty($params[$subkey])) {
99 $optionset[] = $subkey;
100 }
101 else {
102 // as long as there is one match then we don't need to rtn anything
103 $match = 1;
104 }
105 }
106 if (empty($match) && !empty($optionset)) {
107 $unmatched[] = "one of (" . implode(", ", $optionset) . ")";
108 }
109 }
110 else {
5ba3bfc8
CW
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')) {
6a488035
TO
114 $unmatched[] = $key;
115 }
116 }
117 }
118 if (!empty($unmatched)) {
35671d00 119 throw new API_Exception("Mandatory key(s) missing from params array: " . implode(", ", $unmatched), "mandatory_missing", array("fields" => $unmatched));
6a488035
TO
120 }
121}
122
123/**
61fe4988 124 * Create error array.
6a488035 125 *
61fe4988 126 * @param string $msg
916b48b6 127 * @param array $data
61fe4988 128 *
a6c01b45 129 * @return array
6a488035 130 */
9c465c3b 131function civicrm_api3_create_error($msg, $data = array()) {
6a488035
TO
132 $data['is_error'] = 1;
133 $data['error_message'] = $msg;
9c465c3b
TO
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?)
22e263ad 136 if (isset($data['sql']) && CRM_Core_Permission::check('Administer CiviCRM')) {
61fe4988
EM
137 // Isn't this redundant?
138 $data['debug_information'] = $data['sql'];
0db6c3e1
TO
139 }
140 else {
2baf21cf 141 unset($data['sql']);
e7c4a581 142 }
6a488035
TO
143 return $data;
144}
145
146/**
35823763 147 * Format array in result output style.
6a488035 148 *
77b97be7 149 * @param array|int $values values generated by API operation (the result)
cf470720
TO
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.
156 * @param object $dao
157 * DAO object to be freed here.
158 * @param array $extraReturnValues
159 * Additional values to be added to top level of result array(.
6a488035
TO
160 * - this param is currently used for legacy behaviour support
161 *
a6c01b45 162 * @return array
6a488035 163 */
54df0f0c 164function civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL, &$dao = NULL, $extraReturnValues = array()) {
6a488035 165 $result = array();
4846df91
CW
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);
6a488035
TO
169 $result['is_error'] = 0;
170 //lets set the ['id'] field if it's not set & we know what the entity is
4846df91 171 if (is_array($values) && $entity && $action != 'getfields') {
6a488035 172 foreach ($values as $key => $item) {
4846df91
CW
173 if (empty($item['id']) && !empty($item[$lowercase_entity . "_id"])) {
174 $values[$key]['id'] = $item[$lowercase_entity . "_id"];
6a488035 175 }
9b873358 176 if (!empty($item['financial_type_id'])) {
797b807e 177 //4.3 legacy handling
a1c68fd2 178 $values[$key]['contribution_type_id'] = $item['financial_type_id'];
179 }
9b873358 180 if (!empty($item['next_sched_contribution_date'])) {
797b807e 181 // 4.4 legacy handling
182 $values[$key]['next_sched_contribution'] = $item['next_sched_contribution_date'];
183 }
6a488035
TO
184 }
185 }
d8453bed 186
187 if (is_array($params) && !empty($params['debug'])) {
6a488035
TO
188 if (is_string($action) && $action != 'getfields') {
189 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => $action) + $params);
190 }
191 elseif ($action != 'getfields') {
192 $apiFields = civicrm_api($entity, 'getfields', array('version' => 3) + $params);
193 }
194 else {
195 $apiFields = FALSE;
196 }
197
198 $allFields = array();
199 if ($action != 'getfields' && is_array($apiFields) && is_array(CRM_Utils_Array::value('values', $apiFields))) {
200 $allFields = array_keys($apiFields['values']);
201 }
202 $paramFields = array_keys($params);
9d32e6f7
EM
203 $undefined = array_diff($paramFields, $allFields, array_keys($_COOKIE), array(
204 'action',
205 'entity',
206 'debug',
207 'version',
208 'check_permissions',
209 'IDS_request_uri',
210 'IDS_user_agent',
211 'return',
212 'sequential',
213 'rowCount',
214 'option_offset',
215 'option_limit',
216 'custom',
217 'option_sort',
218 'options',
219 'prettyprint',
220 ));
6a488035
TO
221 if ($undefined) {
222 $result['undefined_fields'] = array_merge($undefined);
223 }
224 }
225 if (is_object($dao)) {
226 $dao->free();
227 }
228
229 $result['version'] = 3;
230 if (is_array($values)) {
e7c4a581 231 $result['count'] = (int) count($values);
6a488035
TO
232
233 // Convert value-separated strings to array
234 _civicrm_api3_separate_values($values);
235
236 if ($result['count'] == 1) {
237 list($result['id']) = array_keys($values);
238 }
239 elseif (!empty($values['id']) && is_int($values['id'])) {
240 $result['id'] = $values['id'];
241 }
242 }
243 else {
244 $result['count'] = !empty($values) ? 1 : 0;
245 }
246
247 if (is_array($values) && isset($params['sequential']) &&
248 $params['sequential'] == 1
249 ) {
250 $result['values'] = array_values($values);
251 }
252 else {
253 $result['values'] = $values;
254 }
22e263ad 255 if (!empty($params['options']['metadata'])) {
9d32e6f7 256 // We've made metadata an array but only supporting 'fields' atm.
22e263ad 257 if (in_array('fields', (array) $params['options']['metadata']) && $action !== 'getfields') {
9d32e6f7
EM
258 $fields = civicrm_api3($entity, 'getfields', array(
259 'action' => substr($action, 0, 3) == 'get' ? 'get' : 'create',
260 ));
dc5a7701
E
261 $result['metadata']['fields'] = $fields['values'];
262 }
263 }
9d32e6f7 264 // Report deprecations.
a14e9d08 265 $deprecated = _civicrm_api3_deprecation_check($entity, $result);
1726c7d2
CW
266 // Always report "setvalue" action as deprecated.
267 if (!is_string($deprecated) && ($action == 'getactions' || $action == 'setvalue')) {
265df5a0
CW
268 $deprecated = ((array) $deprecated) + array('setvalue' => 'The "setvalue" action is deprecated. Use "create" with an id instead.');
269 }
9d32e6f7 270 // Always report "update" action as deprecated.
a14e9d08
CW
271 if (!is_string($deprecated) && ($action == 'getactions' || $action == 'update')) {
272 $deprecated = ((array) $deprecated) + array('update' => 'The "update" action is deprecated. Use "create" with an id instead.');
273 }
274 if ($deprecated) {
9d32e6f7 275 // Metadata-level deprecations or wholesale entity deprecations.
1644b908 276 if ($entity == 'Entity' || $action == 'getactions' || is_string($deprecated)) {
a14e9d08
CW
277 $result['deprecated'] = $deprecated;
278 }
279 // Action-specific deprecations
280 elseif (!empty($deprecated[$action])) {
281 $result['deprecated'] = $deprecated[$action];
282 }
283 }
6a488035
TO
284 return array_merge($result, $extraReturnValues);
285}
11e09c59
TO
286
287/**
61fe4988
EM
288 * Load the DAO of the entity.
289 *
645ee340 290 * @param $entity
9d32e6f7 291 *
645ee340 292 * @return bool
6a488035
TO
293 */
294function _civicrm_api3_load_DAO($entity) {
295 $dao = _civicrm_api3_get_DAO($entity);
296 if (empty($dao)) {
297 return FALSE;
298 }
6a488035
TO
299 $d = new $dao();
300 return $d;
301}
11e09c59
TO
302
303/**
61fe4988
EM
304 * Return the DAO of the function or Entity.
305 *
cf470720
TO
306 * @param string $name
307 * Either a function of the api (civicrm_{entity}_create or the entity name.
16b10e64
CW
308 * return the DAO name to manipulate this function
309 * eg. "civicrm_api3_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
61fe4988 310 *
26728d3f 311 * @return mixed|string
6a488035
TO
312 */
313function _civicrm_api3_get_DAO($name) {
6a488035
TO
314 if (strpos($name, 'civicrm_api3') !== FALSE) {
315 $last = strrpos($name, '_');
316 // len ('civicrm_api3_') == 13
317 $name = substr($name, 13, $last - 13);
318 }
319
1644b908 320 $name = _civicrm_api_get_camel_name($name);
6a488035 321
663072a5 322 if ($name == 'Individual' || $name == 'Household' || $name == 'Organization') {
6a488035
TO
323 $name = 'Contact';
324 }
325
da54ec85
CW
326 // hack to deal with incorrectly named BAO/DAO - see CRM-10859
327
bd6658bd
TO
328 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingEventQueue
329 if ($name == 'MailingEventQueue') {
330 return 'CRM_Mailing_Event_DAO_Queue';
331 }
da54ec85
CW
332 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingRecipients
333 // but am not confident mailing_recipients is tested so have not tackled.
663072a5 334 if ($name == 'MailingRecipients') {
da54ec85 335 return 'CRM_Mailing_DAO_Recipients';
6a488035 336 }
d615ccf5
CW
337 // FIXME: DAO should be renamed CRM_Mailing_DAO_MailingComponent
338 if ($name == 'MailingComponent') {
339 return 'CRM_Mailing_DAO_Component';
340 }
da54ec85 341 // FIXME: DAO should be renamed CRM_ACL_DAO_AclRole
663072a5
CW
342 if ($name == 'AclRole') {
343 return 'CRM_ACL_DAO_EntityRole';
344 }
da54ec85
CW
345 // FIXME: DAO should be renamed CRM_SMS_DAO_SmsProvider
346 // But this would impact SMS extensions so need to coordinate
347 // Probably best approach is to migrate them to use the api and decouple them from core BAOs
348 if ($name == 'SmsProvider') {
349 return 'CRM_SMS_DAO_Provider';
350 }
351 // FIXME: DAO names should follow CamelCase convention
663072a5 352 if ($name == 'Im' || $name == 'Acl') {
1fe97a01 353 $name = strtoupper($name);
6a488035 354 }
23474ab3 355 $dao = CRM_Core_DAO_AllCoreTables::getFullName($name);
9537a4e1 356 if ($dao || !$name) {
23474ab3
CW
357 return $dao;
358 }
359
360 // Really weird apis can declare their own DAO name. Not sure if this is a good idea...
22e263ad 361 if (file_exists("api/v3/$name.php")) {
db47ea7b 362 include_once "api/v3/$name.php";
363 }
bada0f66 364
23474ab3
CW
365 $daoFn = "_civicrm_api3_" . _civicrm_api_get_entity_name_from_camel($name) . "_DAO";
366 if (function_exists($daoFn)) {
367 return $daoFn();
368 }
369
370 return NULL;
6a488035
TO
371}
372
11e09c59 373/**
61fe4988
EM
374 * Return the DAO of the function or Entity.
375 *
cf470720
TO
376 * @param string $name
377 * Is either a function of the api (civicrm_{entity}_create or the entity name.
16b10e64
CW
378 * return the DAO name to manipulate this function
379 * eg. "civicrm_contact_create" or "Contact" will return "CRM_Contact_BAO_Contact"
61fe4988 380 *
26728d3f 381 * @return mixed
6a488035
TO
382 */
383function _civicrm_api3_get_BAO($name) {
da54ec85
CW
384 // FIXME: DAO should be renamed CRM_Badge_DAO_BadgeLayout
385 if ($name == 'PrintLabel') {
386 return 'CRM_Badge_BAO_Layout';
387 }
6a488035 388 $dao = _civicrm_api3_get_DAO($name);
5c1174d3
CW
389 if (!$dao) {
390 return NULL;
391 }
d9f036bb 392 $bao = str_replace("DAO", "BAO", $dao);
49e101d0 393 $file = strtr($bao, '_', '/') . '.php';
5c1174d3 394 // Check if this entity actually has a BAO. Fall back on the DAO if not.
49e101d0 395 return stream_resolve_include_path($file) ? $bao : $dao;
6a488035
TO
396}
397
398/**
61fe4988
EM
399 * Recursive function to explode value-separated strings into arrays.
400 *
645ee340 401 * @param $values
6a488035
TO
402 */
403function _civicrm_api3_separate_values(&$values) {
404 $sp = CRM_Core_DAO::VALUE_SEPARATOR;
405 foreach ($values as $key => & $value) {
406 if (is_array($value)) {
407 _civicrm_api3_separate_values($value);
408 }
409 elseif (is_string($value)) {
61fe4988
EM
410 // This is to honor the way case API was originally written.
411 if ($key == 'case_type_id') {
6a488035
TO
412 $value = trim(str_replace($sp, ',', $value), ',');
413 }
414 elseif (strpos($value, $sp) !== FALSE) {
415 $value = explode($sp, trim($value, $sp));
416 }
417 }
418 }
419}
11e09c59
TO
420
421/**
61fe4988
EM
422 * This is a legacy wrapper for api_store_values.
423 *
424 * It checks suitable fields using getfields rather than DAO->fields.
6a488035 425 *
61fe4988 426 * Getfields has handling for how to deal with unique names which dao->fields doesn't
6a488035
TO
427 *
428 * Note this is used by BAO type create functions - eg. contribution
61fe4988 429 *
6a488035
TO
430 * @param string $entity
431 * @param array $params
432 * @param array $values
433 */
9b873358 434function _civicrm_api3_filter_fields_for_bao($entity, &$params, &$values) {
35671d00 435 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
6a488035
TO
436 $fields = $fields['values'];
437 _civicrm_api3_store_values($fields, $params, $values);
438}
439/**
61fe4988 440 * Store values.
6a488035
TO
441 *
442 * @param array $fields
443 * @param array $params
444 * @param array $values
445 *
a6c01b45 446 * @return Bool
6a488035
TO
447 */
448function _civicrm_api3_store_values(&$fields, &$params, &$values) {
449 $valueFound = FALSE;
450
451 $keys = array_intersect_key($params, $fields);
452 foreach ($keys as $name => $value) {
453 if ($name !== 'id') {
454 $values[$name] = $value;
455 $valueFound = TRUE;
456 }
457 }
458 return $valueFound;
459}
26728d3f 460
4eea368c
JV
461/**
462 * Get function for query object api.
463 *
464 * This is a simple get function, but it should be usable for any kind of
465 * entity. I created it to work around CRM-16036.
84c546ab 466 *
4eea368c
JV
467 * @param string $dao_name
468 * Name of DAO
469 * @param array $params
6a271fe0 470 * As passed into api get function.
0f3699bf 471 * @param bool $isFillUniqueFields
472 * Do we need to ensure unique fields continue to be populated for this api? (backward compatibility).
01c8287d 473 * @param CRM_Utils_SQL_Select|NULL $sqlFragment
6a271fe0 474 *
4eea368c
JV
475 * @return array
476 */
01c8287d 477function _civicrm_api3_get_using_utils_sql($dao_name, $params, $isFillUniqueFields, $sqlFragment) {
1c9cf443 478
4eea368c
JV
479 $dao = new $dao_name();
480 $entity = _civicrm_api_get_entity_name_from_dao($dao);
fb214de7 481 $custom_fields = _civicrm_api3_custom_fields_for_entity($entity);
836231f4 482 $options = _civicrm_api3_get_options_from_params($params);
0298287b 483
2b28667f 484 // Unset $params['options'] if they are api parameters (not options as a fieldname).
485 if (!empty($params['options']) && is_array($params['options'])&& array_intersect(array_keys($params['options']), array_keys($options))) {
486 unset ($params['options']);
487 }
7d49d7b3 488
0f3699bf 489 $entity_field_names = _civicrm_api3_field_names(_civicrm_api3_build_fields_array($dao));
1c9cf443 490 $custom_field_names = array();
0298287b 491 $uniqueAliases = array();
0f3699bf 492 $getFieldsResult = civicrm_api3($entity, 'getfields', array('action' => 'get'));
493 $getFieldsResult = $getFieldsResult['values'];
0298287b 494 foreach ($getFieldsResult as $getFieldKey => $getFieldSpec) {
495 $uniqueAliases[$getFieldKey] = $getFieldSpec['name'];
496 $uniqueAliases[$getFieldSpec['name']] = $getFieldSpec['name'];
497 }
498
683e39eb
JV
499 // $select_fields maps column names to the field names of the result
500 // values.
836231f4 501 $select_fields = array();
836231f4 502
0f3699bf 503 // array with elements array('column', 'operator', 'value');
84c546ab 504 $where_clauses = array();
fb214de7
JV
505
506 // Tables we need to join with to retrieve the custom values.
bee644e5
JV
507 $custom_value_tables = array();
508
509 // ID's of custom fields that refer to a contact.
510 $contact_reference_field_ids = array();
fb214de7 511
fb214de7 512 // populate $select_fields
5d5c3c21 513 $return_all_fields = (empty($options['return']) || !is_array($options['return']));
0298287b 514 $return = $return_all_fields ? array_fill_keys($entity_field_names, 1) : $options['return'];
5d5c3c21
JV
515
516 // default fields
0298287b 517 foreach (array_keys($return) as $field_name) {
4ac3496d 518 if (!empty($uniqueAliases[$field_name]) && (CRM_Core_BAO_CustomField::getKeyID($field_name) == FALSE)) {
a50d9fb1 519 // 'a.' is an alias for the entity table.
0298287b 520 $select_fields["a.{$uniqueAliases[$field_name]}"] = $uniqueAliases[$field_name];
a50d9fb1 521 }
5d5c3c21
JV
522 }
523
524 // custom fields
525 foreach ($custom_fields as $cf_id => $custom_field) {
526 $field_name = "custom_$cf_id";
1c9cf443 527 $custom_field_names[] = $field_name;
2b28667f 528 if ($return_all_fields || !empty($options['return'][$field_name])
529 ||
530 // This is a tested format so we support it.
531 !empty($options['return']['custom'])
532 ) {
a50d9fb1
JV
533 $table_name = $custom_field["table_name"];
534 $column_name = $custom_field["column_name"];
5d5c3c21 535 // remember that we will need to join the correct table.
bee644e5
JV
536 if (!in_array($table_name, $custom_value_tables)) {
537 $custom_value_tables[] = $table_name;
538 }
539 if ($custom_field["data_type"] != "ContactReference") {
540 // 'ordinary' custom field. We will select the value as custom_XX.
541 $select_fields["$table_name.$column_name"] = $field_name;
542 }
543 else {
544 // contact reference custom field. The ID will be stored in
545 // custom_XX_id. custom_XX will contain the sort name of the
546 // contact.
547 $contact_reference_field_ids[] = $cf_id;
548 $select_fields["$table_name.$column_name"] = $field_name . "_id";
549 // We will call the contact table for the join c_XX.
550 $select_fields["c_$cf_id.sort_name"] = $field_name;
a50d9fb1
JV
551 }
552 }
553 }
5d5c3c21
JV
554 if (!in_array("a.id", $select_fields)) {
555 // Always select the ID.
556 $select_fields["a.id"] = "id";
836231f4 557 }
2b28667f 558 // build query
559 $query = CRM_Utils_SQL_Select::from($dao->tableName() . " a");
836231f4 560
fb214de7 561 // populate $where_clauses
84c546ab 562 foreach ($params as $key => $value) {
2b28667f 563 $type = 'String';
0298287b 564 $table_name = NULL;
565 $column_name = NULL;
566
567 if (substr($key, 0, 7) == 'filter.') {
568 // Legacy support for old filter syntax per the test contract.
569 // (Convert the style to the later one & then deal with them).
570 $filterArray = explode('.', $key);
571 $value = array($filterArray[1] => $value);
572 $key = 'filters';
573 }
574
575 // Legacy support for 'filter's construct.
576 if ($key == 'filters') {
577 foreach ($value as $filterKey => $filterValue) {
578 if (substr($filterKey, -4, 4) == 'high') {
579 $key = substr($filterKey, 0, -5);
580 $value = array('<=' => $filterValue);
581 }
582
583 if (substr($filterKey, -3, 3) == 'low') {
584 $key = substr($filterKey, 0, -4);
585 $value = array('>=' => $filterValue);
586 }
587
588 if ($filterKey == 'is_current' || $filterKey == 'isCurrent') {
589 // Is current is almost worth creating as a 'sql filter' in the DAO function since several entities have the
590 // concept.
591 $todayStart = date('Ymd000000', strtotime('now'));
592 $todayEnd = date('Ymd235959', strtotime('now'));
593 $query->where(array("(a.start_date <= '$todayStart' OR a.start_date IS NULL) AND (a.end_date >= '$todayEnd' OR
594 a.end_date IS NULL)
595 AND a.is_active = 1
596 "));
597 }
598 }
599 }
600
0f3699bf 601 if (array_key_exists($key, $getFieldsResult)) {
b766580c 602 $type = $getFieldsResult[$key]['type'];
0f3699bf 603 $key = $getFieldsResult[$key]['name'];
604 }
0298287b 605 if ($key == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
606 // The test contract enforces support of (eg) mailing_group_id if the entity is MailingGroup.
607 $type = 'int';
608 $key = 'id';
609 }
2b28667f 610 if (in_array($key, $entity_field_names)) {
611 $table_name = 'a';
b766580c 612 $column_name = $key;
2b28667f 613 }
614 elseif (($cf_id = CRM_Core_BAO_CustomField::getKeyID($key)) != FALSE) {
615 $table_name = $custom_fields[$cf_id]["table_name"];
b766580c 616 $column_name = $custom_fields[$cf_id]["column_name"];
617
618 if (!in_array($table_name, $custom_value_tables)) {
619 $custom_value_tables[] = $table_name;
620 }
2b28667f 621 }
0f3699bf 622 // I don't know why I had to specifically exclude 0 as a key - wouldn't the others have caught it?
623 // We normally silently ignore null values passed in - if people want IS_NULL they can use acceptedSqlOperator syntax.
0298287b 624 if ((!$table_name) || empty($key) || is_null($value)) {
1c9cf443
JV
625 // No valid filter field. This might be a chained call or something.
626 // Just ignore this for the $where_clause.
627 continue;
628 }
bd744b8a 629 if (!is_array($value)) {
b766580c 630 $query->where(array("{$table_name}.{$column_name} = @value"), array(
2b28667f 631 "@value" => $value,
632 ));
bd744b8a
JV
633 }
634 else {
635 // We expect only one element in the array, of the form
636 // "operator" => "rhs".
faee6095 637 $operator = CRM_Utils_Array::first(array_keys($value));
bd744b8a 638 if (!in_array($operator, CRM_Core_DAO::acceptedSQLOperators())) {
b766580c 639 $query->where(array(
640 "{$table_name}.{$column_name} = @value"), array("@value" => $value)
641 );
2b28667f 642 }
643 else {
4339a82a 644 $query->where(CRM_Core_DAO::createSQLFilter("{$table_name}.{$column_name}", $value, $type));
bd744b8a 645 }
bd744b8a 646 }
b766580c 647 }
efdf2008 648
7cbc0503 649 $i = 0;
0f3699bf 650 if (!$options['is_count']) {
651 foreach ($select_fields as $column => $alias) {
652 ++$i;
653 $query = $query->select("!column_$i as !alias_$i", array(
654 "!column_$i" => $column,
2b28667f 655 "!alias_$i" => $alias,
0f3699bf 656 ));
657 }
658 }
659 else {
660 $query->select("count(*) as c");
836231f4 661 }
4b217aea 662
bee644e5
JV
663 // join with custom value tables
664 foreach ($custom_value_tables as $table_name) {
7cbc0503
JV
665 ++$i;
666 $query = $query->join(
667 "!table_name_$i",
668 "LEFT OUTER JOIN !table_name_$i ON !table_name_$i.entity_id = a.id",
669 array("!table_name_$i" => $table_name)
670 );
fb214de7
JV
671 }
672
bee644e5
JV
673 // join with contact for contact reference fields
674 foreach ($contact_reference_field_ids as $field_id) {
675 ++$i;
676 $query = $query->join(
677 "!contact_table_name$i",
678 "LEFT OUTER JOIN civicrm_contact !contact_table_name_$i ON !contact_table_name_$i.id = !values_table_name_$i.!column_name_$i",
679 array(
680 "!contact_table_name_$i" => "c_$field_id",
681 "!values_table_name_$i" => $custom_fields[$field_id]["table_name"],
682 "!column_name_$i" => $custom_fields[$field_id]["column_name"],
683 ));
684 };
685
bd744b8a 686 foreach ($where_clauses as $clause) {
7cbc0503 687 ++$i;
bd744b8a 688 if (substr($clause[1], -4) == "NULL") {
7cbc0503
JV
689 $query->where("!columnName_$i !nullThing_$i", array(
690 "!columnName_$i" => $clause[0],
691 "!nullThing_$i" => $clause[1],
692 ));
bd744b8a
JV
693 }
694 else {
7cbc0503
JV
695 $query->where("!columnName_$i !operator_$i @value_$i", array(
696 "!columnName_$i" => $clause[0],
697 "!operator_$i" => $clause[1],
698 "@value_$i" => $clause[2],
699 ));
bd744b8a 700 }
fb214de7 701 };
01c8287d
TO
702 if (!empty($sqlFragment)) {
703 $query->merge($sqlFragment);
0f3699bf 704 }
4eea368c 705
f4b04d2c
JV
706 // order by
707 if (!empty($options['sort'])) {
2b28667f 708 $sort_fields = array();
f4b04d2c
JV
709 foreach (explode(',', $options['sort']) as $sort_option) {
710 $words = preg_split("/[\s]+/", $sort_option);
711 if (count($words) > 0 && in_array($words[0], array_values($select_fields))) {
712 $tmp = $words[0];
0298287b 713 if (!empty($words[1]) && strtoupper($words[1]) == 'DESC') {
f4b04d2c
JV
714 $tmp .= " DESC";
715 }
716 $sort_fields[] = $tmp;
717 }
718 }
719 if (count($sort_fields) > 0) {
7cbc0503 720 $query->orderBy(implode(",", $sort_fields));
f4b04d2c
JV
721 }
722 }
723
724 // limit
7cbc0503
JV
725 if (!empty($options['limit']) || !empty($options['offset'])) {
726 $query->limit($options['limit'], $options['offset']);
f4b04d2c
JV
727 }
728
4eea368c 729 $result_entities = array();
7cbc0503 730 $result_dao = CRM_Core_DAO::executeQuery($query->toSQL());
0f3699bf 731
4eea368c 732 while ($result_dao->fetch()) {
0f3699bf 733 if ($options['is_count']) {
734 $result_dao->free();
735 return (int) $result_dao->c;
736 }
4eea368c 737 $result_entities[$result_dao->id] = array();
683e39eb 738 foreach ($select_fields as $column => $alias) {
0298287b 739 if (property_exists($result_dao, $alias) && $result_dao->$alias != NULL) {
683e39eb 740 $result_entities[$result_dao->id][$alias] = $result_dao->$alias;
4b217aea 741 }
0f3699bf 742 // Backward compatibility on fields names.
743 if ($isFillUniqueFields && !empty($getFieldsResult['values'][$column]['uniqueName'])) {
744 $result_entities[$result_dao->id][$getFieldsResult['values'][$column]['uniqueName']] = $result_dao->$alias;
745 }
746 foreach ($getFieldsResult as $returnName => $spec) {
0f3699bf 747 if (empty($result_entities[$result_dao->id][$returnName]) && !empty($result_entities[$result_dao->id][$spec['name']])) {
748 $result_entities[$result_dao->id][$returnName] = $result_entities[$result_dao->id][$spec['name']];
749 }
750 }
4eea368c
JV
751 };
752 }
e13654dc 753 $result_dao->free();
0f3699bf 754 return $result_entities;
4eea368c
JV
755}
756
836231f4
JV
757/**
758 * Returns field names of the given entity fields.
759 *
2b28667f 760 * @param array $fields
836231f4
JV
761 * Fields array to retrieve the field names for.
762 * @return array
763 */
764function _civicrm_api3_field_names($fields) {
765 $result = array();
84c546ab 766 foreach ($fields as $key => $value) {
a50d9fb1 767 if (!empty($value['name'])) {
84c546ab 768 $result[] = $value['name'];
a50d9fb1 769 }
836231f4
JV
770 }
771 return $result;
772}
773
fb214de7
JV
774/**
775 * Returns an array with database information for the custom fields of an
776 * entity.
777 *
778 * Something similar might already exist in CiviCRM. But I was not
779 * able to find it.
780 *
781 * @param string $entity
782 *
783 * @return array
784 * an array that maps the custom field ID's to table name and
785 * column name. E.g.:
786 * {
84c546ab
JV
787 * '1' => array {
788 * 'table_name' => 'table_name_1',
bee644e5
JV
789 * 'column_name' => 'column_name_1',
790 * 'data_type' => 'data_type_1',
fb214de7
JV
791 * },
792 * }
793 */
794function _civicrm_api3_custom_fields_for_entity($entity) {
795 $result = array();
796
797 $query = "
798SELECT f.id, f.label, f.data_type,
799 f.html_type, f.is_search_range,
800 f.option_group_id, f.custom_group_id,
801 f.column_name, g.table_name,
802 f.date_format,f.time_format
803 FROM civicrm_custom_field f
804 JOIN civicrm_custom_group g ON f.custom_group_id = g.id
805 WHERE g.is_active = 1
806 AND f.is_active = 1
807 AND g.extends = %1";
808
809 $params = array(
84c546ab 810 '1' => array($entity, 'String'),
fb214de7
JV
811 );
812
813 $dao = CRM_Core_DAO::executeQuery($query, $params);
814 while ($dao->fetch()) {
815 $result[$dao->id] = array(
816 'table_name' => $dao->table_name,
817 'column_name' => $dao->column_name,
bee644e5 818 'data_type' => $dao->data_type,
fb214de7
JV
819 );
820 }
821 $dao->free();
822
823 return $result;
824}
825
6a488035 826/**
61fe4988
EM
827 * Get function for query object api.
828 *
829 * The API supports 2 types of get request. The more complex uses the BAO query object.
6a488035
TO
830 * This is a generic function for those functions that call it
831 *
832 * At the moment only called by contact we should extend to contribution &
833 * others that use the query object. Note that this function passes permission information in.
834 * The others don't
835 *
c23f45d3 836 * Ideally this would be merged with _civicrm_get_query_object but we need to resolve differences in what the
82f7d8b2 837 * 2 variants call
61fe4988 838 *
26728d3f 839 * @param $entity
cf470720
TO
840 * @param array $params
841 * As passed into api get or getcount function.
842 * @param array $additional_options
843 * Array of options (so we can modify the filter).
844 * @param bool $getCount
845 * Are we just after the count.
26728d3f 846 *
2241036a 847 * @return array
6a488035 848 */
9b873358 849function _civicrm_api3_get_using_query_object($entity, $params, $additional_options = array(), $getCount = NULL) {
244bbdd8 850 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
6a488035 851 // Convert id to e.g. contact_id
244bbdd8
CW
852 if (empty($params[$lowercase_entity . '_id']) && isset($params['id'])) {
853 $params[$lowercase_entity . '_id'] = $params['id'];
6a488035
TO
854 }
855 unset($params['id']);
856
857 $options = _civicrm_api3_get_options_from_params($params, TRUE);
858
859 $inputParams = array_merge(
860 CRM_Utils_Array::value('input_params', $options, array()),
861 CRM_Utils_Array::value('input_params', $additional_options, array())
862 );
863 $returnProperties = array_merge(
864 CRM_Utils_Array::value('return', $options, array()),
865 CRM_Utils_Array::value('return', $additional_options, array())
866 );
9b873358 867 if (empty($returnProperties)) {
53ed8466 868 $returnProperties = NULL;
6a488035 869 }
9b873358 870 if (!empty($params['check_permissions'])) {
6a488035
TO
871 // we will filter query object against getfields
872 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
873 // we need to add this in as earlier in this function 'id' was unset in favour of $entity_id
244bbdd8 874 $fields['values'][$lowercase_entity . '_id'] = array();
6a488035 875 $varsToFilter = array('returnProperties', 'inputParams');
9b873358
TO
876 foreach ($varsToFilter as $varToFilter) {
877 if (!is_array($$varToFilter)) {
6a488035
TO
878 continue;
879 }
880 //I was going to throw an exception rather than silently filter out - but
881 //would need to diff out of exceptions arr other keys like 'options', 'return', 'api. etcetc
882 //so we are silently ignoring parts of their request
883 //$exceptionsArr = array_diff(array_keys($$varToFilter), array_keys($fields['values']));
884 $$varToFilter = array_intersect_key($$varToFilter, $fields['values']);
885 }
886 }
35671d00 887 $options = array_merge($options, $additional_options);
6a488035
TO
888 $sort = CRM_Utils_Array::value('sort', $options, NULL);
889 $offset = CRM_Utils_Array::value('offset', $options, NULL);
890 $limit = CRM_Utils_Array::value('limit', $options, NULL);
891 $smartGroupCache = CRM_Utils_Array::value('smartGroupCache', $params);
892
9b873358 893 if ($getCount) {
6a488035
TO
894 $limit = NULL;
895 $returnProperties = NULL;
896 }
897
abb4c597 898 if (substr($sort, 0, 2) == 'id') {
244bbdd8 899 $sort = $lowercase_entity . "_" . $sort;
abb4c597 900 }
901
6a488035 902 $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams);
d031c654 903
35671d00 904 $skipPermissions = !empty($params['check_permissions']) ? 0 : 1;
78c0bfc0 905
6a488035
TO
906 list($entities, $options) = CRM_Contact_BAO_Query::apiQuery(
907 $newParams,
908 $returnProperties,
909 NULL,
910 $sort,
35671d00 911 $offset,
6a488035
TO
912 $limit,
913 $smartGroupCache,
914 $getCount,
915 $skipPermissions
916 );
971d41b1
CW
917 if ($getCount) {
918 // only return the count of contacts
6a488035
TO
919 return $entities;
920 }
921
922 return $entities;
923}
11e09c59 924
82f7d8b2 925/**
61fe4988
EM
926 * Get dao query object based on input params.
927 *
82f7d8b2
EM
928 * Ideally this would be merged with _civicrm_get_using_query_object but we need to resolve differences in what the
929 * 2 variants call
930 *
931 * @param array $params
932 * @param string $mode
933 * @param string $entity
61fe4988 934 *
971d41b1
CW
935 * @return array
936 * [CRM_Core_DAO|CRM_Contact_BAO_Query]
82f7d8b2
EM
937 */
938function _civicrm_api3_get_query_object($params, $mode, $entity) {
971d41b1
CW
939 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
940 $sort = CRM_Utils_Array::value('sort', $options, NULL);
941 $offset = CRM_Utils_Array::value('offset', $options);
942 $rowCount = CRM_Utils_Array::value('limit', $options);
943 $inputParams = CRM_Utils_Array::value('input_params', $options, array());
82f7d8b2
EM
944 $returnProperties = CRM_Utils_Array::value('return', $options, NULL);
945 if (empty($returnProperties)) {
946 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
947 }
948
3c151c70 949 $newParams = CRM_Contact_BAO_Query::convertFormValues($inputParams, 0, FALSE, $entity);
82f7d8b2 950 $query = new CRM_Contact_BAO_Query($newParams, $returnProperties, NULL,
835307a7
EM
951 FALSE, FALSE, $mode,
952 empty($params['check_permissions'])
82f7d8b2
EM
953 );
954 list($select, $from, $where, $having) = $query->query();
955
956 $sql = "$select $from $where $having";
957
958 if (!empty($sort)) {
959 $sql .= " ORDER BY $sort ";
960 }
22e263ad 961 if (!empty($rowCount)) {
82f7d8b2
EM
962 $sql .= " LIMIT $offset, $rowCount ";
963 }
964 $dao = CRM_Core_DAO::executeQuery($sql);
965 return array($dao, $query);
966}
967
11e09c59 968/**
61fe4988
EM
969 * Function transfers the filters being passed into the DAO onto the params object.
970 *
0298287b 971 * @deprecated DAO based retrieval is being phased out.
972 *
a75c13cc
EM
973 * @param CRM_Core_DAO $dao
974 * @param array $params
975 * @param bool $unique
0f3699bf 976 * @param array $extraSql
977 * API specific queries eg for event isCurrent would be converted to
978 * $extraSql['where'] = array('civicrm_event' => array('(start_date >= CURDATE() || end_date >= CURDATE())'));
a75c13cc
EM
979 *
980 * @throws API_Exception
981 * @throws Exception
6a488035 982 */
0f3699bf 983function _civicrm_api3_dao_set_filter(&$dao, $params, $unique = TRUE, $extraSql = array()) {
244bbdd8
CW
984 $entity = _civicrm_api_get_entity_name_from_dao($dao);
985 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
986 if (!empty($params[$lowercase_entity . "_id"]) && empty($params['id'])) {
6a488035 987 //if entity_id is set then treat it as ID (will be overridden by id if set)
244bbdd8 988 $params['id'] = $params[$lowercase_entity . "_id"];
6a488035 989 }
461c9a60
EM
990 $allfields = _civicrm_api3_build_fields_array($dao, $unique);
991 $fields = array_intersect(array_keys($allfields), array_keys($params));
3c70d501 992
993 $options = _civicrm_api3_get_options_from_params($params);
6a488035
TO
994 //apply options like sort
995 _civicrm_api3_apply_options_to_dao($params, $dao, $entity);
996
997 //accept filters like filter.activity_date_time_high
998 // std is now 'filters' => ..
999 if (strstr(implode(',', array_keys($params)), 'filter')) {
1000 if (isset($params['filters']) && is_array($params['filters'])) {
1001 foreach ($params['filters'] as $paramkey => $paramvalue) {
1002 _civicrm_api3_apply_filters_to_dao($paramkey, $paramvalue, $dao);
1003 }
1004 }
1005 else {
1006 foreach ($params as $paramkey => $paramvalue) {
1007 if (strstr($paramkey, 'filter')) {
1008 _civicrm_api3_apply_filters_to_dao(substr($paramkey, 7), $paramvalue, $dao);
1009 }
1010 }
1011 }
1012 }
6a488035
TO
1013 if (!$fields) {
1014 $fields = array();
1015 }
1016
1017 foreach ($fields as $field) {
1018 if (is_array($params[$field])) {
1019 //get the actual fieldname from db
1020 $fieldName = $allfields[$field]['name'];
a038992c 1021 $where = CRM_Core_DAO::createSqlFilter($fieldName, $params[$field], 'String');
22e263ad 1022 if (!empty($where)) {
a038992c 1023 $dao->whereAdd($where);
6a488035
TO
1024 }
1025 }
1026 else {
1027 if ($unique) {
ed22af33
TO
1028 $daoFieldName = $allfields[$field]['name'];
1029 if (empty($daoFieldName)) {
1030 throw new API_Exception("Failed to determine field name for \"$field\"");
1031 }
1032 $dao->{$daoFieldName} = $params[$field];
6a488035
TO
1033 }
1034 else {
1035 $dao->$field = $params[$field];
1036 }
1037 }
1038 }
0f3699bf 1039 if (!empty($extraSql['where'])) {
1040 foreach ($extraSql['where'] as $table => $sqlWhere) {
1041 foreach ($sqlWhere as $where) {
1042 $dao->whereAdd($where);
1043 }
1044 }
1045 }
972322c5 1046 if (!empty($options['return']) && is_array($options['return']) && empty($options['is_count'])) {
6a488035 1047 $dao->selectAdd();
9d32e6f7
EM
1048 // Ensure 'id' is included.
1049 $options['return']['id'] = TRUE;
35671d00 1050 $allfields = _civicrm_api3_get_unique_name_array($dao);
3c70d501 1051 $returnMatched = array_intersect(array_keys($options['return']), $allfields);
6a488035 1052 foreach ($returnMatched as $returnValue) {
48e1c0dc 1053 $dao->selectAdd($returnValue);
6a488035 1054 }
48e1c0dc 1055
61fe4988
EM
1056 // Not already matched on the field names.
1057 $unmatchedFields = array_diff(
48e1c0dc 1058 array_keys($options['return']),
1059 $returnMatched
1060 );
1061
1062 $returnUniqueMatched = array_intersect(
1063 $unmatchedFields,
9d32e6f7
EM
1064 // But a match for the field keys.
1065 array_flip($allfields)
48e1c0dc 1066 );
9b873358 1067 foreach ($returnUniqueMatched as $uniqueVal) {
6a488035 1068 $dao->selectAdd($allfields[$uniqueVal]);
6a488035 1069 }
6a488035 1070 }
6e1bb60c 1071 $dao->setApiFilter($params);
6a488035
TO
1072}
1073
11e09c59 1074/**
61fe4988
EM
1075 * Apply filters (e.g. high, low) to DAO object (prior to find).
1076 *
cf470720
TO
1077 * @param string $filterField
1078 * Field name of filter.
1079 * @param string $filterValue
1080 * Field value of filter.
1081 * @param object $dao
1082 * DAO object.
6a488035
TO
1083 */
1084function _civicrm_api3_apply_filters_to_dao($filterField, $filterValue, &$dao) {
1085 if (strstr($filterField, 'high')) {
1086 $fieldName = substr($filterField, 0, -5);
1087 $dao->whereAdd("($fieldName <= $filterValue )");
1088 }
1089 if (strstr($filterField, 'low')) {
1090 $fieldName = substr($filterField, 0, -4);
1091 $dao->whereAdd("($fieldName >= $filterValue )");
1092 }
9b873358 1093 if ($filterField == 'is_current' && $filterValue == 1) {
6a488035
TO
1094 $todayStart = date('Ymd000000', strtotime('now'));
1095 $todayEnd = date('Ymd235959', strtotime('now'));
1096 $dao->whereAdd("(start_date <= '$todayStart' OR start_date IS NULL) AND (end_date >= '$todayEnd' OR end_date IS NULL)");
9b873358 1097 if (property_exists($dao, 'is_active')) {
6a488035
TO
1098 $dao->whereAdd('is_active = 1');
1099 }
1100 }
1101}
11e09c59
TO
1102
1103/**
6a488035 1104 * Get sort, limit etc options from the params - supporting old & new formats.
9d32e6f7
EM
1105 *
1106 * Get returnProperties for legacy
26728d3f 1107 *
cf470720
TO
1108 * @param array $params
1109 * Params array as passed into civicrm_api.
1110 * @param bool $queryObject
9d32e6f7 1111 * Is this supporting a queryObject api (e.g contact) - if so we support more options.
16b10e64 1112 * for legacy report & return a unique fields array
26728d3f
E
1113 *
1114 * @param string $entity
1115 * @param string $action
1116 *
1cfa04c4 1117 * @throws API_Exception
a6c01b45 1118 * @return array
72b3a70c 1119 * options extracted from params
6a488035 1120 */
53ed8466 1121function _civicrm_api3_get_options_from_params(&$params, $queryObject = FALSE, $entity = '', $action = '') {
4846df91 1122 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
972322c5 1123 $is_count = FALSE;
6a488035
TO
1124 $sort = CRM_Utils_Array::value('sort', $params, 0);
1125 $sort = CRM_Utils_Array::value('option.sort', $params, $sort);
1126 $sort = CRM_Utils_Array::value('option_sort', $params, $sort);
1127
1128 $offset = CRM_Utils_Array::value('offset', $params, 0);
1129 $offset = CRM_Utils_Array::value('option.offset', $params, $offset);
1130 // dear PHP thought it would be a good idea to transform a.b into a_b in the get/post
1131 $offset = CRM_Utils_Array::value('option_offset', $params, $offset);
1132
1133 $limit = CRM_Utils_Array::value('rowCount', $params, 25);
1134 $limit = CRM_Utils_Array::value('option.limit', $params, $limit);
1135 $limit = CRM_Utils_Array::value('option_limit', $params, $limit);
1136
1137 if (is_array(CRM_Utils_Array::value('options', $params))) {
972322c5 1138 // is count is set by generic getcount not user
1139 $is_count = CRM_Utils_Array::value('is_count', $params['options']);
6a488035
TO
1140 $offset = CRM_Utils_Array::value('offset', $params['options'], $offset);
1141 $limit = CRM_Utils_Array::value('limit', $params['options'], $limit);
1142 $sort = CRM_Utils_Array::value('sort', $params['options'], $sort);
1143 }
1144
1145 $returnProperties = array();
1146 // handle the format return =sort_name,display_name...
1147 if (array_key_exists('return', $params)) {
1148 if (is_array($params['return'])) {
1149 $returnProperties = array_fill_keys($params['return'], 1);
1150 }
1151 else {
1152 $returnProperties = explode(',', str_replace(' ', '', $params['return']));
1153 $returnProperties = array_fill_keys($returnProperties, 1);
1154 }
1155 }
35671d00 1156 if ($entity && $action == 'get') {
a7488080 1157 if (!empty($returnProperties['id'])) {
4846df91 1158 $returnProperties[$lowercase_entity . '_id'] = 1;
6a488035
TO
1159 unset($returnProperties['id']);
1160 }
9b873358 1161 switch (trim(strtolower($sort))) {
35671d00
TO
1162 case 'id':
1163 case 'id desc':
1164 case 'id asc':
4846df91 1165 $sort = str_replace('id', $lowercase_entity . '_id', $sort);
6a488035
TO
1166 }
1167 }
1168
6a488035 1169 $options = array(
ba93e7ad
CW
1170 'offset' => CRM_Utils_Rule::integer($offset) ? $offset : NULL,
1171 'sort' => CRM_Utils_Rule::string($sort) ? $sort : NULL,
1172 'limit' => CRM_Utils_Rule::integer($limit) ? $limit : NULL,
6313f1f7 1173 'is_count' => $is_count,
9af2925b 1174 'return' => !empty($returnProperties) ? $returnProperties : array(),
6a488035 1175 );
972322c5 1176
13c1cf91 1177 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
ba93e7ad
CW
1178 throw new API_Exception('invalid string in sort options');
1179 }
13c1cf91 1180
6a488035
TO
1181 if (!$queryObject) {
1182 return $options;
1183 }
1184 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
2b28667f 1185 // if the query object is being used this should be used
6a488035
TO
1186 $inputParams = array();
1187 $legacyreturnProperties = array();
1188 $otherVars = array(
35671d00 1189 'sort', 'offset', 'rowCount', 'options', 'return',
dba939ce 1190 'version', 'prettyprint', 'check_permissions', 'sequential',
6a488035
TO
1191 );
1192 foreach ($params as $n => $v) {
1193 if (substr($n, 0, 7) == 'return.') {
1194 $legacyreturnProperties[substr($n, 7)] = $v;
1195 }
13c1cf91 1196 elseif ($n == 'id') {
4846df91 1197 $inputParams[$lowercase_entity . '_id'] = $v;
6a488035 1198 }
35671d00
TO
1199 elseif (in_array($n, $otherVars)) {
1200 }
13c1cf91 1201 else {
6a488035 1202 $inputParams[$n] = $v;
13c1cf91 1203 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
ba93e7ad
CW
1204 throw new API_Exception('invalid string');
1205 }
6a488035
TO
1206 }
1207 }
1208 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
1209 $options['input_params'] = $inputParams;
1210 return $options;
1211}
11e09c59
TO
1212
1213/**
9d32e6f7 1214 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
26728d3f 1215 *
cf470720
TO
1216 * @param array $params
1217 * Params array as passed into civicrm_api.
1218 * @param object $dao
1219 * DAO object.
26728d3f 1220 * @param $entity
6a488035
TO
1221 */
1222function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
1223
35671d00 1224 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
22e263ad
TO
1225 if (!$options['is_count']) {
1226 if (!empty($options['limit'])) {
35671d00 1227 $dao->limit((int) $options['offset'], (int) $options['limit']);
ebddc2d9 1228 }
972322c5 1229 if (!empty($options['sort'])) {
1230 $dao->orderBy($options['sort']);
1231 }
6a488035
TO
1232 }
1233}
1234
11e09c59 1235/**
9d32e6f7
EM
1236 * Build fields array.
1237 *
1238 * This is the array of fields as it relates to the given DAO
6a488035 1239 * returns unique fields as keys by default but if set but can return by DB fields
971d41b1
CW
1240 *
1241 * @param CRM_Core_DAO $bao
645ee340 1242 * @param bool $unique
971d41b1
CW
1243 *
1244 * @return array
6a488035
TO
1245 */
1246function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
1247 $fields = $bao->fields();
1248 if ($unique) {
9b873358 1249 if (empty($fields['id'])) {
4846df91
CW
1250 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
1251 $fields['id'] = $fields[$lowercase_entity . '_id'];
1252 unset($fields[$lowercase_entity . '_id']);
6a488035
TO
1253 }
1254 return $fields;
1255 }
1256
1257 foreach ($fields as $field) {
1258 $dbFields[$field['name']] = $field;
1259 }
1260 return $dbFields;
1261}
1262
11e09c59 1263/**
9d32e6f7
EM
1264 * Build fields array.
1265 *
1266 * This is the array of fields as it relates to the given DAO
6a488035 1267 * returns unique fields as keys by default but if set but can return by DB fields
971d41b1 1268 *
488e7aba 1269 * @param CRM_Core_DAO $bao
fb7f68eb 1270 *
971d41b1 1271 * @return array
6a488035
TO
1272 */
1273function _civicrm_api3_get_unique_name_array(&$bao) {
1274 $fields = $bao->fields();
1275 foreach ($fields as $field => $values) {
35671d00 1276 $uniqueFields[$field] = CRM_Utils_Array::value('name', $values, $field);
6a488035
TO
1277 }
1278 return $uniqueFields;
1279}
1280
6a488035 1281/**
9d32e6f7 1282 * Converts an DAO object to an array.
6a488035 1283 *
0298287b 1284 * @deprecated - DAO based retrieval is being phased out.
1285 *
cf470720
TO
1286 * @param CRM_Core_DAO $dao
1287 * Object to convert.
c490a46a 1288 * @param array $params
26728d3f
E
1289 * @param bool $uniqueFields
1290 * @param string $entity
941feb14
EM
1291 * @param bool $autoFind
1292 *
26728d3f 1293 * @return array
6a488035 1294 */
ab5fa8f2 1295function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
6a488035 1296 $result = array();
22e263ad 1297 if (isset($params['options']) && !empty($params['options']['is_count'])) {
972322c5 1298 return $dao->count();
1299 }
ab5fa8f2
TO
1300 if (empty($dao)) {
1301 return array();
1302 }
1303 if ($autoFind && !$dao->find()) {
6a488035
TO
1304 return array();
1305 }
1306
22e263ad 1307 if (isset($dao->count)) {
972322c5 1308 return $dao->count;
1309 }
6a488035 1310
0f3699bf 1311 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
6a488035
TO
1312 while ($dao->fetch()) {
1313 $tmp = array();
1314 foreach ($fields as $key) {
1315 if (array_key_exists($key, $dao)) {
1316 // not sure on that one
1317 if ($dao->$key !== NULL) {
1318 $tmp[$key] = $dao->$key;
1319 }
1320 }
1321 }
1322 $result[$dao->id] = $tmp;
8295042e 1323
22e263ad 1324 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
6a488035
TO
1325 _civicrm_api3_custom_data_get($result[$dao->id], $entity, $dao->id);
1326 }
1327 }
1328
6a488035
TO
1329 return $result;
1330}
1331
8295042e 1332/**
61fe4988
EM
1333 * Determine if custom fields need to be retrieved.
1334 *
8295042e
EM
1335 * We currently retrieve all custom fields or none at this level so if we know the entity
1336 * && 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
1337 * @todo filter so only required fields are queried
1338 *
cf470720
TO
1339 * @param string $entity
1340 * Entity name in CamelCase.
971d41b1 1341 * @param array $params
8295042e
EM
1342 *
1343 * @return bool
1344 */
1345function _civicrm_api3_custom_fields_are_required($entity, $params) {
1346 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery::$extendsMap)) {
1347 return FALSE;
1348 }
1349 $options = _civicrm_api3_get_options_from_params($params);
61fe4988 1350 // We check for possibility of 'custom' => 1 as well as specific custom fields.
8295042e 1351 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
22e263ad 1352 if (stristr($returnString, 'custom')) {
8295042e
EM
1353 return TRUE;
1354 }
1355}
2b28667f 1356
6a488035 1357/**
61fe4988 1358 * Converts an object to an array.
6a488035 1359 *
cf470720
TO
1360 * @param object $dao
1361 * (reference) object to convert.
1362 * @param array $values
1363 * (reference) array.
26728d3f 1364 * @param array|bool $uniqueFields
6a488035
TO
1365 */
1366function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1367
1368 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1369 foreach ($fields as $key => $value) {
1370 if (array_key_exists($key, $dao)) {
1371 $values[$key] = $dao->$key;
1372 }
1373 }
1374}
1375
11e09c59 1376/**
9d32e6f7
EM
1377 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1378 *
645ee340
EM
1379 * @param $dao
1380 * @param $values
9d32e6f7 1381 *
645ee340 1382 * @return array
6a488035
TO
1383 */
1384function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1385 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1386}
1387
1388/**
9d32e6f7 1389 * Format custom parameters.
6a488035
TO
1390 *
1391 * @param array $params
1392 * @param array $values
cf470720
TO
1393 * @param string $extends
1394 * Entity that this custom field extends (e.g. contribution, event, contact).
1395 * @param string $entityId
1396 * ID of entity per $extends.
6a488035
TO
1397 */
1398function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1399 $values['custom'] = array();
e9f2f3b1
EM
1400 $checkCheckBoxField = FALSE;
1401 $entity = $extends;
22e263ad 1402 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
e9f2f3b1
EM
1403 $entity = 'Contact';
1404 }
1405
1406 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
22e263ad 1407 if (!$fields['is_error']) {
e9f2f3b1
EM
1408 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1409 $fields = $fields['values'];
1410 $checkCheckBoxField = TRUE;
1411 }
1412
6a488035
TO
1413 foreach ($params as $key => $value) {
1414 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField::getKeyID($key, TRUE);
35671d00 1415 if ($customFieldID && (!is_null($value))) {
24e4bf08 1416 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
e9f2f3b1
EM
1417 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1418 }
4c16123d 1419
6a488035 1420 CRM_Core_BAO_CustomField::formatCustomField($customFieldID, $values['custom'],
211353a8 1421 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
6a488035
TO
1422 );
1423 }
1424 }
1425}
1426
8295042e 1427/**
9d32e6f7
EM
1428 * Format parameters for create action.
1429 *
c490a46a 1430 * @param array $params
8295042e
EM
1431 * @param $entity
1432 */
1433function _civicrm_api3_format_params_for_create(&$params, $entity) {
1434 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1435
1436 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery::$extendsMap, array_fill_keys($nonGenericEntities, 1));
22e263ad 1437 if (!array_key_exists($entity, $customFieldEntities)) {
8295042e
EM
1438 return;
1439 }
1440 $values = array();
1441 _civicrm_api3_custom_format_params($params, $values, $entity);
1442 $params = array_merge($params, $values);
1443}
1444
e9f2f3b1 1445/**
9d32e6f7
EM
1446 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1447 *
1448 * We should look at pushing to BAO function
e9f2f3b1
EM
1449 * 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
1450 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1451 *
1452 * 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
1453 * don't touch - lots of very cautious code in here
1454 *
4ee91976
EM
1455 * The resulting array should look like
1456 * array(
1457 * 'key' => 1,
1458 * 'key1' => 1,
1459 * );
1460 *
1461 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1462 *
e9f2f3b1
EM
1463 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1464 * be fixed in future
1465 *
9d32e6f7
EM
1466 * @param mixed $checkboxFieldValue
1467 * @param string $customFieldLabel
1468 * @param string $entity
e9f2f3b1
EM
1469 */
1470function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1471
1472 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO::VALUE_SEPARATOR)) {
9d32e6f7 1473 // We can assume it's pre-formatted.
e9f2f3b1
EM
1474 return;
1475 }
1476 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1477 if (!empty($options['is_error'])) {
9d32e6f7 1478 // The check is precautionary - can probably be removed later.
e9f2f3b1
EM
1479 return;
1480 }
1481
1482 $options = $options['values'];
1483 $validValue = TRUE;
1484 if (is_array($checkboxFieldValue)) {
1485 foreach ($checkboxFieldValue as $key => $value) {
1486 if (!array_key_exists($key, $options)) {
1487 $validValue = FALSE;
1488 }
1489 }
1490 if ($validValue) {
1491 // we have been passed an array that is already in the 'odd' custom field format
1492 return;
1493 }
1494 }
1495
1496 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1497 // if the array only has one item we'll treat it like any other string
1498 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1499 $possibleValue = reset($checkboxFieldValue);
1500 }
1501 if (is_string($checkboxFieldValue)) {
1502 $possibleValue = $checkboxFieldValue;
1503 }
1504 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1505 $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . $possibleValue . CRM_Core_DAO::VALUE_SEPARATOR;
1506 return;
1507 }
1508 elseif (is_array($checkboxFieldValue)) {
1509 // so this time around we are considering the values in the array
1510 $possibleValues = $checkboxFieldValue;
1511 $formatValue = TRUE;
1512 }
1513 elseif (stristr($checkboxFieldValue, ',')) {
1514 $formatValue = TRUE;
e834996a
EM
1515 //lets see if we should separate it - we do this near the end so we
1516 // ensure we have already checked that the comma is not part of a legitimate match
1517 // and of course, we don't make any changes if we don't now have matches
e9f2f3b1
EM
1518 $possibleValues = explode(',', $checkboxFieldValue);
1519 }
1520 else {
1521 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1522 return;
1523 }
1524
1525 foreach ($possibleValues as $index => $possibleValue) {
1526 if (array_key_exists($possibleValue, $options)) {
1527 // 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)
1528 }
1529 elseif (array_key_exists(trim($possibleValue), $options)) {
1530 $possibleValues[$index] = trim($possibleValue);
1531 }
1532 else {
1533 $formatValue = FALSE;
1534 }
1535 }
1536 if ($formatValue) {
1537 $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $possibleValues) . CRM_Core_DAO::VALUE_SEPARATOR;
1538 }
1539}
1540
6a488035 1541/**
9d32e6f7
EM
1542 * This function ensures that we have the right input parameters.
1543 *
6a488035 1544 * @deprecated
6a488035
TO
1545 *
1546 * This function is only called when $dao is passed into verify_mandatory.
1547 * The practice of passing $dao into verify_mandatory turned out to be
9d32e6f7 1548 * unsatisfactory as the required fields @ the dao level is so different to the abstract
6a488035 1549 * api level. Hence the intention is to remove this function
9d32e6f7 1550 * & the associated param from verify_mandatory
6a488035 1551 *
cf470720
TO
1552 * @param array $params
1553 * Associative array of property name/value.
244bbdd8 1554 * pairs to insert in new history.
c490a46a 1555 * @param string $daoName
26728d3f
E
1556 * @param bool $return
1557 *
e4f46be0 1558 * @daoName string DAO to check params against
6a488035 1559 *
2241036a 1560 * @return bool
9d32e6f7 1561 * Should the missing fields be returned as an array (core error created as default)
c866eb5f 1562 * true if all fields present, depending on $result a core error is created of an array of missing fields is returned
6a488035
TO
1563 */
1564function _civicrm_api3_check_required_fields($params, $daoName, $return = FALSE) {
1565 //@deprecated - see notes
1566 if (isset($params['extends'])) {
1567 if (($params['extends'] == 'Activity' ||
1568 $params['extends'] == 'Phonecall' ||
1569 $params['extends'] == 'Meeting' ||
1570 $params['extends'] == 'Group' ||
1571 $params['extends'] == 'Contribution'
1572 ) &&
1573 ($params['style'] == 'Tab')
1574 ) {
1575 return civicrm_api3_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
1576 }
1577 }
1578
1579 $dao = new $daoName();
1580 $fields = $dao->fields();
1581
1582 $missing = array();
1583 foreach ($fields as $k => $v) {
1584 if ($v['name'] == 'id') {
1585 continue;
1586 }
1587
a7488080 1588 if (!empty($v['required'])) {
6a488035
TO
1589 // 0 is a valid input for numbers, CRM-8122
1590 if (!isset($params[$k]) || (empty($params[$k]) && !($params[$k] === 0))) {
1591 $missing[] = $k;
1592 }
1593 }
1594 }
1595
1596 if (!empty($missing)) {
1597 if (!empty($return)) {
1598 return $missing;
1599 }
1600 else {
1601 return civicrm_api3_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not present"));
1602 }
1603 }
1604
1605 return TRUE;
1606}
1607
11e09c59 1608/**
9d32e6f7 1609 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
6a488035 1610 *
cf470720
TO
1611 * @param string $bao_name
1612 * Name of BAO.
1613 * @param array $params
1614 * Params from api.
1615 * @param bool $returnAsSuccess
1616 * Return in api success format.
26728d3f 1617 * @param string $entity
01c8287d
TO
1618 * @param CRM_Utils_SQL_Select|NULL $sql
1619 * Extra SQL bits to add to the query. For filtering current events, this might be:
1620 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
0f3699bf 1621 * @param bool $uniqueFields
1622 * Should unique field names be returned (for backward compatibility)
26728d3f
E
1623 *
1624 * @return array
6a488035 1625 */
01c8287d 1626function _civicrm_api3_basic_get($bao_name, &$params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
6a271fe0 1627
6a488035 1628 if ($returnAsSuccess) {
01c8287d 1629 return civicrm_api3_create_success(_civicrm_api3_get_using_utils_sql($bao_name, $params, $uniqueFields, $sql), $params, $entity, 'get');
6a488035
TO
1630 }
1631 else {
01c8287d 1632 return _civicrm_api3_get_using_utils_sql($bao_name, $params, $uniqueFields, $sql);
6a488035
TO
1633 }
1634}
1635
11e09c59 1636/**
9d32e6f7 1637 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1cfa04c4 1638 *
cf470720
TO
1639 * @param string $bao_name
1640 * Name of BAO Class.
1641 * @param array $params
1642 * Parameters passed into the api call.
1643 * @param string $entity
1644 * Entity - pass in if entity is non-standard & required $ids array.
1cfa04c4
EM
1645 *
1646 * @throws API_Exception
26728d3f 1647 * @return array
6a488035 1648 */
53ed8466 1649function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
8295042e 1650 _civicrm_api3_format_params_for_create($params, $entity);
6a488035 1651 $args = array(&$params);
244bbdd8 1652 if ($entity) {
6a488035
TO
1653 $ids = array($entity => CRM_Utils_Array::value('id', $params));
1654 $args[] = &$ids;
1655 }
acde3ae0 1656
6a488035
TO
1657 if (method_exists($bao_name, 'create')) {
1658 $fct = 'create';
acde3ae0
TO
1659 $fct_name = $bao_name . '::' . $fct;
1660 $bao = call_user_func_array(array($bao_name, $fct), $args);
6a488035
TO
1661 }
1662 elseif (method_exists($bao_name, 'add')) {
1663 $fct = 'add';
acde3ae0
TO
1664 $fct_name = $bao_name . '::' . $fct;
1665 $bao = call_user_func_array(array($bao_name, $fct), $args);
6a488035 1666 }
acde3ae0
TO
1667 else {
1668 $fct_name = '_civicrm_api3_basic_create_fallback';
1669 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
6a488035 1670 }
acde3ae0 1671
6a488035 1672 if (is_null($bao)) {
acde3ae0 1673 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
6a488035 1674 }
736eec43 1675 elseif (is_a($bao, 'CRM_Core_Error')) {
e4f46be0 1676 //some weird circular thing means the error takes itself as an argument
736eec43
E
1677 $msg = $bao->getMessages($bao);
1678 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1679 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1680 // so we need to reset the error object here to avoid getting concatenated errors
1681 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1682 CRM_Core_Error::singleton()->reset();
1683 throw new API_Exception($msg);
1684 }
6a488035
TO
1685 else {
1686 $values = array();
1687 _civicrm_api3_object_to_array($bao, $values[$bao->id]);
504a78f6 1688 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
6a488035
TO
1689 }
1690}
1691
acde3ae0
TO
1692/**
1693 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1694 *
26728d3f 1695 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
acde3ae0
TO
1696 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1697 *
1698 * @param string $bao_name
1699 * @param array $params
916b48b6
VU
1700 *
1701 * @throws API_Exception
9d32e6f7
EM
1702 *
1703 * @return CRM_Core_DAO|NULL
1704 * An instance of the BAO
acde3ae0
TO
1705 */
1706function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
a9739e5d
CW
1707 $dao_name = get_parent_class($bao_name);
1708 if ($dao_name === 'CRM_Core_DAO' || !$dao_name) {
1709 $dao_name = $bao_name;
1710 }
1711 $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($dao_name);
acde3ae0
TO
1712 if (empty($entityName)) {
1713 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1714 'class_name' => $bao_name,
1715 ));
1716 }
1717 $hook = empty($params['id']) ? 'create' : 'edit';
1718
1719 CRM_Utils_Hook::pre($hook, $entityName, CRM_Utils_Array::value('id', $params), $params);
a9739e5d 1720 $instance = new $dao_name();
acde3ae0
TO
1721 $instance->copyValues($params);
1722 $instance->save();
1723 CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance);
1724
1725 return $instance;
1726}
1727
11e09c59 1728/**
9d32e6f7
EM
1729 * Function to do a 'standard' api del.
1730 *
1731 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
3d0d359e 1732 *
100fef9d 1733 * @param string $bao_name
c490a46a 1734 * @param array $params
3d0d359e 1735 *
a6c01b45 1736 * @return array
72b3a70c 1737 * API result array
3d0d359e 1738 * @throws API_Exception
6a488035
TO
1739 */
1740function _civicrm_api3_basic_delete($bao_name, &$params) {
1741
1742 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1743 $args = array(&$params['id']);
1744 if (method_exists($bao_name, 'del')) {
1745 $bao = call_user_func_array(array($bao_name, 'del'), $args);
a65e2e55
CW
1746 if ($bao !== FALSE) {
1747 return civicrm_api3_create_success(TRUE);
1748 }
fb32de45 1749 throw new API_Exception('Could not delete entity id ' . $params['id']);
6a488035
TO
1750 }
1751 elseif (method_exists($bao_name, 'delete')) {
1752 $dao = new $bao_name();
1753 $dao->id = $params['id'];
1754 if ($dao->find()) {
1755 while ($dao->fetch()) {
1756 $dao->delete();
1757 return civicrm_api3_create_success();
1758 }
1759 }
1760 else {
fb32de45 1761 throw new API_Exception('Could not delete entity id ' . $params['id']);
6a488035
TO
1762 }
1763 }
1764
fb32de45 1765 throw new API_Exception('no delete method found');
6a488035
TO
1766}
1767
11e09c59 1768/**
9d32e6f7
EM
1769 * Get custom data for the given entity & Add it to the returnArray.
1770 *
1771 * This looks like 'custom_123' = 'custom string' AND
1772 * 'custom_123_1' = 'custom string'
6a488035
TO
1773 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1774 *
cf470720
TO
1775 * @param array $returnArray
1776 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1777 * @param string $entity
1778 * E.g membership, event.
100fef9d 1779 * @param int $entity_id
cf470720
TO
1780 * @param int $groupID
1781 * Per CRM_Core_BAO_CustomGroup::getTree.
1782 * @param int $subType
1783 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1784 * @param string $subName
1785 * Subtype of entity.
6a488035
TO
1786 */
1787function _civicrm_api3_custom_data_get(&$returnArray, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
9af2925b 1788 $groupTree = CRM_Core_BAO_CustomGroup::getTree($entity,
6a488035
TO
1789 CRM_Core_DAO::$_nullObject,
1790 $entity_id,
1791 $groupID,
b62bc939
EM
1792 NULL,
1793 $subName,
1794 TRUE,
1795 NULL,
1796 TRUE
6a488035
TO
1797 );
1798 $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1, CRM_Core_DAO::$_nullObject);
1799 $customValues = array();
1800 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $customValues);
e0995951
CW
1801 $fieldInfo = array();
1802 foreach ($groupTree as $set) {
1803 $fieldInfo += $set['fields'];
1804 }
6a488035
TO
1805 if (!empty($customValues)) {
1806 foreach ($customValues as $key => $val) {
e0995951
CW
1807 // per standard - return custom_fieldID
1808 $id = CRM_Core_BAO_CustomField::getKeyID($key);
1809 $returnArray['custom_' . $id] = $val;
1810
1811 //not standard - but some api did this so guess we should keep - cheap as chips
1812 $returnArray[$key] = $val;
6a488035 1813
e0995951
CW
1814 // Shim to restore legacy behavior of ContactReference custom fields
1815 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1816 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1817 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
6a488035
TO
1818 }
1819 }
1820 }
1821}
1822
11e09c59 1823/**
9d32e6f7
EM
1824 * Validate fields being passed into API.
1825 *
1826 * This function relies on the getFields function working accurately
6a488035
TO
1827 * for the given API. If error mode is set to TRUE then it will also check
1828 * foreign keys
1829 *
1830 * As of writing only date was implemented.
9d32e6f7 1831 *
6a488035
TO
1832 * @param string $entity
1833 * @param string $action
cf470720
TO
1834 * @param array $params
1835 * -.
1836 * @param array $fields
1837 * Response from getfields all variables are the same as per civicrm_api.
1838 * @param bool $errorMode
1839 * ErrorMode do intensive post fail checks?.
9d32e6f7 1840 *
916b48b6 1841 * @throws Exception
6a488035 1842 */
35671d00 1843function _civicrm_api3_validate_fields($entity, $action, &$params, $fields, $errorMode = FALSE) {
2930d67a 1844 //CRM-15792 handle datetime for custom fields below code handles chain api call
1845 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1846 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1847 foreach ($chainApikeys as $key => $value) {
1848 if (is_array($params[$key])) {
1849 $chainApiParams = array_intersect_key($fields, $params[$key]);
1850 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1851 }
1852 }
1853 }
94359f7e 1854 $fields = array_intersect_key($fields, $params);
2930d67a 1855 if (!empty($chainApiParams)) {
1856 $fields = array_merge($fields, $chainApiParams);
1857 }
70f7ba9e 1858 foreach ($fields as $fieldName => $fieldInfo) {
6a488035
TO
1859 switch (CRM_Utils_Array::value('type', $fieldInfo)) {
1860 case CRM_Utils_Type::T_INT:
1861 //field is of type integer
70f7ba9e 1862 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
6a488035
TO
1863 break;
1864
2930d67a 1865 case CRM_Utils_Type::T_DATE:
1866 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
9bee5ea2 1867 case CRM_Utils_Type::T_TIMESTAMP:
6a488035 1868 //field is of type date or datetime
2930d67a 1869 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1870 $dateParams = &$params[$customFields[$fieldName]];
1871 }
1872 else {
1873 $dateParams = &$params;
1874 }
1875 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
6a488035 1876 break;
83abdecd 1877
971d41b1
CW
1878 case 32:
1879 //blob
70f7ba9e 1880 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
6a488035 1881 break;
6a488035 1882
83abdecd 1883 case CRM_Utils_Type::T_STRING:
70f7ba9e 1884 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
6a488035
TO
1885 break;
1886
1887 case CRM_Utils_Type::T_MONEY:
afa0b07c 1888 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1889 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1890 break;
1891 }
971d41b1 1892 foreach ((array) $fieldValue as $fieldvalue) {
7d543448 1893 if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) {
3a6eb174 1894 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1895 }
6a488035 1896 }
3a6eb174 1897 break;
6a488035
TO
1898 }
1899
1900 // intensive checks - usually only called after DB level fail
1901 if (!empty($errorMode) && strtolower($action) == 'create') {
a7488080 1902 if (!empty($fieldInfo['FKClassName'])) {
3c151c70 1903 if (!empty($fieldValue)) {
70f7ba9e 1904 _civicrm_api3_validate_constraint($params, $fieldName, $fieldInfo);
6a488035 1905 }
a7488080 1906 elseif (!empty($fieldInfo['required'])) {
70f7ba9e 1907 throw new Exception("DB Constraint Violation - possibly $fieldName should possibly be marked as mandatory for this API. If so, please raise a bug report");
6a488035
TO
1908 }
1909 }
a7488080 1910 if (!empty($fieldInfo['api.unique'])) {
6a488035 1911 $params['entity'] = $entity;
8adf88cf 1912 _civicrm_api3_validate_unique_key($params, $fieldName);
6a488035
TO
1913 }
1914 }
1915 }
1916}
1917
11e09c59 1918/**
6a488035 1919 * Validate date fields being passed into API.
9d32e6f7 1920 *
6a488035
TO
1921 * It currently converts both unique fields and DB field names to a mysql date.
1922 * @todo - probably the unique field handling & the if exists handling is now done before this
1923 * function is reached in the wrapper - can reduce this code down to assume we
1924 * are only checking the passed in field
1925 *
1926 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1927 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1928 *
cf470720
TO
1929 * @param array $params
1930 * Params from civicrm_api.
1931 * @param string $fieldName
1932 * Uniquename of field being checked.
1933 * @param array $fieldInfo
1934 * Array of fields from getfields function.
9d32e6f7 1935 *
916b48b6 1936 * @throws Exception
6a488035 1937 */
70f7ba9e 1938function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
afa0b07c 1939 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1940 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1941 return;
1942 }
6a488035 1943 //should we check first to prevent it from being copied if they have passed in sql friendly format?
a7488080 1944 if (!empty($params[$fieldInfo['name']])) {
3c151c70 1945 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
6a488035 1946 }
3c151c70 1947 if ((CRM_Utils_Array::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1948 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
9bee5ea2 1949 }
afa0b07c 1950
1951 if (!empty($op)) {
1952 $params[$fieldName][$op] = $fieldValue;
1953 }
1954 else {
1955 $params[$fieldName] = $fieldValue;
9bee5ea2
EM
1956 }
1957}
1958
1959/**
9d32e6f7
EM
1960 * Convert date into BAO friendly date.
1961 *
1962 * We accept 'whatever strtotime accepts'
9bee5ea2
EM
1963 *
1964 * @param string $dateValue
100fef9d 1965 * @param string $fieldName
9bee5ea2
EM
1966 * @param $fieldType
1967 *
1968 * @throws Exception
9bee5ea2
EM
1969 * @return mixed
1970 */
1971function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1972 if (is_array($dateValue)) {
1973 foreach ($dateValue as $key => $value) {
1974 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
6a488035 1975 }
9bee5ea2
EM
1976 return $dateValue;
1977 }
1978 if (strtotime($dateValue) === FALSE) {
1979 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
6a488035 1980 }
9bee5ea2
EM
1981 $format = ($fieldType == CRM_Utils_Type::T_DATE) ? 'Ymd000000' : 'YmdHis';
1982 return CRM_Utils_Date::processDate($dateValue, NULL, FALSE, $format);
6a488035 1983}
11e09c59
TO
1984
1985/**
6a488035
TO
1986 * Validate foreign constraint fields being passed into API.
1987 *
645ee340 1988 * @param mixed $fieldValue
cf470720
TO
1989 * @param string $fieldName
1990 * Uniquename of field being checked.
1991 * @param array $fieldInfo
1992 * Array of fields from getfields function.
9d32e6f7 1993 *
645ee340 1994 * @throws \API_Exception
6a488035 1995 */
3c151c70 1996function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
971d41b1
CW
1997 $daoName = $fieldInfo['FKClassName'];
1998 $dao = new $daoName();
3c151c70 1999 $dao->id = $fieldValue;
6a488035
TO
2000 $dao->selectAdd();
2001 $dao->selectAdd('id');
2002 if (!$dao->find()) {
645ee340 2003 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
6a488035
TO
2004 }
2005}
2006
11e09c59 2007/**
6a488035
TO
2008 * Validate foreign constraint fields being passed into API.
2009 *
cf470720
TO
2010 * @param array $params
2011 * Params from civicrm_api.
2012 * @param string $fieldName
2013 * Uniquename of field being checked.
9d32e6f7 2014 *
916b48b6 2015 * @throws Exception
6a488035 2016 */
8adf88cf 2017function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
afa0b07c 2018 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2019 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
2020 return;
2021 }
6a488035
TO
2022 $existing = civicrm_api($params['entity'], 'get', array(
2023 'version' => $params['version'],
3c151c70 2024 $fieldName => $fieldValue,
6a488035
TO
2025 ));
2026 // an entry already exists for this unique field
2027 if ($existing['count'] == 1) {
2028 // question - could this ever be a security issue?
446f0940 2029 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
6a488035
TO
2030 }
2031}
2032
2033/**
2034 * Generic implementation of the "replace" action.
2035 *
2036 * Replace the old set of entities (matching some given keys) with a new set of
2037 * entities (matching the same keys).
2038 *
b081365f 2039 * @note This will verify that 'values' is present, but it does not directly verify
6a488035
TO
2040 * any other parameters.
2041 *
cf470720
TO
2042 * @param string $entity
2043 * Entity name.
2044 * @param array $params
2045 * Params from civicrm_api, including:.
6a488035 2046 * - 'values': an array of records to save
9d32e6f7
EM
2047 * - all other items: keys which identify new/pre-existing records.
2048 *
26728d3f 2049 * @return array|int
6a488035
TO
2050 */
2051function _civicrm_api3_generic_replace($entity, $params) {
2052
6a488035
TO
2053 $transaction = new CRM_Core_Transaction();
2054 try {
2055 if (!is_array($params['values'])) {
2056 throw new Exception("Mandatory key(s) missing from params array: values");
2057 }
2058
2059 // Extract the keys -- somewhat scary, don't think too hard about it
e4b4e33a 2060 $baseParams = _civicrm_api3_generic_replace_base_params($params);
6a488035
TO
2061
2062 // Lookup pre-existing records
2063 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
2064 if (civicrm_error($preexisting)) {
2065 $transaction->rollback();
2066 return $preexisting;
2067 }
2068
2069 // Save the new/updated records
2070 $creates = array();
2071 foreach ($params['values'] as $replacement) {
2072 // Sugar: Don't force clients to duplicate the 'key' data
2073 $replacement = array_merge($baseParams, $replacement);
2074 $action = (isset($replacement['id']) || isset($replacement[$entity . '_id'])) ? 'update' : 'create';
2075 $create = civicrm_api($entity, $action, $replacement);
2076 if (civicrm_error($create)) {
2077 $transaction->rollback();
2078 return $create;
2079 }
2080 foreach ($create['values'] as $entity_id => $entity_value) {
2081 $creates[$entity_id] = $entity_value;
2082 }
2083 }
2084
2085 // Remove stale records
2086 $staleIDs = array_diff(
2087 array_keys($preexisting['values']),
2088 array_keys($creates)
2089 );
2090 foreach ($staleIDs as $staleID) {
2091 $delete = civicrm_api($entity, 'delete', array(
2092 'version' => $params['version'],
2093 'id' => $staleID,
2094 ));
2095 if (civicrm_error($delete)) {
2096 $transaction->rollback();
2097 return $delete;
2098 }
2099 }
2100
2101 return civicrm_api3_create_success($creates, $params);
2102 }
2103 catch(PEAR_Exception $e) {
2104 $transaction->rollback();
2105 return civicrm_api3_create_error($e->getMessage());
2106 }
2107 catch(Exception $e) {
2108 $transaction->rollback();
2109 return civicrm_api3_create_error($e->getMessage());
2110 }
2111}
2112
26728d3f 2113/**
9d32e6f7
EM
2114 * Replace base parameters.
2115 *
c490a46a 2116 * @param array $params
26728d3f 2117 *
9d32e6f7 2118 * @return array
26728d3f 2119 */
e4b4e33a
TO
2120function _civicrm_api3_generic_replace_base_params($params) {
2121 $baseParams = $params;
2122 unset($baseParams['values']);
2123 unset($baseParams['sequential']);
2124 unset($baseParams['options']);
2125 return $baseParams;
2126}
2127
11e09c59 2128/**
9d32e6f7 2129 * Returns fields allowable by api.
26728d3f 2130 *
cf470720
TO
2131 * @param $entity
2132 * String Entity to query.
2133 * @param bool $unique
2134 * Index by unique fields?.
26728d3f
E
2135 * @param array $params
2136 *
2137 * @return array
6a488035 2138 */
27b9f49a 2139function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
9d32e6f7
EM
2140 $unsetIfEmpty = array(
2141 'dataPattern',
2142 'headerPattern',
2143 'default',
2144 'export',
2145 'import',
2146 );
6a488035
TO
2147 $dao = _civicrm_api3_get_DAO($entity);
2148 if (empty($dao)) {
2149 return array();
2150 }
6a488035
TO
2151 $d = new $dao();
2152 $fields = $d->fields();
95457d69
CW
2153
2154 // Set html attributes for text fields
2155 foreach ($fields as $name => &$field) {
2156 if (isset($field['html'])) {
2157 $field['html'] += (array) $d::makeAttribute($field);
2158 }
2159 }
2160
6a488035
TO
2161 // replace uniqueNames by the normal names as the key
2162 if (empty($unique)) {
fc6a6a51 2163 foreach ($fields as $name => &$field) {
6a488035
TO
2164 //getting rid of unused attributes
2165 foreach ($unsetIfEmpty as $attr) {
2166 if (empty($field[$attr])) {
2167 unset($field[$attr]);
2168 }
2169 }
2170 if ($name == $field['name']) {
2171 continue;
2172 }
2173 if (array_key_exists($field['name'], $fields)) {
2174 $field['error'] = 'name conflict';
2175 // it should never happen, but better safe than sorry
2176 continue;
2177 }
2178 $fields[$field['name']] = $field;
2179 $fields[$field['name']]['uniqueName'] = $name;
2180 unset($fields[$name]);
2181 }
2182 }
fc6a6a51
CW
2183 // Translate FKClassName to the corresponding api
2184 foreach ($fields as $name => &$field) {
2185 if (!empty($field['FKClassName'])) {
2186 $FKApi = CRM_Core_DAO_AllCoreTables::getBriefName($field['FKClassName']);
2187 if ($FKApi) {
2188 $field['FKApiName'] = $FKApi;
2189 }
2190 }
2191 }
6a488035
TO
2192 $fields += _civicrm_api_get_custom_fields($entity, $params);
2193 return $fields;
2194}
2195
11e09c59 2196/**
9d32e6f7
EM
2197 * Return an array of fields for a given entity.
2198 *
2199 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
2200 *
645ee340 2201 * @param $entity
d0997921 2202 * @param array $params
9d32e6f7 2203 *
645ee340 2204 * @return array
6a488035
TO
2205 */
2206function _civicrm_api_get_custom_fields($entity, &$params) {
6a488035 2207 $entity = _civicrm_api_get_camel_name($entity);
18ec726b
CW
2208 if ($entity == 'Contact') {
2209 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
0400dfac 2210 $entity = CRM_Utils_Array::value('contact_type', $params);
6a488035 2211 }
6a488035
TO
2212 $customfields = CRM_Core_BAO_CustomField::getFields($entity,
2213 FALSE,
2214 FALSE,
18ec726b 2215 // we could / should probably test for other subtypes here - e.g. activity_type_id
39cb3d7b 2216 CRM_Utils_Array::value('contact_sub_type', $params),
6a488035 2217 NULL,
18ec726b 2218 FALSE,
6a488035
TO
2219 FALSE,
2220 FALSE
2221 );
ddaac11c
CW
2222
2223 $ret = array();
6a488035
TO
2224
2225 foreach ($customfields as $key => $value) {
a4c5e9a3
CW
2226 // Regular fields have a 'name' property
2227 $value['name'] = 'custom_' . $key;
3a8e9315 2228 $value['title'] = $value['label'];
2930d67a 2229 $value['type'] = _getStandardTypeFromCustomDataType($value);
ddaac11c 2230 $ret['custom_' . $key] = $value;
6a488035 2231 }
ddaac11c 2232 return $ret;
6a488035 2233}
645ee340 2234
effb666a 2235/**
9d32e6f7
EM
2236 * Translate the custom field data_type attribute into a std 'type'.
2237 *
67f947ac 2238 * @param array $value
9d32e6f7 2239 *
971d41b1 2240 * @return int
effb666a 2241 */
2930d67a 2242function _getStandardTypeFromCustomDataType($value) {
2243 $dataType = $value['data_type'];
2244 //CRM-15792 - If date custom field contains timeformat change type to DateTime
2245 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
d2c56cb4
MM
2246 $dataType = 'DateTime';
2247 }
effb666a 2248 $mapping = array(
2249 'String' => CRM_Utils_Type::T_STRING,
2250 'Int' => CRM_Utils_Type::T_INT,
2251 'Money' => CRM_Utils_Type::T_MONEY,
2252 'Memo' => CRM_Utils_Type::T_LONGTEXT,
2253 'Float' => CRM_Utils_Type::T_FLOAT,
2254 'Date' => CRM_Utils_Type::T_DATE,
d2c56cb4 2255 'DateTime' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
effb666a 2256 'Boolean' => CRM_Utils_Type::T_BOOLEAN,
2257 'StateProvince' => CRM_Utils_Type::T_INT,
2258 'File' => CRM_Utils_Type::T_STRING,
2259 'Link' => CRM_Utils_Type::T_STRING,
2260 'ContactReference' => CRM_Utils_Type::T_INT,
3e93ae67 2261 'Country' => CRM_Utils_Type::T_INT,
effb666a 2262 );
2263 return $mapping[$dataType];
2264}
6a488035 2265
6a488035 2266
11e09c59 2267/**
9d32e6f7
EM
2268 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
2269 *
6a488035
TO
2270 * If multiple aliases the last takes precedence
2271 *
2272 * Function also swaps unique fields for non-unique fields & vice versa.
9d32e6f7 2273 *
645ee340
EM
2274 * @param $apiRequest
2275 * @param $fields
6a488035 2276 */
94359f7e 2277function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2278 foreach ($fields as $field => $values) {
6a488035 2279 $uniqueName = CRM_Utils_Array::value('uniqueName', $values);
a7488080 2280 if (!empty($values['api.aliases'])) {
6a488035
TO
2281 // if aliased field is not set we try to use field alias
2282 if (!isset($apiRequest['params'][$field])) {
2283 foreach ($values['api.aliases'] as $alias) {
2284 if (isset($apiRequest['params'][$alias])) {
2285 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2286 }
2287 //unset original field nb - need to be careful with this as it may bring inconsistencies
2288 // out of the woodwork but will be implementing only as _spec function extended
2289 unset($apiRequest['params'][$alias]);
2290 }
2291 }
2292 }
8cc574cf 2293 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
6a488035
TO
2294 && isset($apiRequest['params'][$values['name']])
2295 ) {
2296 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2297 // note that it would make sense to unset the original field here but tests need to be in place first
79b61cd0 2298 if ($field != 'domain_version') {
2299 unset($apiRequest['params'][$values['name']]);
2300 }
6a488035
TO
2301 }
2302 if (!isset($apiRequest['params'][$field])
2303 && $uniqueName
2304 && $field != $uniqueName
2305 && array_key_exists($uniqueName, $apiRequest['params'])
971d41b1 2306 ) {
6a488035
TO
2307 $apiRequest['params'][$field] = CRM_Utils_Array::value($values['uniqueName'], $apiRequest['params']);
2308 // note that it would make sense to unset the original field here but tests need to be in place first
2309 }
2310 }
2311
2312}
11e09c59
TO
2313
2314/**
6a488035 2315 * Validate integer fields being passed into API.
9d32e6f7
EM
2316 *
2317 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
6a488035 2318 *
cf470720
TO
2319 * @param array $params
2320 * Params from civicrm_api.
2321 * @param string $fieldName
2322 * Uniquename of field being checked.
2323 * @param array $fieldInfo
2324 * Array of fields from getfields function.
5e436708 2325 * @param string $entity
9d32e6f7 2326 *
916b48b6 2327 * @throws API_Exception
6a488035 2328 */
70f7ba9e 2329function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
afa0b07c 2330 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2331 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
2332 return;
2333 }
2334
3c151c70 2335 if (!empty($fieldValue)) {
46b6363c 2336 // if value = 'user_contact_id' (or similar), replace value with contact id
3c151c70 2337 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2338 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
17cb9f7f 2339 if ('unknown-user' === $realContactId) {
971d41b1
CW
2340 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
2341 }
2342 elseif (is_numeric($realContactId)) {
2fa797b9 2343 $fieldValue = $realContactId;
46b6363c 2344 }
6a488035 2345 }
6fa8a394 2346 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) {
3c151c70 2347 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
6a488035
TO
2348 }
2349
283f988c 2350 // After swapping options, ensure we have an integer(s)
3c151c70 2351 foreach ((array) ($fieldValue) as $value) {
736f9c2d 2352 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
283f988c
CW
2353 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
2354 }
6fa8a394
CW
2355 }
2356
2357 // Check our field length
971d41b1 2358 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
48a89be3 2359 ) {
79d7553f 2360 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
971d41b1 2361 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
6a488035
TO
2362 );
2363 }
2364 }
2fa797b9 2365
2366 if (!empty($op)) {
2367 $params[$fieldName][$op] = $fieldValue;
2368 }
2369 else {
2370 $params[$fieldName] = $fieldValue;
2371 }
6a488035
TO
2372}
2373
46b6363c 2374/**
9d32e6f7 2375 * Determine a contact ID using a string expression.
46b6363c 2376 *
cf470720
TO
2377 * @param string $contactIdExpr
2378 * E.g. "user_contact_id" or "@user:username".
9d32e6f7 2379 *
17cb9f7f 2380 * @return int|NULL|'unknown-user'
46b6363c 2381 */
37fa58b0 2382function _civicrm_api3_resolve_contactID($contactIdExpr) {
9d32e6f7 2383 // If value = 'user_contact_id' replace value with logged in user id.
46b6363c 2384 if ($contactIdExpr == "user_contact_id") {
bb341097
EM
2385 return CRM_Core_Session::getLoggedInContactID();
2386 }
2387 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
46b6363c
TO
2388 $config = CRM_Core_Config::singleton();
2389
2390 $ufID = $config->userSystem->getUfId($matches[1]);
2391 if (!$ufID) {
17cb9f7f 2392 return 'unknown-user';
46b6363c
TO
2393 }
2394
2395 $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID);
17cb9f7f
TO
2396 if (!$contactID) {
2397 return 'unknown-user';
46b6363c
TO
2398 }
2399
2400 return $contactID;
2401 }
31fd7b1e 2402 return NULL;
46b6363c
TO
2403}
2404
26728d3f 2405/**
9d32e6f7
EM
2406 * Validate html (check for scripting attack).
2407 *
5e436708
EM
2408 * @param array $params
2409 * @param string $fieldName
2410 * @param array $fieldInfo
26728d3f
E
2411 *
2412 * @throws API_Exception
2413 */
5e436708 2414function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
afa0b07c 2415 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2416 if (strpos($op, 'NULL') || strpos($op, 'EMPTY')) {
2417 return;
2418 }
3c151c70 2419 if ($fieldValue) {
2420 if (!CRM_Utils_Rule::xssString($fieldValue)) {
4232a0a5 2421 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
6a488035
TO
2422 }
2423 }
2424}
2425
11e09c59 2426/**
6a488035 2427 * Validate string fields being passed into API.
9d32e6f7 2428 *
cf470720
TO
2429 * @param array $params
2430 * Params from civicrm_api.
2431 * @param string $fieldName
2432 * Uniquename of field being checked.
2433 * @param array $fieldInfo
2434 * Array of fields from getfields function.
5e436708 2435 * @param string $entity
9d32e6f7 2436 *
916b48b6
VU
2437 * @throws API_Exception
2438 * @throws Exception
6a488035 2439 */
70f7ba9e 2440function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
cbfe5232 2441 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
02ea3d64 2442 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System::isNull($fieldValue)) {
afa0b07c 2443 return;
2444 }
02ea3d64 2445
48a89be3 2446 if (!is_array($fieldValue)) {
3c151c70 2447 $fieldValue = (string) $fieldValue;
69c1fac4 2448 }
92e4c2a5 2449 else {
69c1fac4 2450 //@todo what do we do about passed in arrays. For many of these fields
2451 // the missing piece of functionality is separating them to a separated string
2452 // & many save incorrectly. But can we change them wholesale?
2453 }
3c151c70 2454 if ($fieldValue) {
02ea3d64 2455 foreach ((array) $fieldValue as $value) {
2456 if (!CRM_Utils_Rule::xssString($fieldValue)) {
4232a0a5 2457 throw new Exception('Input contains illegal SCRIPT tag.');
02ea3d64 2458 }
2459 if ($fieldName == 'currency') {
2460 //When using IN operator $fieldValue is a array of currency codes
2461 if (!CRM_Utils_Rule::currencyCode($value)) {
7d543448 2462 throw new Exception("Currency not a valid code: $currency");
3c151c70 2463 }
6a488035
TO
2464 }
2465 }
6a488035 2466 }
7d543448 2467 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) {
2468 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo);
2469 }
2470 // Check our field length
2471 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2472 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2473 2100, array('field' => $fieldName)
2474 );
2475 }
2fa797b9 2476
2477 if (!empty($op)) {
2478 $params[$fieldName][$op] = $fieldValue;
2479 }
2480 else {
2481 $params[$fieldName] = $fieldValue;
6a488035
TO
2482 }
2483}
70f7ba9e
CW
2484
2485/**
9d32e6f7 2486 * Validate & swap out any pseudoconstants / options.
70f7ba9e 2487 *
645ee340
EM
2488 * @param mixed $fieldValue
2489 * @param string $entity : api entity name
2490 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2491 * @param array $fieldInfo : getfields meta-data
9d32e6f7 2492 *
645ee340 2493 * @throws \API_Exception
70f7ba9e 2494 */
3c151c70 2495function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo) {
6fa8a394 2496 $options = CRM_Utils_Array::value('options', $fieldInfo);
08fe8c7e 2497
6fa8a394 2498 if (!$options) {
22e263ad 2499 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
9d32e6f7 2500 // We need to get the options from the entity the field relates to.
94359f7e 2501 $entity = $fieldInfo['entity'];
2502 }
9d32e6f7
EM
2503 $options = civicrm_api($entity, 'getoptions', array(
2504 'version' => 3,
2505 'field' => $fieldInfo['name'],
2506 'context' => 'validate',
2507 ));
6fa8a394
CW
2508 $options = CRM_Utils_Array::value('values', $options, array());
2509 }
70f7ba9e 2510
9d32e6f7 2511 // If passed a value-separated string, explode to an array, then re-implode after matching values.
70f7ba9e 2512 $implode = FALSE;
3c151c70 2513 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
2514 $fieldValue = CRM_Utils_Array::explodePadded($fieldValue);
70f7ba9e
CW
2515 $implode = TRUE;
2516 }
9d32e6f7 2517 // If passed multiple options, validate each.
3c151c70 2518 if (is_array($fieldValue)) {
2519 foreach ($fieldValue as &$value) {
736f9c2d
CW
2520 if (!is_array($value)) {
2521 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2522 }
70f7ba9e
CW
2523 }
2524 // TODO: unwrap the call to implodePadded from the conditional and do it always
2525 // need to verify that this is safe and doesn't break anything though.
2526 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2527 if ($implode) {
3c151c70 2528 CRM_Utils_Array::implodePadded($fieldValue);
70f7ba9e
CW
2529 }
2530 }
2531 else {
3c151c70 2532 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
70f7ba9e
CW
2533 }
2534}
2535
2536/**
9d32e6f7 2537 * Validate & swap a single option value for a field.
70f7ba9e 2538 *
971d41b1
CW
2539 * @param string $value field value
2540 * @param array $options array of options for this field
2541 * @param string $fieldName field name used in api call (not necessarily the canonical name)
9d32e6f7 2542 *
916b48b6 2543 * @throws API_Exception
70f7ba9e
CW
2544 */
2545function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2546 // If option is a key, no need to translate
08fe8c7e 2547 // or if no options are avaiable for pseudoconstant 'table' property
2548 if (array_key_exists($value, $options) || !$options) {
70f7ba9e
CW
2549 return;
2550 }
70f7ba9e 2551
a4c5e9a3
CW
2552 // Translate value into key
2553 $newValue = array_search($value, $options);
2554 if ($newValue !== FALSE) {
2555 $value = $newValue;
2556 return;
2557 }
70f7ba9e 2558 // Case-insensitive matching
80085473 2559 $newValue = strtolower($value);
70f7ba9e 2560 $options = array_map("strtolower", $options);
80085473
CW
2561 $newValue = array_search($newValue, $options);
2562 if ($newValue === FALSE) {
2563 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
70f7ba9e 2564 }
80085473 2565 $value = $newValue;
70f7ba9e
CW
2566}
2567
2568/**
9d32e6f7 2569 * Returns the canonical name of a field.
70f7ba9e 2570 *
cf470720 2571 * @param $entity
16b10e64 2572 * api entity name (string should already be standardized - no camelCase).
cf470720 2573 * @param $fieldName
16b10e64 2574 * any variation of a field's name (name, unique_name, api.alias).
77b97be7 2575 *
2b28667f 2576 * @param string $action
2577 *
72b3a70c 2578 * @return bool|string
2b28667f 2579 * FieldName or FALSE if the field does not exist
70f7ba9e 2580 */
985f4890 2581function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
26a700db
CW
2582 if (!$fieldName) {
2583 return FALSE;
2584 }
a38a89fc 2585 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
a4c5e9a3
CW
2586 return $fieldName;
2587 }
e65c2445 2588 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
a4c5e9a3
CW
2589 return 'id';
2590 }
70f7ba9e
CW
2591 $result = civicrm_api($entity, 'getfields', array(
2592 'version' => 3,
985f4890 2593 'action' => $action,
70f7ba9e
CW
2594 ));
2595 $meta = $result['values'];
e354351f 2596 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2597 $fieldName = $fieldName . '_id';
2598 }
70f7ba9e
CW
2599 if (isset($meta[$fieldName])) {
2600 return $meta[$fieldName]['name'];
2601 }
70f7ba9e
CW
2602 foreach ($meta as $info) {
2603 if ($fieldName == CRM_Utils_Array::value('uniqueName', $info)) {
2604 return $info['name'];
2605 }
2606 if (array_search($fieldName, CRM_Utils_Array::value('api.aliases', $info, array())) !== FALSE) {
2607 return $info['name'];
2608 }
2609 }
985f4890
CW
2610 // Create didn't work, try with get
2611 if ($action == 'create') {
2612 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2613 }
70f7ba9e
CW
2614 return FALSE;
2615}
a14e9d08
CW
2616
2617/**
9d32e6f7
EM
2618 * Check if the function is deprecated.
2619 *
a14e9d08
CW
2620 * @param string $entity
2621 * @param array $result
9d32e6f7 2622 *
15cbe793 2623 * @return string|array|null
a14e9d08
CW
2624 */
2625function _civicrm_api3_deprecation_check($entity, $result = array()) {
15cbe793 2626 if ($entity) {
4846df91 2627 $apiFile = "api/v3/$entity.php";
15cbe793
CW
2628 if (CRM_Utils_File::isIncludable($apiFile)) {
2629 require_once $apiFile;
2630 }
4846df91
CW
2631 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2632 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
15cbe793
CW
2633 if (function_exists($fnName)) {
2634 return $fnName($result);
2635 }
a14e9d08
CW
2636 }
2637}
afa0b07c 2638
2639/**
9d32e6f7
EM
2640 * Get the actual field value.
2641 *
afa0b07c 2642 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
cbfe5232 2643 * So this function returns the actual field value.
afa0b07c 2644 *
2645 * @param array $params
2646 * @param string $fieldName
cbfe5232 2647 * @param string $type
9d32e6f7 2648 *
971d41b1 2649 * @return mixed
afa0b07c 2650 */
cbfe5232 2651function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
afa0b07c 2652 $fieldValue = CRM_Utils_Array::value($fieldName, $params);
2653 $op = NULL;
2654
cbfe5232 2655 if (!empty($fieldValue) && is_array($fieldValue) &&
2656 (array_search(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators()) ||
2657 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2658 ) {
afa0b07c 2659 $op = key($fieldValue);
2660 $fieldValue = CRM_Utils_Array::value($op, $fieldValue);
2661 }
2662 return array($fieldValue, $op);
2663}
5bc7c754
TO
2664
2665/**
a066deea
TO
2666 * A generic "get" API based on simple array data. This is comparable to
2667 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2668 * small/mid-size data loaded from external JSON or XML documents.
5bc7c754 2669 *
2b28667f 2670 * @param $entity
5bc7c754
TO
2671 * @param array $params
2672 * API parameters.
2673 * @param array $records
2674 * List of all records.
2675 * @param string $idCol
2676 * The property which defines the ID of a record
2677 * @param array $fields
2678 * List of filterable fields.
2b28667f 2679 *
5bc7c754 2680 * @return array
2b28667f 2681 * @throws \API_Exception
5bc7c754
TO
2682 */
2683function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) {
2684 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2685 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2686 $offset = CRM_Utils_Array::value('offset', $options);
2687 $limit = CRM_Utils_Array::value('limit', $options);
2688
2689 $matches = array();
2690
2691 $currentOffset = 0;
2692 foreach ($records as $record) {
2693 if ($idCol != 'id') {
2694 $record['id'] = $record[$idCol];
2695 }
2696 $match = TRUE;
2697 foreach ($params as $k => $v) {
a066deea
TO
2698 if ($k == 'id') {
2699 $k = $idCol;
2700 }
66ea2662 2701 if (in_array($k, $fields) && $record[$k] != $v) {
5bc7c754
TO
2702 $match = FALSE;
2703 break;
2704 }
2705 }
2706 if ($match) {
2707 if ($currentOffset >= $offset) {
2708 $matches[$record[$idCol]] = $record;
2709 }
2710 if ($limit && count($matches) >= $limit) {
2711 break;
2712 }
2713 $currentOffset++;
2714 }
2715 }
2716
2717 $return = CRM_Utils_Array::value('return', $options, array());
2718 if (!empty($return)) {
2719 $return['id'] = 1;
2720 $matches = CRM_Utils_Array::filterColumns($matches, array_keys($return));
2721 }
2722
2723 return civicrm_api3_create_success($matches, $params);
2724}