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