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