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