Merge pull request #9575 from jitendrapurohit/CRM-19761
[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 }
817
818 $options = array(
819 'offset' => CRM_Utils_Rule::integer($offset) ? $offset : NULL,
820 'limit' => CRM_Utils_Rule::integer($limit) ? $limit : NULL,
821 'is_count' => $is_count,
822 'return' => !empty($returnProperties) ? $returnProperties : array(),
823 );
824
825 $finalSort = array();
826 $options['sort'] = NULL;
827 if (!empty($sort)) {
828 foreach ((array) $sort as $s) {
829 if (CRM_Utils_Rule::mysqlOrderBy($s)) {
830 if ($entity && $action == 'get') {
831 switch (trim(strtolower($s))) {
832 case 'id':
833 case 'id desc':
834 case 'id asc':
835 $s = str_replace('id', $lowercase_entity . '_id', $s);
836 }
837 }
838 $finalSort[] = $s;
839 }
840 else {
841 throw new API_Exception("Unknown field specified for sort. Cannot order by '$s'");
842 }
843 }
844 $options['sort'] = implode(', ', $finalSort);
845 }
846
847 if ($options['sort'] && stristr($options['sort'], 'SELECT')) {
848 throw new API_Exception('invalid string in sort options');
849 }
850
851 if (!$queryObject) {
852 return $options;
853 }
854 //here comes the legacy support for $returnProperties, $inputParams e.g for contat_get
855 // if the query object is being used this should be used
856 $inputParams = array();
857 $legacyreturnProperties = array();
858 $otherVars = array(
859 'sort', 'offset', 'rowCount', 'options', 'return',
860 'version', 'prettyprint', 'check_permissions', 'sequential',
861 );
862 foreach ($params as $n => $v) {
863 if (substr($n, 0, 7) == 'return.') {
864 $legacyreturnProperties[substr($n, 7)] = $v;
865 }
866 elseif ($n == 'id') {
867 $inputParams[$lowercase_entity . '_id'] = $v;
868 }
869 elseif (in_array($n, $otherVars)) {
870 }
871 else {
872 $inputParams[$n] = $v;
873 if ($v && !is_array($v) && stristr($v, 'SELECT')) {
874 throw new API_Exception('invalid string');
875 }
876 }
877 }
878 $options['return'] = array_merge($returnProperties, $legacyreturnProperties);
879 $options['input_params'] = $inputParams;
880 return $options;
881 }
882
883 /**
884 * Apply options (e.g. sort, limit, order by) to DAO object (prior to find).
885 *
886 * @param array $params
887 * Params array as passed into civicrm_api.
888 * @param object $dao
889 * DAO object.
890 * @param $entity
891 */
892 function _civicrm_api3_apply_options_to_dao(&$params, &$dao, $entity) {
893
894 $options = _civicrm_api3_get_options_from_params($params, FALSE, $entity);
895 if (!$options['is_count']) {
896 if (!empty($options['limit'])) {
897 $dao->limit((int) $options['offset'], (int) $options['limit']);
898 }
899 if (!empty($options['sort'])) {
900 $options['sort'] = CRM_Utils_Type::escape($options['sort'], 'MysqlOrderBy');
901 $dao->orderBy($options['sort']);
902 }
903 }
904 }
905
906 /**
907 * Build fields array.
908 *
909 * This is the array of fields as it relates to the given DAO
910 * returns unique fields as keys by default but if set but can return by DB fields
911 *
912 * @param CRM_Core_DAO $bao
913 * @param bool $unique
914 *
915 * @return array
916 */
917 function _civicrm_api3_build_fields_array(&$bao, $unique = TRUE) {
918 $fields = $bao->fields();
919 if ($unique) {
920 if (empty($fields['id'])) {
921 $lowercase_entity = _civicrm_api_get_entity_name_from_camel(_civicrm_api_get_entity_name_from_dao($bao));
922 $fields['id'] = $fields[$lowercase_entity . '_id'];
923 unset($fields[$lowercase_entity . '_id']);
924 }
925 return $fields;
926 }
927
928 foreach ($fields as $field) {
929 $dbFields[$field['name']] = $field;
930 }
931 return $dbFields;
932 }
933
934 /**
935 * Build fields array.
936 *
937 * This is the array of fields as it relates to the given DAO
938 * returns unique fields as keys by default but if set but can return by DB fields
939 *
940 * @param CRM_Core_DAO $bao
941 *
942 * @return array
943 */
944 function _civicrm_api3_get_unique_name_array(&$bao) {
945 $fields = $bao->fields();
946 foreach ($fields as $field => $values) {
947 $uniqueFields[$field] = CRM_Utils_Array::value('name', $values, $field);
948 }
949 return $uniqueFields;
950 }
951
952 /**
953 * Converts an DAO object to an array.
954 *
955 * @deprecated - DAO based retrieval is being phased out.
956 *
957 * @param CRM_Core_DAO $dao
958 * Object to convert.
959 * @param array $params
960 * @param bool $uniqueFields
961 * @param string $entity
962 * @param bool $autoFind
963 *
964 * @return array
965 */
966 function _civicrm_api3_dao_to_array($dao, $params = NULL, $uniqueFields = TRUE, $entity = "", $autoFind = TRUE) {
967 $result = array();
968 if (isset($params['options']) && !empty($params['options']['is_count'])) {
969 return $dao->count();
970 }
971 if (empty($dao)) {
972 return array();
973 }
974 if ($autoFind && !$dao->find()) {
975 return array();
976 }
977
978 if (isset($dao->count)) {
979 return $dao->count;
980 }
981
982 $fields = array_keys(_civicrm_api3_build_fields_array($dao, FALSE));
983 while ($dao->fetch()) {
984 $tmp = array();
985 foreach ($fields as $key) {
986 if (array_key_exists($key, $dao)) {
987 // not sure on that one
988 if ($dao->$key !== NULL) {
989 $tmp[$key] = $dao->$key;
990 }
991 }
992 }
993 $result[$dao->id] = $tmp;
994
995 if (_civicrm_api3_custom_fields_are_required($entity, $params)) {
996 _civicrm_api3_custom_data_get($result[$dao->id], $params['check_permissions'], $entity, $dao->id);
997 }
998 }
999
1000 return $result;
1001 }
1002
1003 /**
1004 * Determine if custom fields need to be retrieved.
1005 *
1006 * We currently retrieve all custom fields or none at this level so if we know the entity
1007 * && 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
1008 * @todo filter so only required fields are queried
1009 *
1010 * @param string $entity
1011 * Entity name in CamelCase.
1012 * @param array $params
1013 *
1014 * @return bool
1015 */
1016 function _civicrm_api3_custom_fields_are_required($entity, $params) {
1017 if (!array_key_exists($entity, CRM_Core_BAO_CustomQuery::$extendsMap)) {
1018 return FALSE;
1019 }
1020 $options = _civicrm_api3_get_options_from_params($params);
1021 // We check for possibility of 'custom' => 1 as well as specific custom fields.
1022 $returnString = implode('', $options['return']) . implode('', array_keys($options['return']));
1023 if (stristr($returnString, 'custom')) {
1024 return TRUE;
1025 }
1026 }
1027
1028 /**
1029 * Converts an object to an array.
1030 *
1031 * @param object $dao
1032 * (reference) object to convert.
1033 * @param array $values
1034 * (reference) array.
1035 * @param array|bool $uniqueFields
1036 */
1037 function _civicrm_api3_object_to_array(&$dao, &$values, $uniqueFields = FALSE) {
1038
1039 $fields = _civicrm_api3_build_fields_array($dao, $uniqueFields);
1040 foreach ($fields as $key => $value) {
1041 if (array_key_exists($key, $dao)) {
1042 $values[$key] = $dao->$key;
1043 }
1044 }
1045 }
1046
1047 /**
1048 * Wrapper for _civicrm_object_to_array when api supports unique fields.
1049 *
1050 * @param $dao
1051 * @param $values
1052 *
1053 * @return array
1054 */
1055 function _civicrm_api3_object_to_array_unique_fields(&$dao, &$values) {
1056 return _civicrm_api3_object_to_array($dao, $values, TRUE);
1057 }
1058
1059 /**
1060 * Format custom parameters.
1061 *
1062 * @param array $params
1063 * @param array $values
1064 * @param string $extends
1065 * Entity that this custom field extends (e.g. contribution, event, contact).
1066 * @param string $entityId
1067 * ID of entity per $extends.
1068 */
1069 function _civicrm_api3_custom_format_params($params, &$values, $extends, $entityId = NULL) {
1070 $values['custom'] = array();
1071 $checkCheckBoxField = FALSE;
1072 $entity = $extends;
1073 if (in_array($extends, array('Household', 'Individual', 'Organization'))) {
1074 $entity = 'Contact';
1075 }
1076
1077 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'create'));
1078 if (!$fields['is_error']) {
1079 // not sure if fields could be error - maybe change to using civicrm_api3 wrapper later - this is conservative
1080 $fields = $fields['values'];
1081 $checkCheckBoxField = TRUE;
1082 }
1083
1084 foreach ($params as $key => $value) {
1085 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField::getKeyID($key, TRUE);
1086 if ($customFieldID && (!is_null($value))) {
1087 if ($checkCheckBoxField && !empty($fields['custom_' . $customFieldID]) && $fields['custom_' . $customFieldID]['html_type'] == 'CheckBox') {
1088 formatCheckBoxField($value, 'custom_' . $customFieldID, $entity);
1089 }
1090
1091 CRM_Core_BAO_CustomField::formatCustomField($customFieldID, $values['custom'],
1092 $value, $extends, $customValueID, $entityId, FALSE, FALSE, TRUE
1093 );
1094 }
1095 }
1096 }
1097
1098 /**
1099 * Format parameters for create action.
1100 *
1101 * @param array $params
1102 * @param $entity
1103 */
1104 function _civicrm_api3_format_params_for_create(&$params, $entity) {
1105 $nonGenericEntities = array('Contact', 'Individual', 'Household', 'Organization');
1106
1107 $customFieldEntities = array_diff_key(CRM_Core_BAO_CustomQuery::$extendsMap, array_fill_keys($nonGenericEntities, 1));
1108 if (!array_key_exists($entity, $customFieldEntities)) {
1109 return;
1110 }
1111 $values = array();
1112 _civicrm_api3_custom_format_params($params, $values, $entity);
1113 $params = array_merge($params, $values);
1114 }
1115
1116 /**
1117 * We can't rely on downstream to add separators to checkboxes so we'll check here.
1118 *
1119 * We should look at pushing to BAO function
1120 * 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
1121 * note that this is specifically tested in the GRANT api test case so later refactoring should use that as a checking point
1122 *
1123 * 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
1124 * don't touch - lots of very cautious code in here
1125 *
1126 * The resulting array should look like
1127 * array(
1128 * 'key' => 1,
1129 * 'key1' => 1,
1130 * );
1131 *
1132 * OR one or more keys wrapped in a CRM_Core_DAO::VALUE_SEPARATOR - either it accepted by the receiving function
1133 *
1134 * @todo - we are probably skipping handling disabled options as presumably getoptions is not giving us them. This should be non-regressive but might
1135 * be fixed in future
1136 *
1137 * @param mixed $checkboxFieldValue
1138 * @param string $customFieldLabel
1139 * @param string $entity
1140 */
1141 function formatCheckBoxField(&$checkboxFieldValue, $customFieldLabel, $entity) {
1142
1143 if (is_string($checkboxFieldValue) && stristr($checkboxFieldValue, CRM_Core_DAO::VALUE_SEPARATOR)) {
1144 // We can assume it's pre-formatted.
1145 return;
1146 }
1147 $options = civicrm_api($entity, 'getoptions', array('field' => $customFieldLabel, 'version' => 3));
1148 if (!empty($options['is_error'])) {
1149 // The check is precautionary - can probably be removed later.
1150 return;
1151 }
1152
1153 $options = $options['values'];
1154 $validValue = TRUE;
1155 if (is_array($checkboxFieldValue)) {
1156 foreach ($checkboxFieldValue as $key => $value) {
1157 if (!array_key_exists($key, $options)) {
1158 $validValue = FALSE;
1159 }
1160 }
1161 if ($validValue) {
1162 // we have been passed an array that is already in the 'odd' custom field format
1163 return;
1164 }
1165 }
1166
1167 // so we either have an array that is not keyed by the value or we have a string that doesn't hold separators
1168 // if the array only has one item we'll treat it like any other string
1169 if (is_array($checkboxFieldValue) && count($checkboxFieldValue) == 1) {
1170 $possibleValue = reset($checkboxFieldValue);
1171 }
1172 if (is_string($checkboxFieldValue)) {
1173 $possibleValue = $checkboxFieldValue;
1174 }
1175 if (isset($possibleValue) && array_key_exists($possibleValue, $options)) {
1176 $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . $possibleValue . CRM_Core_DAO::VALUE_SEPARATOR;
1177 return;
1178 }
1179 elseif (is_array($checkboxFieldValue)) {
1180 // so this time around we are considering the values in the array
1181 $possibleValues = $checkboxFieldValue;
1182 $formatValue = TRUE;
1183 }
1184 elseif (stristr($checkboxFieldValue, ',')) {
1185 $formatValue = TRUE;
1186 //lets see if we should separate it - we do this near the end so we
1187 // ensure we have already checked that the comma is not part of a legitimate match
1188 // and of course, we don't make any changes if we don't now have matches
1189 $possibleValues = explode(',', $checkboxFieldValue);
1190 }
1191 else {
1192 // run out of ideas as to what the format might be - if it's a string it doesn't match with or without the ','
1193 return;
1194 }
1195
1196 foreach ($possibleValues as $index => $possibleValue) {
1197 if (array_key_exists($possibleValue, $options)) {
1198 // 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)
1199 }
1200 elseif (array_key_exists(trim($possibleValue), $options)) {
1201 $possibleValues[$index] = trim($possibleValue);
1202 }
1203 else {
1204 $formatValue = FALSE;
1205 }
1206 }
1207 if ($formatValue) {
1208 $checkboxFieldValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $possibleValues) . CRM_Core_DAO::VALUE_SEPARATOR;
1209 }
1210 }
1211
1212 /**
1213 * Function to do a 'standard' api get - when the api is only doing a $bao->find then use this.
1214 *
1215 * @param string $bao_name
1216 * Name of BAO.
1217 * @param array $params
1218 * Params from api.
1219 * @param bool $returnAsSuccess
1220 * Return in api success format.
1221 * @param string $entity
1222 * @param CRM_Utils_SQL_Select|NULL $sql
1223 * Extra SQL bits to add to the query. For filtering current events, this might be:
1224 * CRM_Utils_SQL_Select::fragment()->where('(start_date >= CURDATE() || end_date >= CURDATE())');
1225 * @param bool $uniqueFields
1226 * Should unique field names be returned (for backward compatibility)
1227 *
1228 * @return array
1229 */
1230 function _civicrm_api3_basic_get($bao_name, $params, $returnAsSuccess = TRUE, $entity = "", $sql = NULL, $uniqueFields = FALSE) {
1231 $entity = CRM_Core_DAO_AllCoreTables::getBriefName(str_replace('_BAO_', '_DAO_', $bao_name));
1232 $options = _civicrm_api3_get_options_from_params($params);
1233
1234 $query = new \Civi\API\Api3SelectQuery($entity, CRM_Utils_Array::value('check_permissions', $params, FALSE));
1235 $query->where = $params;
1236 if ($options['is_count']) {
1237 $query->select = array('count_rows');
1238 }
1239 else {
1240 $query->select = array_keys(array_filter($options['return']));
1241 $query->orderBy = $options['sort'];
1242 $query->isFillUniqueFields = $uniqueFields;
1243 }
1244 $query->limit = $options['limit'];
1245 $query->offset = $options['offset'];
1246 $query->merge($sql);
1247 $result = $query->run();
1248
1249 if ($returnAsSuccess) {
1250 return civicrm_api3_create_success($result, $params, $entity, 'get');
1251 }
1252 return $result;
1253 }
1254
1255 /**
1256 * Function to do a 'standard' api create - when the api is only doing a $bao::create then use this.
1257 *
1258 * @param string $bao_name
1259 * Name of BAO Class.
1260 * @param array $params
1261 * Parameters passed into the api call.
1262 * @param string $entity
1263 * Entity - pass in if entity is non-standard & required $ids array.
1264 *
1265 * @throws API_Exception
1266 * @throws \Civi\API\Exception\UnauthorizedException
1267 * @return array
1268 */
1269 function _civicrm_api3_basic_create($bao_name, &$params, $entity = NULL) {
1270 _civicrm_api3_check_edit_permissions($bao_name, $params);
1271 _civicrm_api3_format_params_for_create($params, $entity);
1272 $args = array(&$params);
1273 if ($entity) {
1274 $ids = array($entity => CRM_Utils_Array::value('id', $params));
1275 $args[] = &$ids;
1276 }
1277
1278 if (method_exists($bao_name, 'create')) {
1279 $fct = 'create';
1280 $fct_name = $bao_name . '::' . $fct;
1281 $bao = call_user_func_array(array($bao_name, $fct), $args);
1282 }
1283 elseif (method_exists($bao_name, 'add')) {
1284 $fct = 'add';
1285 $fct_name = $bao_name . '::' . $fct;
1286 $bao = call_user_func_array(array($bao_name, $fct), $args);
1287 }
1288 else {
1289 $fct_name = '_civicrm_api3_basic_create_fallback';
1290 $bao = _civicrm_api3_basic_create_fallback($bao_name, $params);
1291 }
1292
1293 if (is_null($bao)) {
1294 return civicrm_api3_create_error('Entity not created (' . $fct_name . ')');
1295 }
1296 elseif (is_a($bao, 'CRM_Core_Error')) {
1297 //some weird circular thing means the error takes itself as an argument
1298 $msg = $bao->getMessages($bao);
1299 // the api deals with entities on a one-by-one basis. However, the contribution bao pushes entities
1300 // onto the error object - presumably because the contribution import is not handling multiple errors correctly
1301 // so we need to reset the error object here to avoid getting concatenated errors
1302 //@todo - the mulitple error handling should be moved out of the contribution object to the import / multiple entity processes
1303 CRM_Core_Error::singleton()->reset();
1304 throw new API_Exception($msg);
1305 }
1306 else {
1307 $values = array();
1308 _civicrm_api3_object_to_array($bao, $values[$bao->id]);
1309 return civicrm_api3_create_success($values, $params, $entity, 'create', $bao);
1310 }
1311 }
1312
1313 /**
1314 * For BAO's which don't have a create() or add() functions, use this fallback implementation.
1315 *
1316 * @fixme There's an intuitive sense that this behavior should be defined somehow in the BAO/DAO class
1317 * structure. In practice, that requires a fair amount of refactoring and/or kludgery.
1318 *
1319 * @param string $bao_name
1320 * @param array $params
1321 *
1322 * @throws API_Exception
1323 *
1324 * @return CRM_Core_DAO|NULL
1325 * An instance of the BAO
1326 */
1327 function _civicrm_api3_basic_create_fallback($bao_name, &$params) {
1328 $dao_name = get_parent_class($bao_name);
1329 if ($dao_name === 'CRM_Core_DAO' || !$dao_name) {
1330 $dao_name = $bao_name;
1331 }
1332 $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($dao_name);
1333 if (empty($entityName)) {
1334 throw new API_Exception("Class \"$bao_name\" does not map to an entity name", "unmapped_class_to_entity", array(
1335 'class_name' => $bao_name,
1336 ));
1337 }
1338 $hook = empty($params['id']) ? 'create' : 'edit';
1339
1340 CRM_Utils_Hook::pre($hook, $entityName, CRM_Utils_Array::value('id', $params), $params);
1341 $instance = new $dao_name();
1342 $instance->copyValues($params);
1343 $instance->save();
1344 CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance);
1345
1346 return $instance;
1347 }
1348
1349 /**
1350 * Function to do a 'standard' api del.
1351 *
1352 * When the api is only doing a $bao::del then use this if api::del doesn't exist it will try DAO delete method.
1353 *
1354 * @param string $bao_name
1355 * @param array $params
1356 *
1357 * @return array
1358 * API result array
1359 * @throws API_Exception
1360 * @throws \Civi\API\Exception\UnauthorizedException
1361 */
1362 function _civicrm_api3_basic_delete($bao_name, &$params) {
1363 civicrm_api3_verify_mandatory($params, NULL, array('id'));
1364 _civicrm_api3_check_edit_permissions($bao_name, array('id' => $params['id']));
1365 $args = array(&$params['id']);
1366 if (method_exists($bao_name, 'del')) {
1367 $dao = new $bao_name();
1368 $dao->id = $params['id'];
1369 if ($dao->find()) {
1370 $bao = call_user_func_array(array($bao_name, 'del'), $args);
1371 if ($bao !== FALSE) {
1372 return civicrm_api3_create_success();
1373 }
1374 throw new API_Exception('Could not delete entity id ' . $params['id']);
1375 }
1376 throw new API_Exception('Could not delete entity id ' . $params['id']);
1377 }
1378 elseif (method_exists($bao_name, 'delete')) {
1379 $dao = new $bao_name();
1380 $dao->id = $params['id'];
1381 if ($dao->find()) {
1382 while ($dao->fetch()) {
1383 $dao->delete();
1384 return civicrm_api3_create_success();
1385 }
1386 }
1387 else {
1388 throw new API_Exception('Could not delete entity id ' . $params['id']);
1389 }
1390 }
1391
1392 throw new API_Exception('no delete method found');
1393 }
1394
1395 /**
1396 * Get custom data for the given entity & Add it to the returnArray.
1397 *
1398 * This looks like 'custom_123' = 'custom string' AND
1399 * 'custom_123_1' = 'custom string'
1400 * Where 123 is field value & 1 is the id within the custom group data table (value ID)
1401 *
1402 * @param array $returnArray
1403 * Array to append custom data too - generally $result[4] where 4 is the entity id.
1404 * @param string $entity
1405 * E.g membership, event.
1406 * @param int $entity_id
1407 * @param int $groupID
1408 * Per CRM_Core_BAO_CustomGroup::getTree.
1409 * @param int $subType
1410 * E.g. membership_type_id where custom data doesn't apply to all membership types.
1411 * @param string $subName
1412 * Subtype of entity.
1413 */
1414 function _civicrm_api3_custom_data_get(&$returnArray, $checkPermission, $entity, $entity_id, $groupID = NULL, $subType = NULL, $subName = NULL) {
1415 $groupTree = CRM_Core_BAO_CustomGroup::getTree($entity,
1416 NULL,
1417 $entity_id,
1418 $groupID,
1419 NULL,
1420 $subName,
1421 TRUE,
1422 NULL,
1423 TRUE,
1424 $checkPermission
1425 );
1426 $groupTree = CRM_Core_BAO_CustomGroup::formatGroupTree($groupTree, 1);
1427 $customValues = array();
1428 CRM_Core_BAO_CustomGroup::setDefaults($groupTree, $customValues);
1429 $fieldInfo = array();
1430 foreach ($groupTree as $set) {
1431 $fieldInfo += $set['fields'];
1432 }
1433 if (!empty($customValues)) {
1434 foreach ($customValues as $key => $val) {
1435 // per standard - return custom_fieldID
1436 $id = CRM_Core_BAO_CustomField::getKeyID($key);
1437 $returnArray['custom_' . $id] = $val;
1438
1439 //not standard - but some api did this so guess we should keep - cheap as chips
1440 $returnArray[$key] = $val;
1441
1442 // Shim to restore legacy behavior of ContactReference custom fields
1443 if (!empty($fieldInfo[$id]) && $fieldInfo[$id]['data_type'] == 'ContactReference') {
1444 $returnArray['custom_' . $id . '_id'] = $returnArray[$key . '_id'] = $val;
1445 $returnArray['custom_' . $id] = $returnArray[$key] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $val, 'sort_name');
1446 }
1447 }
1448 }
1449 }
1450
1451 /**
1452 * Used by the Validate API.
1453 * @param string $entity
1454 * @param string $action
1455 * @param array $params
1456 *
1457 * @return array $errors
1458 */
1459 function _civicrm_api3_validate($entity, $action, $params) {
1460 $errors = array();
1461 $fields = civicrm_api3($entity, 'getfields', array('sequential' => 1, 'api_action' => $action));
1462 $fields = $fields['values'];
1463
1464 // Check for required fields.
1465 foreach ($fields as $values) {
1466 if (!empty($values['api.required']) && empty($params[$values['name']])) {
1467 $errors[$values['name']] = array(
1468 'message' => "Mandatory key(s) missing from params array: " . $values['name'],
1469 'code' => "mandatory_missing",
1470 );
1471 }
1472 }
1473
1474 // Select only the fields which have been input as a param.
1475 $finalfields = array();
1476 foreach ($fields as $values) {
1477 if (array_key_exists($values['name'], $params)) {
1478 $finalfields[] = $values;
1479 }
1480 }
1481
1482 // This derives heavily from the function "_civicrm_api3_validate_fields".
1483 // However, the difference is that try-catch blocks are nested in the loop, making it
1484 // possible for us to get all errors in one go.
1485 foreach ($finalfields as $fieldInfo) {
1486 $fieldName = $fieldInfo['name'];
1487 try {
1488 _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params);
1489 }
1490 catch (Exception $e) {
1491 $errors[$fieldName] = array(
1492 'message' => $e->getMessage(),
1493 'code' => 'incorrect_value',
1494 );
1495 }
1496 }
1497
1498 return array($errors);
1499 }
1500 /**
1501 * Used by the Validate API.
1502 * @param array $fieldInfo
1503 * @param string $entity
1504 * @param array $params
1505 *
1506 * @throws Exception
1507 */
1508 function _civicrm_api3_validate_switch_cases($fieldName, $fieldInfo, $entity, $params) {
1509 switch (CRM_Utils_Array::value('type', $fieldInfo)) {
1510 case CRM_Utils_Type::T_INT:
1511 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1512 break;
1513
1514 case CRM_Utils_Type::T_DATE:
1515 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
1516 case CRM_Utils_Type::T_TIMESTAMP:
1517 //field is of type date or datetime
1518 _civicrm_api3_validate_date($params, $fieldName, $fieldInfo);
1519 break;
1520
1521 case CRM_Utils_Type::T_TEXT:
1522 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1523 break;
1524
1525 case CRM_Utils_Type::T_STRING:
1526 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1527 break;
1528
1529 case CRM_Utils_Type::T_MONEY:
1530 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1531
1532 foreach ((array) $fieldValue as $fieldvalue) {
1533 if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) {
1534 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1535 }
1536 }
1537 break;
1538 }
1539 }
1540
1541 /**
1542 * Validate fields being passed into API.
1543 *
1544 * This function relies on the getFields function working accurately
1545 * for the given API.
1546 *
1547 * As of writing only date was implemented.
1548 *
1549 * @param string $entity
1550 * @param string $action
1551 * @param array $params
1552 * -.
1553 * @param array $fields
1554 * Response from getfields all variables are the same as per civicrm_api.
1555 *
1556 * @throws Exception
1557 */
1558 function _civicrm_api3_validate_fields($entity, $action, &$params, $fields) {
1559 //CRM-15792 handle datetime for custom fields below code handles chain api call
1560 $chainApikeys = array_flip(preg_grep("/^api./", array_keys($params)));
1561 if (!empty($chainApikeys) && is_array($chainApikeys)) {
1562 foreach ($chainApikeys as $key => $value) {
1563 if (is_array($params[$key])) {
1564 $chainApiParams = array_intersect_key($fields, $params[$key]);
1565 $customFields = array_fill_keys(array_keys($params[$key]), $key);
1566 }
1567 }
1568 }
1569 $fields = array_intersect_key($fields, $params);
1570 if (!empty($chainApiParams)) {
1571 $fields = array_merge($fields, $chainApiParams);
1572 }
1573 foreach ($fields as $fieldName => $fieldInfo) {
1574 switch (CRM_Utils_Array::value('type', $fieldInfo)) {
1575 case CRM_Utils_Type::T_INT:
1576 //field is of type integer
1577 _civicrm_api3_validate_integer($params, $fieldName, $fieldInfo, $entity);
1578 break;
1579
1580 case CRM_Utils_Type::T_DATE:
1581 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
1582 case CRM_Utils_Type::T_TIMESTAMP:
1583 //field is of type date or datetime
1584 if (!empty($customFields) && array_key_exists($fieldName, $customFields)) {
1585 $dateParams = &$params[$customFields[$fieldName]];
1586 }
1587 else {
1588 $dateParams = &$params;
1589 }
1590 _civicrm_api3_validate_date($dateParams, $fieldName, $fieldInfo);
1591 break;
1592
1593 case CRM_Utils_Type::T_TEXT:
1594 //blob
1595 _civicrm_api3_validate_html($params, $fieldName, $fieldInfo);
1596 break;
1597
1598 case CRM_Utils_Type::T_STRING:
1599 _civicrm_api3_validate_string($params, $fieldName, $fieldInfo, $entity);
1600 break;
1601
1602 case CRM_Utils_Type::T_MONEY:
1603 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1604 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1605 break;
1606 }
1607 foreach ((array) $fieldValue as $fieldvalue) {
1608 if (!CRM_Utils_Rule::money($fieldvalue) && !empty($fieldvalue)) {
1609 throw new Exception($fieldName . " is not a valid amount: " . $params[$fieldName]);
1610 }
1611 }
1612 break;
1613 }
1614 }
1615 }
1616
1617 /**
1618 * Validate foreign key values of fields being passed into API.
1619 *
1620 * This function relies on the getFields function working accurately
1621 * for the given API.
1622 *
1623 * @param string $entity
1624 * @param string $action
1625 * @param array $params
1626 *
1627 * @param array $fields
1628 * Response from getfields all variables are the same as per civicrm_api.
1629 *
1630 * @throws Exception
1631 */
1632 function _civicrm_api3_validate_foreign_keys($entity, $action, &$params, $fields) {
1633 // intensive checks - usually only called after DB level fail
1634 foreach ($fields as $fieldName => $fieldInfo) {
1635 if (!empty($fieldInfo['FKClassName'])) {
1636 if (!empty($params[$fieldName])) {
1637 _civicrm_api3_validate_constraint($params[$fieldName], $fieldName, $fieldInfo);
1638 }
1639 elseif (!empty($fieldInfo['required'])) {
1640 throw new Exception("DB Constraint Violation - $fieldName should possibly be marked as mandatory for $entity,$action API. If so, please raise a bug report.");
1641 }
1642 }
1643 if (!empty($fieldInfo['api.unique'])) {
1644 $params['entity'] = $entity;
1645 _civicrm_api3_validate_unique_key($params, $fieldName);
1646 }
1647 }
1648 }
1649
1650 /**
1651 * Validate date fields being passed into API.
1652 *
1653 * It currently converts both unique fields and DB field names to a mysql date.
1654 * @todo - probably the unique field handling & the if exists handling is now done before this
1655 * function is reached in the wrapper - can reduce this code down to assume we
1656 * are only checking the passed in field
1657 *
1658 * It also checks against the RULE:date function. This is a centralisation of code that was scattered and
1659 * may not be the best thing to do. There is no code level documentation on the existing functions to work off
1660 *
1661 * @param array $params
1662 * Params from civicrm_api.
1663 * @param string $fieldName
1664 * Uniquename of field being checked.
1665 * @param array $fieldInfo
1666 * Array of fields from getfields function.
1667 *
1668 * @throws Exception
1669 */
1670 function _civicrm_api3_validate_date(&$params, &$fieldName, &$fieldInfo) {
1671 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1672 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1673 return;
1674 }
1675 //should we check first to prevent it from being copied if they have passed in sql friendly format?
1676 if (!empty($params[$fieldInfo['name']])) {
1677 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldInfo['name'], $fieldInfo['type']);
1678 }
1679 if ((CRM_Utils_Array::value('name', $fieldInfo) != $fieldName) && !empty($fieldValue)) {
1680 $fieldValue = _civicrm_api3_getValidDate($fieldValue, $fieldName, $fieldInfo['type']);
1681 }
1682
1683 if (!empty($op)) {
1684 $params[$fieldName][$op] = $fieldValue;
1685 }
1686 else {
1687 $params[$fieldName] = $fieldValue;
1688 }
1689 }
1690
1691 /**
1692 * Convert date into BAO friendly date.
1693 *
1694 * We accept 'whatever strtotime accepts'
1695 *
1696 * @param string $dateValue
1697 * @param string $fieldName
1698 * @param $fieldType
1699 *
1700 * @throws Exception
1701 * @return mixed
1702 */
1703 function _civicrm_api3_getValidDate($dateValue, $fieldName, $fieldType) {
1704 if (is_array($dateValue)) {
1705 foreach ($dateValue as $key => $value) {
1706 $dateValue[$key] = _civicrm_api3_getValidDate($value, $fieldName, $fieldType);
1707 }
1708 return $dateValue;
1709 }
1710 if (strtotime($dateValue) === FALSE) {
1711 throw new Exception($fieldName . " is not a valid date: " . $dateValue);
1712 }
1713 $format = ($fieldType == CRM_Utils_Type::T_DATE) ? 'Ymd000000' : 'YmdHis';
1714 return CRM_Utils_Date::processDate($dateValue, NULL, FALSE, $format);
1715 }
1716
1717 /**
1718 * Validate foreign constraint fields being passed into API.
1719 *
1720 * @param mixed $fieldValue
1721 * @param string $fieldName
1722 * Uniquename of field being checked.
1723 * @param array $fieldInfo
1724 * Array of fields from getfields function.
1725 *
1726 * @throws \API_Exception
1727 */
1728 function _civicrm_api3_validate_constraint(&$fieldValue, &$fieldName, &$fieldInfo) {
1729 $daoName = $fieldInfo['FKClassName'];
1730 $dao = new $daoName();
1731 $dao->id = $fieldValue;
1732 $dao->selectAdd();
1733 $dao->selectAdd('id');
1734 if (!$dao->find()) {
1735 throw new API_Exception("$fieldName is not valid : " . $fieldValue);
1736 }
1737 }
1738
1739 /**
1740 * Validate foreign constraint fields being passed into API.
1741 *
1742 * @param array $params
1743 * Params from civicrm_api.
1744 * @param string $fieldName
1745 * Uniquename of field being checked.
1746 *
1747 * @throws Exception
1748 */
1749 function _civicrm_api3_validate_unique_key(&$params, &$fieldName) {
1750 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
1751 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
1752 return;
1753 }
1754 $existing = civicrm_api($params['entity'], 'get', array(
1755 'version' => $params['version'],
1756 $fieldName => $fieldValue,
1757 ));
1758 // an entry already exists for this unique field
1759 if ($existing['count'] == 1) {
1760 // question - could this ever be a security issue?
1761 throw new API_Exception("Field: `$fieldName` must be unique. An conflicting entity already exists - id: " . $existing['id']);
1762 }
1763 }
1764
1765 /**
1766 * Generic implementation of the "replace" action.
1767 *
1768 * Replace the old set of entities (matching some given keys) with a new set of
1769 * entities (matching the same keys).
1770 *
1771 * @note This will verify that 'values' is present, but it does not directly verify
1772 * any other parameters.
1773 *
1774 * @param string $entity
1775 * Entity name.
1776 * @param array $params
1777 * Params from civicrm_api, including:.
1778 * - 'values': an array of records to save
1779 * - all other items: keys which identify new/pre-existing records.
1780 *
1781 * @return array|int
1782 */
1783 function _civicrm_api3_generic_replace($entity, $params) {
1784
1785 $transaction = new CRM_Core_Transaction();
1786 try {
1787 if (!is_array($params['values'])) {
1788 throw new Exception("Mandatory key(s) missing from params array: values");
1789 }
1790
1791 // Extract the keys -- somewhat scary, don't think too hard about it
1792 $baseParams = _civicrm_api3_generic_replace_base_params($params);
1793
1794 // Lookup pre-existing records
1795 $preexisting = civicrm_api($entity, 'get', $baseParams, $params);
1796 if (civicrm_error($preexisting)) {
1797 $transaction->rollback();
1798 return $preexisting;
1799 }
1800
1801 // Save the new/updated records
1802 $creates = array();
1803 foreach ($params['values'] as $replacement) {
1804 // Sugar: Don't force clients to duplicate the 'key' data
1805 $replacement = array_merge($baseParams, $replacement);
1806 $action = (isset($replacement['id']) || isset($replacement[$entity . '_id'])) ? 'update' : 'create';
1807 $create = civicrm_api($entity, $action, $replacement);
1808 if (civicrm_error($create)) {
1809 $transaction->rollback();
1810 return $create;
1811 }
1812 foreach ($create['values'] as $entity_id => $entity_value) {
1813 $creates[$entity_id] = $entity_value;
1814 }
1815 }
1816
1817 // Remove stale records
1818 $staleIDs = array_diff(
1819 array_keys($preexisting['values']),
1820 array_keys($creates)
1821 );
1822 foreach ($staleIDs as $staleID) {
1823 $delete = civicrm_api($entity, 'delete', array(
1824 'version' => $params['version'],
1825 'id' => $staleID,
1826 ));
1827 if (civicrm_error($delete)) {
1828 $transaction->rollback();
1829 return $delete;
1830 }
1831 }
1832
1833 return civicrm_api3_create_success($creates, $params);
1834 }
1835 catch(PEAR_Exception $e) {
1836 $transaction->rollback();
1837 return civicrm_api3_create_error($e->getMessage());
1838 }
1839 catch(Exception $e) {
1840 $transaction->rollback();
1841 return civicrm_api3_create_error($e->getMessage());
1842 }
1843 }
1844
1845 /**
1846 * Replace base parameters.
1847 *
1848 * @param array $params
1849 *
1850 * @return array
1851 */
1852 function _civicrm_api3_generic_replace_base_params($params) {
1853 $baseParams = $params;
1854 unset($baseParams['values']);
1855 unset($baseParams['sequential']);
1856 unset($baseParams['options']);
1857 return $baseParams;
1858 }
1859
1860 /**
1861 * Returns fields allowable by api.
1862 *
1863 * @param $entity
1864 * String Entity to query.
1865 * @param bool $unique
1866 * Index by unique fields?.
1867 * @param array $params
1868 *
1869 * @return array
1870 */
1871 function _civicrm_api_get_fields($entity, $unique = FALSE, &$params = array()) {
1872 $unsetIfEmpty = array(
1873 'dataPattern',
1874 'headerPattern',
1875 'default',
1876 'export',
1877 'import',
1878 );
1879 $dao = _civicrm_api3_get_DAO($entity);
1880 if (empty($dao)) {
1881 return array();
1882 }
1883 $d = new $dao();
1884 $fields = $d->fields();
1885
1886 // Set html attributes for text fields
1887 foreach ($fields as $name => &$field) {
1888 if (isset($field['html'])) {
1889 $field['html'] += (array) $d::makeAttribute($field);
1890 }
1891 }
1892
1893 // replace uniqueNames by the normal names as the key
1894 if (empty($unique)) {
1895 foreach ($fields as $name => &$field) {
1896 //getting rid of unused attributes
1897 foreach ($unsetIfEmpty as $attr) {
1898 if (empty($field[$attr])) {
1899 unset($field[$attr]);
1900 }
1901 }
1902 if ($name == $field['name']) {
1903 continue;
1904 }
1905 if (array_key_exists($field['name'], $fields)) {
1906 $field['error'] = 'name conflict';
1907 // it should never happen, but better safe than sorry
1908 continue;
1909 }
1910 $fields[$field['name']] = $field;
1911 $fields[$field['name']]['uniqueName'] = $name;
1912 unset($fields[$name]);
1913 }
1914 }
1915 // Translate FKClassName to the corresponding api
1916 foreach ($fields as $name => &$field) {
1917 if (!empty($field['FKClassName'])) {
1918 $FKApi = CRM_Core_DAO_AllCoreTables::getBriefName($field['FKClassName']);
1919 if ($FKApi) {
1920 $field['FKApiName'] = $FKApi;
1921 }
1922 }
1923 }
1924 $fields += _civicrm_api_get_custom_fields($entity, $params);
1925 return $fields;
1926 }
1927
1928 /**
1929 * Return an array of fields for a given entity.
1930 *
1931 * This is the same as the BAO function but fields are prefixed with 'custom_' to represent api params.
1932 *
1933 * @param $entity
1934 * @param array $params
1935 *
1936 * @return array
1937 */
1938 function _civicrm_api_get_custom_fields($entity, &$params) {
1939 $entity = _civicrm_api_get_camel_name($entity);
1940 if ($entity == 'Contact') {
1941 // Use sub-type if available, otherwise "NULL" to fetch from all contact types
1942 $entity = CRM_Utils_Array::value('contact_type', $params);
1943 }
1944 $customfields = CRM_Core_BAO_CustomField::getFields($entity,
1945 FALSE,
1946 FALSE,
1947 // we could / should probably test for other subtypes here - e.g. activity_type_id
1948 CRM_Utils_Array::value('contact_sub_type', $params),
1949 NULL,
1950 FALSE,
1951 FALSE,
1952 FALSE
1953 );
1954
1955 $ret = array();
1956
1957 foreach ($customfields as $key => $value) {
1958 // Regular fields have a 'name' property
1959 $value['name'] = 'custom_' . $key;
1960 $value['title'] = $value['label'];
1961 $value['type'] = _getStandardTypeFromCustomDataType($value);
1962 $ret['custom_' . $key] = $value;
1963 }
1964 return $ret;
1965 }
1966
1967 /**
1968 * Translate the custom field data_type attribute into a std 'type'.
1969 *
1970 * @param array $value
1971 *
1972 * @return int
1973 */
1974 function _getStandardTypeFromCustomDataType($value) {
1975 $dataType = $value['data_type'];
1976 //CRM-15792 - If date custom field contains timeformat change type to DateTime
1977 if ($value['data_type'] == 'Date' && isset($value['time_format']) && $value['time_format'] > 0) {
1978 $dataType = 'DateTime';
1979 }
1980 $mapping = array(
1981 'String' => CRM_Utils_Type::T_STRING,
1982 'Int' => CRM_Utils_Type::T_INT,
1983 'Money' => CRM_Utils_Type::T_MONEY,
1984 'Memo' => CRM_Utils_Type::T_LONGTEXT,
1985 'Float' => CRM_Utils_Type::T_FLOAT,
1986 'Date' => CRM_Utils_Type::T_DATE,
1987 'DateTime' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
1988 'Boolean' => CRM_Utils_Type::T_BOOLEAN,
1989 'StateProvince' => CRM_Utils_Type::T_INT,
1990 'File' => CRM_Utils_Type::T_STRING,
1991 'Link' => CRM_Utils_Type::T_STRING,
1992 'ContactReference' => CRM_Utils_Type::T_INT,
1993 'Country' => CRM_Utils_Type::T_INT,
1994 );
1995 return $mapping[$dataType];
1996 }
1997
1998
1999 /**
2000 * Fill params array with alternate (alias) values where a field has an alias and that is filled & the main field isn't.
2001 *
2002 * If multiple aliases the last takes precedence
2003 *
2004 * Function also swaps unique fields for non-unique fields & vice versa.
2005 *
2006 * @param $apiRequest
2007 * @param $fields
2008 */
2009 function _civicrm_api3_swap_out_aliases(&$apiRequest, $fields) {
2010 foreach ($fields as $field => $values) {
2011 $uniqueName = CRM_Utils_Array::value('uniqueName', $values);
2012 if (!empty($values['api.aliases'])) {
2013 // if aliased field is not set we try to use field alias
2014 if (!isset($apiRequest['params'][$field])) {
2015 foreach ($values['api.aliases'] as $alias) {
2016 if (isset($apiRequest['params'][$alias])) {
2017 $apiRequest['params'][$field] = $apiRequest['params'][$alias];
2018 }
2019 //unset original field nb - need to be careful with this as it may bring inconsistencies
2020 // out of the woodwork but will be implementing only as _spec function extended
2021 unset($apiRequest['params'][$alias]);
2022 }
2023 }
2024 }
2025 if (!isset($apiRequest['params'][$field]) && !empty($values['name']) && $field != $values['name']
2026 && isset($apiRequest['params'][$values['name']])
2027 ) {
2028 $apiRequest['params'][$field] = $apiRequest['params'][$values['name']];
2029 // note that it would make sense to unset the original field here but tests need to be in place first
2030 if ($field != 'domain_version') {
2031 unset($apiRequest['params'][$values['name']]);
2032 }
2033 }
2034 if (!isset($apiRequest['params'][$field])
2035 && $uniqueName
2036 && $field != $uniqueName
2037 && array_key_exists($uniqueName, $apiRequest['params'])
2038 ) {
2039 $apiRequest['params'][$field] = CRM_Utils_Array::value($values['uniqueName'], $apiRequest['params']);
2040 // note that it would make sense to unset the original field here but tests need to be in place first
2041 }
2042 }
2043
2044 }
2045
2046 /**
2047 * Validate integer fields being passed into API.
2048 *
2049 * It currently converts the incoming value 'user_contact_id' into the id of the currently logged in user.
2050 *
2051 * @param array $params
2052 * Params from civicrm_api.
2053 * @param string $fieldName
2054 * Uniquename of field being checked.
2055 * @param array $fieldInfo
2056 * Array of fields from getfields function.
2057 * @param string $entity
2058 *
2059 * @throws API_Exception
2060 */
2061 function _civicrm_api3_validate_integer(&$params, &$fieldName, &$fieldInfo, $entity) {
2062 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2063 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
2064 return;
2065 }
2066
2067 if (!empty($fieldValue) || $fieldValue === '0' || $fieldValue === 0) {
2068 // if value = 'user_contact_id' (or similar), replace value with contact id
2069 if (!is_numeric($fieldValue) && is_scalar($fieldValue)) {
2070 $realContactId = _civicrm_api3_resolve_contactID($fieldValue);
2071 if ('unknown-user' === $realContactId) {
2072 throw new API_Exception("\"$fieldName\" \"{$fieldValue}\" cannot be resolved to a contact ID", 2002, array('error_field' => $fieldName, "type" => "integer"));
2073 }
2074 elseif (is_numeric($realContactId)) {
2075 $fieldValue = $realContactId;
2076 }
2077 }
2078 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) {
2079 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2080 }
2081
2082 // After swapping options, ensure we have an integer(s)
2083 foreach ((array) ($fieldValue) as $value) {
2084 if ($value && !is_numeric($value) && $value !== 'null' && !is_array($value)) {
2085 throw new API_Exception("$fieldName is not a valid integer", 2001, array('error_field' => $fieldName, "type" => "integer"));
2086 }
2087 }
2088
2089 // Check our field length
2090 if (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen($fieldValue) > $fieldInfo['maxlength']
2091 ) {
2092 throw new API_Exception($fieldValue . " is " . strlen($fieldValue) . " characters - longer than $fieldName length" . $fieldInfo['maxlength'] . ' characters',
2093 2100, array('field' => $fieldName, "max_length" => $fieldInfo['maxlength'])
2094 );
2095 }
2096 }
2097
2098 if (!empty($op)) {
2099 $params[$fieldName][$op] = $fieldValue;
2100 }
2101 else {
2102 $params[$fieldName] = $fieldValue;
2103 }
2104 }
2105
2106 /**
2107 * Determine a contact ID using a string expression.
2108 *
2109 * @param string $contactIdExpr
2110 * E.g. "user_contact_id" or "@user:username".
2111 *
2112 * @return int|NULL|'unknown-user'
2113 */
2114 function _civicrm_api3_resolve_contactID($contactIdExpr) {
2115 // If value = 'user_contact_id' replace value with logged in user id.
2116 if ($contactIdExpr == "user_contact_id") {
2117 return CRM_Core_Session::getLoggedInContactID();
2118 }
2119 elseif (preg_match('/^@user:(.*)$/', $contactIdExpr, $matches)) {
2120 $config = CRM_Core_Config::singleton();
2121
2122 $ufID = $config->userSystem->getUfId($matches[1]);
2123 if (!$ufID) {
2124 return 'unknown-user';
2125 }
2126
2127 $contactID = CRM_Core_BAO_UFMatch::getContactId($ufID);
2128 if (!$contactID) {
2129 return 'unknown-user';
2130 }
2131
2132 return $contactID;
2133 }
2134 return NULL;
2135 }
2136
2137 /**
2138 * Validate html (check for scripting attack).
2139 *
2140 * @param array $params
2141 * @param string $fieldName
2142 * @param array $fieldInfo
2143 *
2144 * @throws API_Exception
2145 */
2146 function _civicrm_api3_validate_html(&$params, &$fieldName, $fieldInfo) {
2147 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName);
2148 if (strpos($op, 'NULL') || strpos($op, 'EMPTY')) {
2149 return;
2150 }
2151 if ($fieldValue) {
2152 if (!CRM_Utils_Rule::xssString($fieldValue)) {
2153 throw new API_Exception('Input contains illegal SCRIPT tag.', array("field" => $fieldName, "error_code" => "xss"));
2154 }
2155 }
2156 }
2157
2158 /**
2159 * Validate string fields being passed into API.
2160 *
2161 * @param array $params
2162 * Params from civicrm_api.
2163 * @param string $fieldName
2164 * Uniquename of field being checked.
2165 * @param array $fieldInfo
2166 * Array of fields from getfields function.
2167 * @param string $entity
2168 *
2169 * @throws API_Exception
2170 * @throws Exception
2171 */
2172 function _civicrm_api3_validate_string(&$params, &$fieldName, &$fieldInfo, $entity) {
2173 list($fieldValue, $op) = _civicrm_api3_field_value_check($params, $fieldName, 'String');
2174 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE || CRM_Utils_System::isNull($fieldValue)) {
2175 return;
2176 }
2177
2178 if (!is_array($fieldValue)) {
2179 $fieldValue = (string) $fieldValue;
2180 }
2181 else {
2182 //@todo what do we do about passed in arrays. For many of these fields
2183 // the missing piece of functionality is separating them to a separated string
2184 // & many save incorrectly. But can we change them wholesale?
2185 }
2186 if ($fieldValue) {
2187 foreach ((array) $fieldValue as $value) {
2188 if (!CRM_Utils_Rule::xssString($fieldValue)) {
2189 throw new Exception('Input contains illegal SCRIPT tag.');
2190 }
2191 if ($fieldName == 'currency') {
2192 //When using IN operator $fieldValue is a array of currency codes
2193 if (!CRM_Utils_Rule::currencyCode($value)) {
2194 throw new Exception("Currency not a valid code: $currency");
2195 }
2196 }
2197 }
2198 }
2199 if (!empty($fieldInfo['pseudoconstant']) || !empty($fieldInfo['options'])) {
2200 _civicrm_api3_api_match_pseudoconstant($fieldValue, $entity, $fieldName, $fieldInfo, $op);
2201 }
2202 // Check our field length
2203 elseif (is_string($fieldValue) && !empty($fieldInfo['maxlength']) && strlen(utf8_decode($fieldValue)) > $fieldInfo['maxlength']) {
2204 throw new API_Exception("Value for $fieldName is " . strlen(utf8_decode($value)) . " characters - This field has a maxlength of {$fieldInfo['maxlength']} characters.",
2205 2100, array('field' => $fieldName)
2206 );
2207 }
2208
2209 if (!empty($op)) {
2210 $params[$fieldName][$op] = $fieldValue;
2211 }
2212 else {
2213 $params[$fieldName] = $fieldValue;
2214 }
2215 }
2216
2217 /**
2218 * Validate & swap out any pseudoconstants / options.
2219 *
2220 * @param mixed $fieldValue
2221 * @param string $entity : api entity name
2222 * @param string $fieldName : field name used in api call (not necessarily the canonical name)
2223 * @param array $fieldInfo : getfields meta-data
2224 * @param string $op
2225 *
2226 * @throws \API_Exception
2227 */
2228 function _civicrm_api3_api_match_pseudoconstant(&$fieldValue, $entity, $fieldName, $fieldInfo, $op = '=') {
2229 if (in_array($op, array('>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'))) {
2230 return;
2231 }
2232
2233 $options = CRM_Utils_Array::value('options', $fieldInfo);
2234
2235 if (!$options) {
2236 if (strtolower($entity) == 'profile' && !empty($fieldInfo['entity'])) {
2237 // We need to get the options from the entity the field relates to.
2238 $entity = $fieldInfo['entity'];
2239 }
2240 $options = civicrm_api($entity, 'getoptions', array(
2241 'version' => 3,
2242 'field' => $fieldInfo['name'],
2243 'context' => 'validate',
2244 ));
2245 $options = CRM_Utils_Array::value('values', $options, array());
2246 }
2247
2248 // If passed a value-separated string, explode to an array, then re-implode after matching values.
2249 $implode = FALSE;
2250 if (is_string($fieldValue) && strpos($fieldValue, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
2251 $fieldValue = CRM_Utils_Array::explodePadded($fieldValue);
2252 $implode = TRUE;
2253 }
2254 // If passed multiple options, validate each.
2255 if (is_array($fieldValue)) {
2256 foreach ($fieldValue as &$value) {
2257 if (!is_array($value)) {
2258 _civicrm_api3_api_match_pseudoconstant_value($value, $options, $fieldName);
2259 }
2260 }
2261 // TODO: unwrap the call to implodePadded from the conditional and do it always
2262 // need to verify that this is safe and doesn't break anything though.
2263 // Better yet would be to leave it as an array and ensure that every dao/bao can handle array input
2264 if ($implode) {
2265 CRM_Utils_Array::implodePadded($fieldValue);
2266 }
2267 }
2268 else {
2269 _civicrm_api3_api_match_pseudoconstant_value($fieldValue, $options, $fieldName);
2270 }
2271 }
2272
2273 /**
2274 * Validate & swap a single option value for a field.
2275 *
2276 * @param string $value field value
2277 * @param array $options array of options for this field
2278 * @param string $fieldName field name used in api call (not necessarily the canonical name)
2279 *
2280 * @throws API_Exception
2281 */
2282 function _civicrm_api3_api_match_pseudoconstant_value(&$value, $options, $fieldName) {
2283 // If option is a key, no need to translate
2284 // or if no options are avaiable for pseudoconstant 'table' property
2285 if (array_key_exists($value, $options) || !$options) {
2286 return;
2287 }
2288
2289 // Translate value into key
2290 // Cast $value to string to avoid a bug in array_search
2291 $newValue = array_search((string) $value, $options);
2292 if ($newValue !== FALSE) {
2293 $value = $newValue;
2294 return;
2295 }
2296 // Case-insensitive matching
2297 $newValue = strtolower($value);
2298 $options = array_map("strtolower", $options);
2299 $newValue = array_search($newValue, $options);
2300 if ($newValue === FALSE) {
2301 throw new API_Exception("'$value' is not a valid option for field $fieldName", 2001, array('error_field' => $fieldName));
2302 }
2303 $value = $newValue;
2304 }
2305
2306 /**
2307 * Returns the canonical name of a field.
2308 *
2309 * @param $entity
2310 * api entity name (string should already be standardized - no camelCase).
2311 * @param $fieldName
2312 * any variation of a field's name (name, unique_name, api.alias).
2313 *
2314 * @param string $action
2315 *
2316 * @return bool|string
2317 * FieldName or FALSE if the field does not exist
2318 */
2319 function _civicrm_api3_api_resolve_alias($entity, $fieldName, $action = 'create') {
2320 if (!$fieldName) {
2321 return FALSE;
2322 }
2323 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2324 return $fieldName;
2325 }
2326 if ($fieldName == _civicrm_api_get_entity_name_from_camel($entity) . '_id') {
2327 return 'id';
2328 }
2329 $result = civicrm_api($entity, 'getfields', array(
2330 'version' => 3,
2331 'action' => $action,
2332 ));
2333 $meta = $result['values'];
2334 if (!isset($meta[$fieldName]['name']) && isset($meta[$fieldName . '_id'])) {
2335 $fieldName = $fieldName . '_id';
2336 }
2337 if (isset($meta[$fieldName])) {
2338 return $meta[$fieldName]['name'];
2339 }
2340 foreach ($meta as $info) {
2341 if ($fieldName == $info['name'] || $fieldName == CRM_Utils_Array::value('uniqueName', $info)) {
2342 return $info['name'];
2343 }
2344 if (array_search($fieldName, CRM_Utils_Array::value('api.aliases', $info, array())) !== FALSE) {
2345 return $info['name'];
2346 }
2347 }
2348 // Create didn't work, try with get
2349 if ($action == 'create') {
2350 return _civicrm_api3_api_resolve_alias($entity, $fieldName, 'get');
2351 }
2352 return FALSE;
2353 }
2354
2355 /**
2356 * Check if the function is deprecated.
2357 *
2358 * @param string $entity
2359 * @param array $result
2360 *
2361 * @return string|array|null
2362 */
2363 function _civicrm_api3_deprecation_check($entity, $result = array()) {
2364 if ($entity) {
2365 $apiFile = "api/v3/$entity.php";
2366 if (CRM_Utils_File::isIncludable($apiFile)) {
2367 require_once $apiFile;
2368 }
2369 $lowercase_entity = _civicrm_api_get_entity_name_from_camel($entity);
2370 $fnName = "_civicrm_api3_{$lowercase_entity}_deprecation";
2371 if (function_exists($fnName)) {
2372 return $fnName($result);
2373 }
2374 }
2375 }
2376
2377 /**
2378 * Get the actual field value.
2379 *
2380 * In some case $params[$fieldName] holds Array value in this format Array([operator] => [value])
2381 * So this function returns the actual field value.
2382 *
2383 * @param array $params
2384 * @param string $fieldName
2385 * @param string $type
2386 *
2387 * @return mixed
2388 */
2389 function _civicrm_api3_field_value_check(&$params, $fieldName, $type = NULL) {
2390 $fieldValue = CRM_Utils_Array::value($fieldName, $params);
2391 $op = NULL;
2392
2393 if (!empty($fieldValue) && is_array($fieldValue) &&
2394 (array_search(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators()) ||
2395 $type == 'String' && strstr(key($fieldValue), 'EMPTY'))
2396 ) {
2397 $op = key($fieldValue);
2398 $fieldValue = CRM_Utils_Array::value($op, $fieldValue);
2399 }
2400 return array($fieldValue, $op);
2401 }
2402
2403 /**
2404 * A generic "get" API based on simple array data. This is comparable to
2405 * _civicrm_api3_basic_get but does not use DAO/BAO. This is useful for
2406 * small/mid-size data loaded from external JSON or XML documents.
2407 *
2408 * @param $entity
2409 * @param array $params
2410 * API parameters.
2411 * @param array $records
2412 * List of all records.
2413 * @param string $idCol
2414 * The property which defines the ID of a record
2415 * @param array $fields
2416 * List of filterable fields.
2417 *
2418 * @return array
2419 * @throws \API_Exception
2420 */
2421 function _civicrm_api3_basic_array_get($entity, $params, $records, $idCol, $fields) {
2422 $options = _civicrm_api3_get_options_from_params($params, TRUE, $entity, 'get');
2423 // TODO // $sort = CRM_Utils_Array::value('sort', $options, NULL);
2424 $offset = CRM_Utils_Array::value('offset', $options);
2425 $limit = CRM_Utils_Array::value('limit', $options);
2426
2427 $matches = array();
2428
2429 $currentOffset = 0;
2430 foreach ($records as $record) {
2431 if ($idCol != 'id') {
2432 $record['id'] = $record[$idCol];
2433 }
2434 $match = TRUE;
2435 foreach ($params as $k => $v) {
2436 if ($k == 'id') {
2437 $k = $idCol;
2438 }
2439 if (in_array($k, $fields) && $record[$k] != $v) {
2440 $match = FALSE;
2441 break;
2442 }
2443 }
2444 if ($match) {
2445 if ($currentOffset >= $offset) {
2446 $matches[$record[$idCol]] = $record;
2447 }
2448 if ($limit && count($matches) >= $limit) {
2449 break;
2450 }
2451 $currentOffset++;
2452 }
2453 }
2454
2455 $return = CRM_Utils_Array::value('return', $options, array());
2456 if (!empty($return)) {
2457 $return['id'] = 1;
2458 $matches = CRM_Utils_Array::filterColumns($matches, array_keys($return));
2459 }
2460
2461 return civicrm_api3_create_success($matches, $params);
2462 }
2463
2464 /**
2465 * @param string $bao_name
2466 * @param array $params
2467 * @throws \Civi\API\Exception\UnauthorizedException
2468 */
2469 function _civicrm_api3_check_edit_permissions($bao_name, $params) {
2470 // For lack of something more clever, here's a whitelist of entities whos permissions
2471 // are inherited from a contact record.
2472 // Note, when adding here, also remember to modify _civicrm_api3_permissions()
2473 $contactEntities = array(
2474 'CRM_Core_BAO_Email',
2475 'CRM_Core_BAO_Phone',
2476 'CRM_Core_BAO_Address',
2477 'CRM_Core_BAO_IM',
2478 'CRM_Core_BAO_Website',
2479 'CRM_Core_BAO_OpenID',
2480 );
2481 if (!empty($params['check_permissions']) && in_array($bao_name, $contactEntities)) {
2482 $cid = !empty($params['contact_id']) ? $params['contact_id'] : CRM_Core_DAO::getFieldValue($bao_name, $params['id'], 'contact_id');
2483 if (!CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT)) {
2484 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
2485 }
2486 }
2487 }