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