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