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