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