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