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