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