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