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