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