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