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