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