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