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