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