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