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