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