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