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