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