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