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