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