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