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