]> git.mxchange.org Git - friendica.git/blobdiff - include/api.php
And again ...
[friendica.git] / include / api.php
index fe87799cc8ac18a89090511f8ad100783abbe7a5..5f89b7ecf8dbf0ffbcbc58c4c08e3c591c2682c8 100644 (file)
@@ -27,12 +27,9 @@ use Friendica\App;
 use Friendica\Content\ContactSelector;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\HTML;
-use Friendica\Core\Hook;
 use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
-use Friendica\Core\Session;
 use Friendica\Core\System;
-use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\Contact;
@@ -45,9 +42,9 @@ use Friendica\Model\Post;
 use Friendica\Model\Profile;
 use Friendica\Model\User;
 use Friendica\Model\Verb;
+use Friendica\Module\BaseApi;
 use Friendica\Network\HTTPException;
 use Friendica\Network\HTTPException\BadRequestException;
-use Friendica\Network\HTTPException\ExpectationFailedException;
 use Friendica\Network\HTTPException\ForbiddenException;
 use Friendica\Network\HTTPException\InternalServerErrorException;
 use Friendica\Network\HTTPException\MethodNotAllowedException;
@@ -56,13 +53,12 @@ use Friendica\Network\HTTPException\TooManyRequestsException;
 use Friendica\Network\HTTPException\UnauthorizedException;
 use Friendica\Object\Image;
 use Friendica\Protocol\Activity;
-use Friendica\Protocol\Diaspora;
+use Friendica\Security\BasicAuth;
 use Friendica\Security\OAuth;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Images;
 use Friendica\Util\Network;
 use Friendica\Util\Strings;
-use Friendica\Util\XML;
 
 require_once __DIR__ . '/../mod/item.php';
 require_once __DIR__ . '/../mod/wall_upload.php';
@@ -173,94 +169,6 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY
        ];
 }
 
-/**
- * Log in user via Simple HTTP Auth.
- * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
- *
- * @param App $a App
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- * @hook  'authenticate'
- *               array $addon_auth
- *               'username' => username from login form
- *               'password' => password from login form
- *               'authenticated' => return status,
- *               'user_record' => return authenticated user record
- */
-function api_login(App $a)
-{
-       $_SESSION["allow_api"] = false;
-
-       // workaround for HTTP-auth in CGI mode
-       if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
-               $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
-               if (strlen($userpass)) {
-                       list($name, $password) = explode(':', $userpass);
-                       $_SERVER['PHP_AUTH_USER'] = $name;
-                       $_SERVER['PHP_AUTH_PW'] = $password;
-               }
-       }
-
-       if (empty($_SERVER['PHP_AUTH_USER'])) {
-               Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
-               header('WWW-Authenticate: Basic realm="Friendica"');
-               throw new UnauthorizedException("This API requires login");
-       }
-
-       $user = $_SERVER['PHP_AUTH_USER'] ?? '';
-       $password = $_SERVER['PHP_AUTH_PW'] ?? '';
-
-       // allow "user@server" login (but ignore 'server' part)
-       $at = strstr($user, "@", true);
-       if ($at) {
-               $user = $at;
-       }
-
-       // next code from mod/auth.php. needs better solution
-       $record = null;
-
-       $addon_auth = [
-               'username' => trim($user),
-               'password' => trim($password),
-               'authenticated' => 0,
-               'user_record' => null,
-       ];
-
-       /*
-       * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
-       * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
-       * and later addons should not interfere with an earlier one that succeeded.
-       */
-       Hook::callAll('authenticate', $addon_auth);
-
-       if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
-               $record = $addon_auth['user_record'];
-       } else {
-               $user_id = User::authenticate(trim($user), trim($password), true);
-               if ($user_id !== false) {
-                       $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
-               }
-       }
-
-       if (!DBA::isResult($record)) {
-               Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
-               header('WWW-Authenticate: Basic realm="Friendica"');
-               //header('HTTP/1.0 401 Unauthorized');
-               //die('This api requires login');
-               throw new UnauthorizedException("This API requires login");
-       }
-
-       // Don't refresh the login date more often than twice a day to spare database writes
-       $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
-
-       DI::auth()->setForUser($a, $record, false, false, $login_refresh);
-
-       $_SESSION["allow_api"] = true;
-
-       Hook::callAll('logged_in', $record);
-}
-
 /**
  * Check HTTP method of called API
  *
@@ -320,8 +228,8 @@ function api_call(App $a, App\Arguments $args = null)
 
                                $called_api = explode("/", $p);
 
-                               if (!empty($info['auth']) && api_user() === false) {
-                                       api_login($a);
+                               if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
+                                       BasicAuth::getCurrentUserID(true);
                                        Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
                                }
 
@@ -373,53 +281,13 @@ function api_call(App $a, App\Arguments $args = null)
                Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
                throw new NotFoundException();
        } catch (HTTPException $e) {
-               header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
-               return api_error($type, $e, $args);
-       }
-}
-
-/**
- * Format API error string
- *
- * @param string $type Return type (xml, json, rss, as)
- * @param object $e    HTTPException Error object
- * @param App\Arguments $args The App arguments
- * @return string|array error message formatted as $type
- */
-function api_error($type, $e, App\Arguments $args)
-{
-       $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
-       /// @TODO:  https://dev.twitter.com/overview/api/response-codes
-
-       $error = ["error" => $error,
-                       "code" => $e->getCode() . " " . $e->httpdesc,
-                       "request" => $args->getQueryString()];
-
-       $return = api_format_data('status', $type, ['status' => $error]);
-
-       switch ($type) {
-               case "xml":
-                       header("Content-Type: text/xml");
-                       break;
-               case "json":
-                       header("Content-Type: application/json");
-                       $return = json_encode($return);
-                       break;
-               case "rss":
-                       header("Content-Type: application/rss+xml");
-                       break;
-               case "atom":
-                       header("Content-Type: application/atom+xml");
-                       break;
+               DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
        }
-
-       return $return;
 }
 
 /**
  * Set values for RSS template
  *
- * @param App   $a
  * @param array $arr       Array to be passed to template
  * @param array $user_info User info
  * @return array
@@ -429,10 +297,15 @@ function api_error($type, $e, App\Arguments $args)
  * @throws UnauthorizedException
  * @todo  find proper type-hints
  */
-function api_rss_extra(App $a, $arr, $user_info)
+function api_rss_extra($arr, $user_info)
 {
        if (is_null($user_info)) {
-               $user_info = api_get_user($a);
+               $uid = BaseApi::getCurrentUserID();
+               if (empty($uid)) {
+                       throw new ForbiddenException();
+               }
+
+               $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
        }
 
        $arr['$user'] = $user_info;
@@ -480,7 +353,7 @@ function api_unique_id_to_nurl($id)
  * @throws InternalServerErrorException
  * @throws UnauthorizedException
  */
-function api_get_user(App $a, $contact_id = null)
+function api_get_user($contact_id = null)
 {
        global $called_api;
 
@@ -492,55 +365,55 @@ function api_get_user(App $a, $contact_id = null)
 
        // Searching for contact URL
        if (!is_null($contact_id) && (intval($contact_id) == 0)) {
-               $user = DBA::escape(Strings::normaliseLink($contact_id));
+               $user = Strings::normaliseLink($contact_id);
                $url = $user;
-               $extra_query = "AND `contact`.`nurl` = '%s' ";
-               if (api_user() !== false) {
-                       $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
+               $extra_query = "AND `contact`.`nurl` = ? ";
+               if (BaseApi::getCurrentUserID() !== false) {
+                       $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
                }
        }
 
        // Searching for contact id with uid = 0
        if (!is_null($contact_id) && (intval($contact_id) != 0)) {
-               $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
+               $user = api_unique_id_to_nurl(intval($contact_id));
 
                if ($user == "") {
                        throw new BadRequestException("User ID ".$contact_id." not found.");
                }
 
                $url = $user;
-               $extra_query = "AND `contact`.`nurl` = '%s' ";
-               if (api_user() !== false) {
-                       $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
+               $extra_query = "AND `contact`.`nurl` = ? ";
+               if (BaseApi::getCurrentUserID() !== false) {
+                       $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
                }
        }
 
        if (is_null($user) && !empty($_GET['user_id'])) {
-               $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
+               $user = api_unique_id_to_nurl($_GET['user_id']);
 
                if ($user == "") {
                        throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
                }
 
                $url = $user;
-               $extra_query = "AND `contact`.`nurl` = '%s' ";
-               if (api_user() !== false) {
-                       $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
+               $extra_query = "AND `contact`.`nurl` = ? ";
+               if (BaseApi::getCurrentUserID() !== false) {
+                       $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
                }
        }
        if (is_null($user) && !empty($_GET['screen_name'])) {
-               $user = DBA::escape($_GET['screen_name']);
-               $extra_query = "AND `contact`.`nick` = '%s' ";
-               if (api_user() !== false) {
-                       $extra_query .= "AND `contact`.`uid`=".intval(api_user());
+               $user = $_GET['screen_name'];
+               $extra_query = "AND `contact`.`nick` = ? ";
+               if (BaseApi::getCurrentUserID() !== false) {
+                       $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
                }
        }
 
        if (is_null($user) && !empty($_GET['profileurl'])) {
-               $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
-               $extra_query = "AND `contact`.`nurl` = '%s' ";
-               if (api_user() !== false) {
-                       $extra_query .= "AND `contact`.`uid`=".intval(api_user());
+               $user = Strings::normaliseLink($_GET['profileurl']);
+               $extra_query = "AND `contact`.`nurl` = ? ";
+               if (BaseApi::getCurrentUserID() !== false) {
+                       $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
                }
        }
 
@@ -550,24 +423,23 @@ function api_get_user(App $a, $contact_id = null)
                if (!empty(DI::args()->getArgv()[$argid])) {
                        $data = explode(".", DI::args()->getArgv()[$argid]);
                        if (count($data) > 1) {
-                               list($user, $null) = $data;
+                               [$user, $null] = $data;
                        }
                }
                if (is_numeric($user)) {
-                       $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
+                       $user = api_unique_id_to_nurl(intval($user));
 
                        if ($user != "") {
                                $url = $user;
-                               $extra_query = "AND `contact`.`nurl` = '%s' ";
-                               if (api_user() !== false) {
-                                       $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
+                               $extra_query = "AND `contact`.`nurl` = ? ";
+                               if (BaseApi::getCurrentUserID() !== false) {
+                                       $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
                                }
                        }
                } else {
-                       $user = DBA::escape($user);
-                       $extra_query = "AND `contact`.`nick` = '%s' ";
-                       if (api_user() !== false) {
-                               $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
+                       $extra_query = "AND `contact`.`nick` = ? ";
+                       if (BaseApi::getCurrentUserID() !== false) {
+                               $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
                        }
                }
        }
@@ -575,187 +447,42 @@ function api_get_user(App $a, $contact_id = null)
        Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
 
        if (!$user) {
-               if (api_user() === false) {
-                       api_login($a);
+               if (empty(BaseApi::getCurrentUserID())) {
+                       BasicAuth::getCurrentUserID(true);
                        return false;
                } else {
-                       $user = api_user();
-                       $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
+                       $user = BaseApi::getCurrentUserID();
+                       $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
                }
        }
 
        Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
 
        // user info
-       $uinfo = q(
+       $uinfo = DBA::toArray(DBA::p(
                "SELECT *, `contact`.`id` AS `cid` FROM `contact`
                        WHERE 1
                $extra_query",
                $user
-       );
+       ));
 
-       // Selecting the id by priority, friendica first
-       if (is_array($uinfo)) {
+       if (DBA::isResult($uinfo)) {
+               // Selecting the id by priority, friendica first
                api_best_nickname($uinfo);
+               return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
        }
 
-       // if the contact wasn't found, fetch it from the contacts with uid = 0
-       if (!DBA::isResult($uinfo)) {
-               if ($url == "") {
-                       throw new BadRequestException("User not found.");
-               }
-
-               $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
-
-               if (DBA::isResult($contact)) {
-                       $ret = [
-                               'id' => $contact["id"],
-                               'id_str' => (string) $contact["id"],
-                               'name' => $contact["name"],
-                               'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
-                               'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
-                               'description' => BBCode::toPlaintext($contact["about"] ?? ''),
-                               'profile_image_url' => $contact["micro"],
-                               'profile_image_url_https' => $contact["micro"],
-                               'profile_image_url_profile_size' => $contact["thumb"],
-                               'profile_image_url_large' => $contact["photo"],
-                               'url' => $contact["url"],
-                               'protected' => false,
-                               'followers_count' => 0,
-                               'friends_count' => 0,
-                               'listed_count' => 0,
-                               'created_at' => api_date($contact["created"]),
-                               'favourites_count' => 0,
-                               'utc_offset' => 0,
-                               'time_zone' => 'UTC',
-                               'geo_enabled' => false,
-                               'verified' => false,
-                               'statuses_count' => 0,
-                               'lang' => '',
-                               'contributors_enabled' => false,
-                               'is_translator' => false,
-                               'is_translation_enabled' => false,
-                               'following' => false,
-                               'follow_request_sent' => false,
-                               'statusnet_blocking' => false,
-                               'notifications' => false,
-                               'statusnet_profile_url' => $contact["url"],
-                               'uid' => 0,
-                               'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
-                               'pid' => Contact::getIdForURL($contact["url"], 0, false),
-                               'self' => 0,
-                               'network' => $contact["network"],
-                       ];
-
-                       return $ret;
-               } else {
-                       throw new BadRequestException("User ".$url." not found.");
-               }
-       }
-
-       if ($uinfo[0]['self']) {
-               if ($uinfo[0]['network'] == "") {
-                       $uinfo[0]['network'] = Protocol::DFRN;
-               }
-
-               $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
-               $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
+       if ($url == "") {
+               throw new BadRequestException("User not found.");
        }
-       $countitems = 0;
-       $countfriends = 0;
-       $countfollowers = 0;
-       $starred = 0;
 
-       $pcontact_id  = Contact::getIdForURL($uinfo[0]['url'], 0, false);
-
-       if (!empty($profile['about'])) {
-               $description = $profile['about'];
-       } else {
-               $description = $uinfo[0]["about"];
-       }
+       $cid = Contact::getIdForURL($url, 0, false);
 
-       if (!empty($usr['default-location'])) {
-               $location = $usr['default-location'];
-       } elseif (!empty($uinfo[0]["location"])) {
-               $location = $uinfo[0]["location"];
+       if (!empty($cid)) {
+               return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
        } else {
-               $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
-       }
-
-       $ret = [
-               'id' => intval($pcontact_id),
-               'id_str' => (string) intval($pcontact_id),
-               'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
-               'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
-               'location' => $location,
-               'description' => BBCode::toPlaintext($description ?? ''),
-               'profile_image_url' => $uinfo[0]['micro'],
-               'profile_image_url_https' => $uinfo[0]['micro'],
-               'profile_image_url_profile_size' => $uinfo[0]["thumb"],
-               'profile_image_url_large' => $uinfo[0]["photo"],
-               'url' => $uinfo[0]['url'],
-               'protected' => false,
-               'followers_count' => intval($countfollowers),
-               'friends_count' => intval($countfriends),
-               'listed_count' => 0,
-               'created_at' => api_date($uinfo[0]['created']),
-               'favourites_count' => intval($starred),
-               'utc_offset' => "0",
-               'time_zone' => 'UTC',
-               'geo_enabled' => false,
-               'verified' => true,
-               'statuses_count' => intval($countitems),
-               'lang' => '',
-               'contributors_enabled' => false,
-               'is_translator' => false,
-               'is_translation_enabled' => false,
-               'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
-               'follow_request_sent' => false,
-               'statusnet_blocking' => false,
-               'notifications' => false,
-               /// @TODO old way?
-               //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
-               'statusnet_profile_url' => $uinfo[0]['url'],
-               'uid' => intval($uinfo[0]['uid']),
-               'cid' => intval($uinfo[0]['cid']),
-               'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
-               'self' => $uinfo[0]['self'],
-               'network' => $uinfo[0]['network'],
-       ];
-
-       // If this is a local user and it uses Frio, we can get its color preferences.
-       if ($ret['self']) {
-               $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
-               if ($theme_info['theme'] === 'frio') {
-                       $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
-
-                       if ($schema && ($schema != '---')) {
-                               if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
-                                       $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
-                                       require_once $schemefile;
-                               }
-                       } else {
-                               $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
-                               $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
-                               $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
-                       }
-                       if (empty($nav_bg)) {
-                               $nav_bg = "#708fa0";
-                       }
-                       if (empty($link_color)) {
-                               $link_color = "#6fdbe8";
-                       }
-                       if (empty($bgcolor)) {
-                               $bgcolor = "#ededed";
-                       }
-
-                       $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
-                       $ret['profile_link_color'] = str_replace('#', '', $link_color);
-                       $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
-               }
+               throw new BadRequestException("User ".$url." not found.");
        }
-
-       return $ret;
 }
 
 /**
@@ -771,14 +498,20 @@ function api_get_user(App $a, $contact_id = null)
  */
 function api_item_get_user(App $a, $item)
 {
-       $status_user = api_get_user($a, $item['author-id'] ?? null);
+       if (empty($item['author-id'])) {
+               $item['author-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
+       }
+       $status_user = DI::twitterUser()->createFromContactId($item['author-id'], BaseApi::getCurrentUserID())->toArray();
 
        $author_user = $status_user;
 
        $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
 
        if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
-               $owner_user = api_get_user($a, $item['owner-id'] ?? null);
+               if (empty($item['owner-id'])) {
+                       $item['owner-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
+               }
+               $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], BaseApi::getCurrentUserID())->toArray();
        } else {
                $owner_user = $author_user;
        }
@@ -786,130 +519,6 @@ function api_item_get_user(App $a, $item)
        return ([$status_user, $author_user, $owner_user]);
 }
 
-/**
- * walks recursively through an array with the possibility to change value and key
- *
- * @param array    $array    The array to walk through
- * @param callable $callback The callback function
- *
- * @return array the transformed array
- */
-function api_walk_recursive(array &$array, callable $callback)
-{
-       $new_array = [];
-
-       foreach ($array as $k => $v) {
-               if (is_array($v)) {
-                       if ($callback($v, $k)) {
-                               $new_array[$k] = api_walk_recursive($v, $callback);
-                       }
-               } else {
-                       if ($callback($v, $k)) {
-                               $new_array[$k] = $v;
-                       }
-               }
-       }
-       $array = $new_array;
-
-       return $array;
-}
-
-/**
- * Callback function to transform the array in an array that can be transformed in a XML file
- *
- * @param mixed  $item Array item value
- * @param string $key  Array key
- *
- * @return boolean Should the array item be deleted?
- */
-function api_reformat_xml(&$item, &$key)
-{
-       if (is_bool($item)) {
-               $item = ($item ? "true" : "false");
-       }
-
-       if (substr($key, 0, 10) == "statusnet_") {
-               $key = "statusnet:".substr($key, 10);
-       } elseif (substr($key, 0, 10) == "friendica_") {
-               $key = "friendica:".substr($key, 10);
-       }
-       /// @TODO old-lost code?
-       //else
-       //      $key = "default:".$key;
-
-       return true;
-}
-
-/**
- * Creates the XML from a JSON style array
- *
- * @param array  $data         JSON style array
- * @param string $root_element Name of the root element
- *
- * @return string The XML data
- */
-function api_create_xml(array $data, $root_element)
-{
-       $childname = key($data);
-       $data2 = array_pop($data);
-
-       $namespaces = ["" => "http://api.twitter.com",
-                               "statusnet" => "http://status.net/schema/api/1/",
-                               "friendica" => "http://friendi.ca/schema/api/1/",
-                               "georss" => "http://www.georss.org/georss"];
-
-       /// @todo Auto detection of needed namespaces
-       if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
-               $namespaces = [];
-       }
-
-       if (is_array($data2)) {
-               $key = key($data2);
-               api_walk_recursive($data2, "api_reformat_xml");
-
-               if ($key == "0") {
-                       $data4 = [];
-                       $i = 1;
-
-                       foreach ($data2 as $item) {
-                               $data4[$i++ . ":" . $childname] = $item;
-                       }
-
-                       $data2 = $data4;
-               }
-       }
-
-       $data3 = [$root_element => $data2];
-
-       $ret = XML::fromArray($data3, $xml, false, $namespaces);
-       return $ret;
-}
-
-/**
- * Formats the data according to the data type
- *
- * @param string $root_element Name of the root element
- * @param string $type         Return type (atom, rss, xml, json)
- * @param array  $data         JSON style array
- *
- * @return array|string (string|array) XML data or JSON data
- */
-function api_format_data($root_element, $type, $data)
-{
-       switch ($type) {
-               case "atom":
-               case "rss":
-               case "xml":
-                       $ret = api_create_xml($data, $root_element);
-                       break;
-               case "json":
-               default:
-                       $ret = $data;
-                       break;
-       }
-       return $ret;
-}
-
 /**
  * TWITTER API
  */
@@ -930,11 +539,10 @@ function api_format_data($root_element, $type, $data)
  */
 function api_account_verify_credentials($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
 
        unset($_REQUEST["user_id"]);
        unset($_GET["user_id"]);
@@ -944,7 +552,7 @@ function api_account_verify_credentials($type)
 
        $skip_status = $_REQUEST['skip_status'] ?? false;
 
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        // "verified" isn't used here in the standard
        unset($user_info["verified"]);
@@ -961,7 +569,7 @@ function api_account_verify_credentials($type)
        unset($user_info["uid"]);
        unset($user_info["self"]);
 
-       return api_format_data("user", $type, ['user' => $user_info]);
+       return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -1000,13 +608,15 @@ function api_statuses_mediap($type)
 {
        $a = DI::app();
 
-       if (api_user() === false) {
-               Logger::log('api_statuses_update: no user');
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
-       $user_info = api_get_user($a);
 
-       $_REQUEST['profile_uid'] = api_user();
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
+
+       $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
        $_REQUEST['api_source'] = true;
        $txt = requestdata('status') ?? '';
        /// @TODO old-lost code?
@@ -1054,12 +664,11 @@ function api_statuses_update($type)
 {
        $a = DI::app();
 
-       if (api_user() === false) {
-               Logger::log('api_statuses_update: no user');
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
 
-       api_get_user($a);
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // convert $_POST array items to the form we use for web posts.
        if (requestdata('htmlstatus')) {
@@ -1097,7 +706,7 @@ function api_statuses_update($type)
        if (requestdata('lat') && requestdata('long')) {
                $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
        }
-       $_REQUEST['profile_uid'] = api_user();
+       $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
 
        if (!$parent) {
                // Check for throttling (maximum posts per day, week and month)
@@ -1105,11 +714,11 @@ function api_statuses_update($type)
                if ($throttle_day > 0) {
                        $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
 
-                       $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
+                       $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
                        $posts_day = Post::count($condition);
 
                        if ($posts_day > $throttle_day) {
-                               Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
+                               logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
                                // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
                                throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
                        }
@@ -1119,11 +728,11 @@ function api_statuses_update($type)
                if ($throttle_week > 0) {
                        $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
 
-                       $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
+                       $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
                        $posts_week = Post::count($condition);
 
                        if ($posts_week > $throttle_week) {
-                               Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
+                               logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
                                // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
                                throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
                        }
@@ -1133,11 +742,11 @@ function api_statuses_update($type)
                if ($throttle_month > 0) {
                        $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
 
-                       $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
+                       $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
                        $posts_month = Post::count($condition);
 
                        if ($posts_month > $throttle_month) {
-                               Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
+                               logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
                                // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
                                throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
                        }
@@ -1162,7 +771,7 @@ function api_statuses_update($type)
                        $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
                                        INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
                                                (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
-                                       ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
+                                       ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
 
                        if (!empty($media)) {
                                $ressources[] = $media[0]['resource-id'];
@@ -1210,7 +819,7 @@ function api_statuses_update($type)
        if (!empty($ressources) && !empty($item_id)) {
                $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
                foreach ($ressources as $ressource) {
-                       Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
+                       Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
                }
        }
 
@@ -1237,12 +846,11 @@ function api_media_upload()
 {
        $a = DI::app();
 
-       if (api_user() === false) {
-               Logger::log('no user');
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
 
-       api_get_user($a);
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        if (empty($_FILES['media'])) {
                // Output error
@@ -1290,14 +898,7 @@ api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST)
  */
 function api_media_metadata_create($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               Logger::info('no user');
-               throw new ForbiddenException();
-       }
-
-       api_get_user($a);
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        $postdata = Network::postdata();
 
@@ -1320,7 +921,7 @@ function api_media_metadata_create($type)
 
        Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
 
-       $condition =  ['id' => $data['media_id'], 'uid' => api_user()];
+       $condition =  ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
        $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
        if (!DBA::isResult($photo)) {
                throw new BadRequestException("Metadata not found.");
@@ -1350,7 +951,7 @@ function api_status_show($type, $item_id)
 
        Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
 
-       return api_format_data('statuses', $type, ['status' => $status_info]);
+       return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
 }
 
 /**
@@ -1403,9 +1004,9 @@ function api_get_item(array $condition)
  */
 function api_users_show($type)
 {
-       $a = Friendica\DI::app();
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
 
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        $item = api_get_last_status($user_info['pid'], $user_info['uid']);
        if (!empty($item)) {
@@ -1416,7 +1017,7 @@ function api_users_show($type)
        unset($user_info['uid']);
        unset($user_info['self']);
 
-       return api_format_data('user', $type, ['user' => $user_info]);
+       return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -1437,8 +1038,6 @@ api_register_func('api/externalprofile/show', 'api_users_show');
  */
 function api_users_search($type)
 {
-       $a = DI::app();
-
        $userlist = [];
 
        if (!empty($_GET['q'])) {
@@ -1456,7 +1055,7 @@ function api_users_search($type)
                if (DBA::isResult($contacts)) {
                        $k = 0;
                        foreach ($contacts as $contact) {
-                               $user_info = api_get_user($a, $contact['id']);
+                               $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
 
                                if ($type == 'xml') {
                                        $userlist[$k++ . ':user'] = $user_info;
@@ -1472,7 +1071,7 @@ function api_users_search($type)
                throw new BadRequestException('No search term specified.');
        }
 
-       return api_format_data('users', $type, $userlist);
+       return DI::apiResponse()->formatData('users', $type, $userlist);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -1499,7 +1098,7 @@ function api_users_lookup($type)
        if (!empty($_REQUEST['user_id'])) {
                foreach (explode(',', $_REQUEST['user_id']) as $id) {
                        if (!empty($id)) {
-                               $users[] = api_get_user(DI::app(), $id);
+                               $users[] = api_get_user($id);
                        }
                }
        }
@@ -1508,7 +1107,7 @@ function api_users_lookup($type)
                throw new NotFoundException;
        }
 
-       return api_format_data("users", $type, ['users' => $users]);
+       return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -1530,12 +1129,12 @@ api_register_func('api/users/lookup', 'api_users_lookup', true);
  */
 function api_search($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        if (empty($_REQUEST['q'])) {
                throw new BadRequestException('q parameter is required.');
@@ -1571,7 +1170,7 @@ function api_search($type)
                DBA::close($tags);
 
                if (empty($uriids)) {
-                       return api_format_data('statuses', $type, $data);
+                       return DI::apiResponse()->formatData('statuses', $type, $data);
                }
 
                $condition = ['uri-id' => $uriids];
@@ -1585,7 +1184,7 @@ function api_search($type)
                        " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
                        AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
                        AND `body` LIKE CONCAT('%',?,'%')",
-                       $since_id, api_user(), $_REQUEST['q']];
+                       $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
                if ($max_id > 0) {
                        $condition[0] .= ' AND `id` <= ?';
                        $condition[] = $max_id;
@@ -1595,7 +1194,7 @@ function api_search($type)
        $statuses = [];
 
        if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
-               $id = Item::fetchByLink($searchTerm, api_user());
+               $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
                if (!$id) {
                        // Public post
                        $id = Item::fetchByLink($searchTerm);
@@ -1606,13 +1205,13 @@ function api_search($type)
                }
        }
 
-       $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
+       $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
        $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
 
        bindComments($data['status']);
 
-       return api_format_data('statuses', $type, $data);
+       return DI::apiResponse()->formatData('statuses', $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -1637,12 +1236,12 @@ api_register_func('api/search', 'api_search', true);
  */
 function api_statuses_home_timeline($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        unset($_REQUEST["user_id"]);
        unset($_GET["user_id"]);
@@ -1663,7 +1262,7 @@ function api_statuses_home_timeline($type)
        $start = max(0, ($page - 1) * $count);
 
        $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
-               api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
+               BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
 
        if ($max_id > 0) {
                $condition[0] .= " AND `id` <= ?";
@@ -1679,7 +1278,7 @@ function api_statuses_home_timeline($type)
        }
 
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-       $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+       $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
        $items = Post::toArray($statuses);
 
@@ -1705,11 +1304,11 @@ function api_statuses_home_timeline($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 
@@ -1731,12 +1330,12 @@ api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline',
  */
 function api_statuses_public_timeline($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        // get last network messages
 
@@ -1760,7 +1359,7 @@ function api_statuses_public_timeline($type)
                }
 
                $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-               $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+               $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
                $r = Post::toArray($statuses);
        } else {
@@ -1777,7 +1376,7 @@ function api_statuses_public_timeline($type)
                }
 
                $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-               $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+               $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
                $r = Post::toArray($statuses);
        }
@@ -1791,11 +1390,11 @@ function api_statuses_public_timeline($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -1814,12 +1413,12 @@ api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline'
  */
 function api_statuses_networkpublic_timeline($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        $since_id        = $_REQUEST['since_id'] ?? 0;
        $max_id          = $_REQUEST['max_id'] ?? 0;
@@ -1839,7 +1438,7 @@ function api_statuses_networkpublic_timeline($type)
        }
 
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-       $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
+       $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
 
        $ret = api_format_items($statuses, $user_info, false, $type);
 
@@ -1850,11 +1449,11 @@ function api_statuses_networkpublic_timeline($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -1875,12 +1474,12 @@ api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpu
  */
 function api_statuses_show($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        // params
        $id = intval(DI::args()->getArgv()[3] ?? 0);
@@ -1894,7 +1493,7 @@ function api_statuses_show($type)
                $id = intval(DI::args()->getArgv()[4] ?? 0);
        }
 
-       Logger::log('API: api_statuses_show: ' . $id);
+       logger::notice('API: api_statuses_show: ' . $id);
 
        $conversation = !empty($_REQUEST['conversation']);
 
@@ -1904,7 +1503,7 @@ function api_statuses_show($type)
                throw new BadRequestException(sprintf("There is no status with the id %d", $id));
        }
 
-       $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
+       $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
        if (!DBA::isResult($item)) {
                throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
        }
@@ -1919,7 +1518,7 @@ function api_statuses_show($type)
                $params = [];
        }
 
-       $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+       $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
        /// @TODO How about copying this to above methods which don't check $r ?
        if (!DBA::isResult($statuses)) {
@@ -1930,10 +1529,10 @@ function api_statuses_show($type)
 
        if ($conversation) {
                $data = ['status' => $ret];
-               return api_format_data("statuses", $type, $data);
+               return DI::apiResponse()->formatData("statuses", $type, $data);
        } else {
                $data = ['status' => $ret[0]];
-               return api_format_data("status", $type, $data);
+               return DI::apiResponse()->formatData("status", $type, $data);
        }
 }
 
@@ -1954,12 +1553,12 @@ api_register_func('api/statuses/show', 'api_statuses_show', true);
  */
 function api_conversation_show($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        // params
        $id       = intval(DI::args()->getArgv()[3]           ?? 0);
@@ -1984,10 +1583,10 @@ function api_conversation_show($type)
        // try to fetch the item for the local user - or the public item, if there is no local one
        $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
        if (!DBA::isResult($item)) {
-               throw new BadRequestException("There is no status with this id.");
+               throw new BadRequestException("There is no status with the id $id.");
        }
 
-       $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
+       $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
        if (!DBA::isResult($parent)) {
                throw new BadRequestException("There is no status with this id.");
        }
@@ -1995,7 +1594,7 @@ function api_conversation_show($type)
        $id = $parent['id'];
 
        $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
-               $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
+               $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
 
        if ($max_id > 0) {
                $condition[0] .= " AND `id` <= ?";
@@ -2003,7 +1602,7 @@ function api_conversation_show($type)
        }
 
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-       $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+       $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
        if (!DBA::isResult($statuses)) {
                throw new BadRequestException("There is no status with id $id.");
@@ -2012,7 +1611,7 @@ function api_conversation_show($type)
        $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
 
        $data = ['status' => $ret];
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -2038,11 +1637,11 @@ function api_statuses_repeat($type)
 
        $a = DI::app();
 
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
 
-       api_get_user($a);
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // params
        $id = intval(DI::args()->getArgv()[3] ?? 0);
@@ -2056,7 +1655,7 @@ function api_statuses_repeat($type)
                $id = intval(DI::args()->getArgv()[4] ?? 0);
        }
 
-       Logger::log('API: api_statuses_repeat: '.$id);
+       logger::notice('API: api_statuses_repeat: ' . $id);
 
        $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
        $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
@@ -2083,7 +1682,7 @@ function api_statuses_repeat($type)
                                $post .= "[/share]";
                        }
                        $_REQUEST['body'] = $post;
-                       $_REQUEST['profile_uid'] = api_user();
+                       $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
                        $_REQUEST['api_source'] = true;
 
                        if (empty($_REQUEST['source'])) {
@@ -2119,13 +1718,11 @@ api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHO
  */
 function api_statuses_destroy($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
 
-       api_get_user($a);
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // params
        $id = intval(DI::args()->getArgv()[3] ?? 0);
@@ -2139,11 +1736,11 @@ function api_statuses_destroy($type)
                $id = intval(DI::args()->getArgv()[4] ?? 0);
        }
 
-       Logger::log('API: api_statuses_destroy: '.$id);
+       logger::notice('API: api_statuses_destroy: ' . $id);
 
        $ret = api_statuses_show($type);
 
-       Item::deleteForUser(['id' => $id], api_user());
+       Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
 
        return $ret;
 }
@@ -2166,12 +1763,12 @@ api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METH
  */
 function api_statuses_mentions($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        unset($_REQUEST["user_id"]);
        unset($_GET["user_id"]);
@@ -2193,11 +1790,14 @@ function api_statuses_mentions($type)
                (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
                AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
 
-       $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
-               Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
-               Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
-               Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
-               api_user(), $since_id];
+       $condition = [
+               GRAVITY_PARENT, GRAVITY_COMMENT,
+               BaseApi::getCurrentUserID(),
+               Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
+               Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
+               Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
+               BaseApi::getCurrentUserID(), $since_id,
+       ];
 
        if ($max_id > 0) {
                $query .= " AND `id` <= ?";
@@ -2207,7 +1807,7 @@ function api_statuses_mentions($type)
        array_unshift($condition, $query);
 
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-       $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+       $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
        $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
 
@@ -2216,11 +1816,11 @@ function api_statuses_mentions($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -2241,14 +1841,14 @@ api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
  */
 function api_statuses_user_timeline($type)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
-       Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
+       Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
 
        $since_id        = $_REQUEST['since_id'] ?? 0;
        $max_id          = $_REQUEST['max_id'] ?? 0;
@@ -2262,7 +1862,7 @@ function api_statuses_user_timeline($type)
        $start = max(0, ($page - 1) * $count);
 
        $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
-               api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
+               BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
 
        if ($user_info['self'] == 1) {
                $condition[0] .= ' AND `wall` ';
@@ -2283,7 +1883,7 @@ function api_statuses_user_timeline($type)
                $condition[] = $max_id;
        }
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-       $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+       $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
        $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
 
@@ -2294,11 +1894,11 @@ function api_statuses_user_timeline($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -2320,12 +1920,12 @@ api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', tr
  */
 function api_favorites_create_destroy($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
 
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
+
        // for versioned api.
        /// @TODO We need a better global soluton
        $action_argv_id = 2;
@@ -2343,7 +1943,7 @@ function api_favorites_create_destroy($type)
                $itemid = intval($_REQUEST['id'] ?? 0);
        }
 
-       $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
+       $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
 
        if (!DBA::isResult($item)) {
                throw new BadRequestException("Invalid item.");
@@ -2366,8 +1966,7 @@ function api_favorites_create_destroy($type)
                throw new InternalServerErrorException("DB error");
        }
 
-
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $rets = api_format_items([$item], $user_info, false, $type);
        $ret = $rets[0];
 
@@ -2376,11 +1975,11 @@ function api_favorites_create_destroy($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("status", $type, $data);
+       return DI::apiResponse()->formatData("status", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -2403,12 +2002,12 @@ function api_favorites($type)
 {
        global $called_api;
 
-       $a = DI::app();
-       $user_info = api_get_user($a);
-
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        $called_api = [];
 
@@ -2428,7 +2027,7 @@ function api_favorites($type)
                $start = max(0, ($page - 1) * $count);
 
                $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
-                       api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
+                       BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
 
                $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
 
@@ -2437,7 +2036,7 @@ function api_favorites($type)
                        $condition[] = $max_id;
                }
 
-               $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+               $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
                $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
        }
@@ -2449,11 +2048,11 @@ function api_favorites($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -2875,8 +2474,6 @@ function api_contactlink_to_array($txt)
  */
 function api_format_items_activities($item, $type = "json")
 {
-       $a = DI::app();
-
        $activities = [
                'like' => [],
                'dislike' => [],
@@ -2894,7 +2491,7 @@ function api_format_items_activities($item, $type = "json")
                //builtin_activity_puller($i, $activities);
 
                // get user data and add it to the array of the activity
-               $user = api_get_user($a, $parent_item['author-id']);
+               $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
                switch ($parent_item['verb']) {
                        case Activity::LIKE:
                                $activities['like'][] = $user;
@@ -2953,7 +2550,7 @@ function api_format_items_activities($item, $type = "json")
  */
 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
 {
-       $a = Friendica\DI::app();
+       $a = DI::app();
 
        $ret = [];
 
@@ -2962,7 +2559,7 @@ function api_format_items($items, $user_info, $filter_user = false, $type = "jso
        }
 
        foreach ((array)$items as $item) {
-               list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
+               [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
 
                // Look if the posts are matching if they should be filtered by user id
                if ($filter_user && ($status_user["id"] != $user_info["id"])) {
@@ -2991,10 +2588,10 @@ function api_format_items($items, $user_info, $filter_user = false, $type = "jso
  */
 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
 {
-       $a = Friendica\DI::app();
+       $a = DI::app();
 
        if (empty($status_user) || empty($author_user) || empty($owner_user)) {
-               list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
+               [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
        }
 
        DI::contentItem()->localize($item);
@@ -3058,7 +2655,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
                if (!empty($announce)) {
                        $retweeted_item = $item;
                        $item = $announce;
-                       $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
+                       $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
                }
        }
 
@@ -3077,7 +2674,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
                        $quoted_status['text'] = $conv_quoted['text'];
                        $quoted_status['statusnet_html'] = $conv_quoted['html'];
                        try {
-                               $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
+                               $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
                        } catch (BadRequestException $e) {
                                // user not found. should be found?
                                /// @todo check if the user should be always found
@@ -3099,7 +2696,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
                unset($retweeted_status['statusnet_conversation_id']);
                $status['user'] = $status['friendica_owner'];
                try {
-                       $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
+                       $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
                } catch (BadRequestException $e) {
                        // user not found. should be found?
                        /// @todo check if the user should be always found
@@ -3147,63 +2744,6 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
        return $status;
 }
 
-/**
- * Returns the remaining number of API requests available to the user before the API limit is reached.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws Exception
- */
-function api_account_rate_limit_status($type)
-{
-       if ($type == "xml") {
-               $hash = [
-                               'remaining-hits' => '150',
-                               '@attributes' => ["type" => "integer"],
-                               'hourly-limit' => '150',
-                               '@attributes2' => ["type" => "integer"],
-                               'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
-                               '@attributes3' => ["type" => "datetime"],
-                               'reset_time_in_seconds' => strtotime('now + 1 hour'),
-                               '@attributes4' => ["type" => "integer"],
-                       ];
-       } else {
-               $hash = [
-                               'reset_time_in_seconds' => strtotime('now + 1 hour'),
-                               'remaining_hits' => '150',
-                               'hourly_limit' => '150',
-                               'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
-                       ];
-       }
-
-       return api_format_data('hash', $type, ['hash' => $hash]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
-
-/**
- * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- */
-function api_help_test($type)
-{
-       if ($type == 'xml') {
-               $ok = "true";
-       } else {
-               $ok = "ok";
-       }
-
-       return api_format_data('ok', $type, ["ok" => $ok]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/help/test', 'api_help_test', false);
-
 /**
  * Returns all lists the user subscribes to.
  *
@@ -3216,7 +2756,7 @@ function api_lists_list($type)
 {
        $ret = [];
        /// @TODO $ret is not filled here?
-       return api_format_data('lists', $type, ["lists_list" => $ret]);
+       return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -3238,14 +2778,13 @@ api_register_func('api/lists/subscriptions', 'api_lists_list', true);
  */
 function api_lists_ownerships($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $uid = $user_info['uid'];
 
        $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
@@ -3266,7 +2805,7 @@ function api_lists_ownerships($type)
                        'mode' => $mode
                ];
        }
-       return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
+       return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -3287,12 +2826,12 @@ api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
  */
 function api_lists_statuses($type)
 {
-       $a = DI::app();
-
-       $user_info = api_get_user($a);
-       if (api_user() === false || $user_info === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        unset($_REQUEST["user_id"]);
        unset($_GET["user_id"]);
@@ -3316,7 +2855,7 @@ function api_lists_statuses($type)
 
        $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
        $gids = array_column($groups, 'contact-id');
-       $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
+       $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
        $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
 
        if ($max_id > 0) {
@@ -3333,7 +2872,7 @@ function api_lists_statuses($type)
        }
 
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-       $statuses = Post::selectForUser(api_user(), [], $condition, $params);
+       $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
 
        $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
 
@@ -3342,11 +2881,11 @@ function api_lists_statuses($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("statuses", $type, $data);
+       return DI::apiResponse()->formatData("statuses", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -3368,11 +2907,7 @@ api_register_func('api/lists/statuses', 'api_lists_statuses', true);
  */
 function api_statuses_f($qtype)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
 
        // pagination
        $count = $_GET['count'] ?? 20;
@@ -3380,7 +2915,7 @@ function api_statuses_f($qtype)
 
        $start = max(0, ($page - 1) * $count);
 
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
                /* this is to stop Hotot to load friends multiple times
@@ -3413,23 +2948,24 @@ function api_statuses_f($qtype)
                $sql_filter = 'AND (NOT `blocked` OR `pending`)';
        }
 
-       $r = q(
-               "SELECT `nurl`
+       // @todo This query most likely can be replaced with a Contact::select...
+       $r = DBA::toArray(DBA::p(
+               "SELECT `id`
                FROM `contact`
-               WHERE `uid` = %d
+               WHERE `uid` = ?
                AND NOT `self`
                $sql_filter
                $sql_extra
                ORDER BY `nick`
-               LIMIT %d, %d",
-               intval(api_user()),
-               intval($start),
-               intval($count)
-       );
+               LIMIT ?, ?",
+               BaseApi::getCurrentUserID(),
+               $start,
+               $count
+       ));
 
        $ret = [];
        foreach ($r as $cid) {
-               $user = api_get_user($a, $cid['nurl']);
+               $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
                // "uid" and "self" are only needed for some internal stuff, so remove it from here
                unset($user["uid"]);
                unset($user["self"]);
@@ -3459,7 +2995,7 @@ function api_statuses_friends($type)
        if ($data === false) {
                return false;
        }
-       return api_format_data("users", $type, $data);
+       return DI::apiResponse()->formatData("users", $type, $data);
 }
 
 /**
@@ -3478,7 +3014,7 @@ function api_statuses_followers($type)
        if ($data === false) {
                return false;
        }
-       return api_format_data("users", $type, $data);
+       return DI::apiResponse()->formatData("users", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -3502,7 +3038,7 @@ function api_blocks_list($type)
        if ($data === false) {
                return false;
        }
-       return api_format_data("users", $type, $data);
+       return DI::apiResponse()->formatData("users", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -3531,116 +3067,56 @@ function api_friendships_incoming($type)
                $ids[] = $user['id'];
        }
 
-       return api_format_data("ids", $type, ['id' => $ids]);
+       return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
 }
 
 /// @TODO move to top of file or somewhere better
 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
 
 /**
- * Returns the instance's configuration information.
+ * Sends a new direct message.
  *
  * @param string $type Return type (atom, rss, xml, json)
  *
  * @return array|string
+ * @throws BadRequestException
+ * @throws ForbiddenException
+ * @throws ImagickException
  * @throws InternalServerErrorException
+ * @throws NotFoundException
+ * @throws UnauthorizedException
+ * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
  */
-function api_statusnet_config($type)
+function api_direct_messages_new($type)
 {
-       $name      = DI::config()->get('config', 'sitename');
-       $server    = DI::baseUrl()->getHostname();
-       $logo      = DI::baseUrl() . '/images/friendica-64.png';
-       $email     = DI::config()->get('config', 'admin_email');
-       $closed    = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
-       $private   = DI::config()->get('system', 'block_public') ? 'true' : 'false';
-       $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
-       $ssl       = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
-       $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
-
-       $config = [
-               'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
-                       'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
-                       'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
-                       'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
-                       'shorturllength' => '30',
-                       'friendica' => [
-                                       'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
-                                       'FRIENDICA_VERSION' => FRIENDICA_VERSION,
-                                       'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
-                                       'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
-                                       ]
-               ],
-       ];
+       if (empty(BaseApi::getCurrentUserID())) {
+               throw new ForbiddenException();
+       }
 
-       return api_format_data('config', $type, ['config' => $config]);
-}
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
-/// @TODO move to top of file or somewhere better
-api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
-api_register_func('api/statusnet/config', 'api_statusnet_config', false);
-
-/**
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- */
-function api_statusnet_version($type)
-{
-       // liar
-       $fake_statusnet_version = "0.9.7";
-
-       return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
-api_register_func('api/statusnet/version', 'api_statusnet_version', false);
-
-/**
- * Sends a new direct message.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws NotFoundException
- * @throws UnauthorizedException
- * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
- */
-function api_direct_messages_new($type)
-{
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       $uid = BaseApi::getCurrentUserID();
+       if (empty($uid)) {
+               throw new ForbiddenException();
+       }
 
        if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
                return;
        }
 
-       $sender = api_get_user($a);
+       $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
 
        $recipient = null;
        if (!empty($_POST['screen_name'])) {
-               $r = q(
-                       "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
-                       intval(api_user()),
-                       DBA::escape($_POST['screen_name'])
-               );
-
-               if (DBA::isResult($r)) {
+               $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
+               if (DBA::isResult($contacts)) {
                        // Selecting the id by priority, friendica first
-                       api_best_nickname($r);
+                       api_best_nickname($contacts);
 
-                       $recipient = api_get_user($a, $r[0]['nurl']);
+                       $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
                }
        } else {
-               $recipient = api_get_user($a, $_POST['user_id']);
+               $recipient = api_get_user($_POST['user_id']);
        }
 
        if (empty($recipient)) {
@@ -3649,13 +3125,9 @@ function api_direct_messages_new($type)
 
        $replyto = '';
        if (!empty($_REQUEST['replyto'])) {
-               $r = q(
-                       'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
-                       intval(api_user()),
-                       intval($_REQUEST['replyto'])
-               );
-               $replyto = $r[0]['parent-uri'];
-               $sub     = $r[0]['title'];
+               $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
+               $replyto = $mail['parent-uri'];
+               $sub     = $mail['title'];
        } else {
                if (!empty($_REQUEST['title'])) {
                        $sub = $_REQUEST['title'];
@@ -3667,10 +3139,10 @@ function api_direct_messages_new($type)
        $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
 
        if ($id > -1) {
-               $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
-               $ret = api_format_messages($r[0], $recipient, $sender);
+               $mail = DBA::selectFirst('mail', [], ['id' => $id]);
+               $ret = api_format_messages($mail, $recipient, $sender);
        } else {
-               $ret = ["error"=>$id];
+               $ret = ["error" => $id];
        }
 
        $data = ['direct_message'=>$ret];
@@ -3679,11 +3151,11 @@ function api_direct_messages_new($type)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $sender);
+                       $data = api_rss_extra($data, $sender);
                        break;
        }
 
-       return api_format_data("direct-messages", $type, $data);
+       return DI::apiResponse()->formatData("direct-messages", $type, $data);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -3703,14 +3175,14 @@ api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, AP
  */
 function api_direct_messages_destroy($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
 
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
+
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        //required
        $id = $_REQUEST['id'] ?? 0;
        // optional
@@ -3722,7 +3194,7 @@ function api_direct_messages_destroy($type)
        // error if no id or parenturi specified (for clients posting parent-uri as well)
        if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
                $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
-               return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
+               return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
        }
 
        // BadRequestException if no id specified (for clients using Twitter API)
@@ -3733,38 +3205,27 @@ function api_direct_messages_destroy($type)
        // add parent-uri to sql command if specified by calling app
        $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
 
-       // get data of the specified message id
-       $r = q(
-               "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
-               intval($uid),
-               intval($id)
-       );
-
        // error message if specified id is not in database
-       if (!DBA::isResult($r)) {
+       if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
                if ($verbose == "true") {
                        $answer = ['result' => 'error', 'message' => 'message id not in database'];
-                       return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
+                       return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
                }
                /// @todo BadRequestException ok for Twitter API clients?
                throw new BadRequestException('message id not in database');
        }
 
        // delete message
-       $result = q(
-               "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
-               intval($uid),
-               intval($id)
-       );
+       $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
 
        if ($verbose == "true") {
                if ($result) {
                        // return success
                        $answer = ['result' => 'ok', 'message' => 'message deleted'];
-                       return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
+                       return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
                } else {
                        $answer = ['result' => 'error', 'message' => 'unknown error'];
-                       return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
+                       return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
                }
        }
        /// @todo return JSON data like Twitter API not yet implemented
@@ -3787,7 +3248,7 @@ api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy',
  */
 function api_friendships_destroy($type)
 {
-       $uid = api_user();
+       $uid = BaseApi::getCurrentUserID();
 
        if ($uid === false) {
                throw new HTTPException\ForbiddenException();
@@ -3826,10 +3287,8 @@ function api_friendships_destroy($type)
                throw new HTTPException\NotFoundException('Not following Contact');
        }
 
-       $dissolve = ($contact['rel'] == Contact::SHARING);
-
        try {
-               $result = Contact::terminateFriendship($owner, $contact, $dissolve);
+               $result = Contact::terminateFriendship($owner, $contact);
 
                if ($result === null) {
                        Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
@@ -3840,7 +3299,7 @@ function api_friendships_destroy($type)
                        throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
                }
        } catch (Exception $e) {
-               Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact, 'dissolve' => $dissolve]);
+               Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
                throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
        }
 
@@ -3851,8 +3310,9 @@ function api_friendships_destroy($type)
        // Set screen_name since Twidere requests it
        $contact['screen_name'] = $contact['nick'];
 
-       return api_format_data('friendships-destroy', $type, ['user' => $contact]);
+       return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
 }
+
 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
 
 /**
@@ -3870,10 +3330,11 @@ api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, AP
  */
 function api_direct_messages_box($type, $box, $verbose)
 {
-       $a = DI::app();
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
+
        // params
        $count = $_GET['count'] ?? 20;
        $page = $_REQUEST['page'] ?? 1;
@@ -3891,10 +3352,8 @@ function api_direct_messages_box($type, $box, $verbose)
        unset($_REQUEST["screen_name"]);
        unset($_GET["screen_name"]);
 
-       $user_info = api_get_user($a);
-       if ($user_info === false) {
-               throw new ForbiddenException();
-       }
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
+
        $profile_url = $user_info["url"];
 
        // pagination
@@ -3923,25 +3382,25 @@ function api_direct_messages_box($type, $box, $verbose)
                $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
        }
 
-       $r = q(
-               "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
-               intval(api_user()),
-               intval($since_id),
-               intval($start),
-               intval($count)
-       );
+       $r = DBA::toArray(DBA::p(
+               "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
+               BaseApi::getCurrentUserID(),
+               $since_id,
+               $start,
+               $count
+       ));
        if ($verbose == "true" && !DBA::isResult($r)) {
                $answer = ['result' => 'error', 'message' => 'no mails available'];
-               return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
+               return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
        }
 
        $ret = [];
        foreach ($r as $item) {
                if ($box == "inbox" || $item['from-url'] != $profile_url) {
                        $recipient = $user_info;
-                       $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+                       $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
                } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
-                       $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+                       $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
                        $sender = $user_info;
                }
 
@@ -3956,11 +3415,11 @@ function api_direct_messages_box($type, $box, $verbose)
                case "atom":
                        break;
                case "rss":
-                       $data = api_rss_extra($a, $data, $user_info);
+                       $data = api_rss_extra($data, $user_info);
                        break;
        }
 
-       return api_format_data("direct-messages", $type, $data);
+       return DI::apiResponse()->formatData("direct-messages", $type, $data);
 }
 
 /**
@@ -4029,95 +3488,6 @@ api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
 
-/**
- * delete a complete photoalbum with all containing photos from database through api
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- */
-function api_fr_photoalbum_delete($type)
-{
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-       // input params
-       $album = $_REQUEST['album'] ?? '';
-
-       // we do not allow calls without album string
-       if ($album == "") {
-               throw new BadRequestException("no albumname specified");
-       }
-       // check if album is existing
-
-       $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
-       if (!DBA::isResult($photos)) {
-               throw new BadRequestException("album not available");
-       }
-
-       $resourceIds = array_column($photos, 'resource-id');
-
-       // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
-       // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
-       $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
-       Item::deleteForUser($condition, api_user());
-
-       // now let's delete all photos from the album
-       $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
-
-       // return success of deletion or error message
-       if ($result) {
-               $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
-               return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
-       } else {
-               throw new InternalServerErrorException("unknown error - deleting from database failed");
-       }
-}
-
-/**
- * update the name of the album for all photos of an album
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- */
-function api_fr_photoalbum_update($type)
-{
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-       // input params
-       $album = $_REQUEST['album'] ?? '';
-       $album_new = $_REQUEST['album_new'] ?? '';
-
-       // we do not allow calls without album string
-       if ($album == "") {
-               throw new BadRequestException("no albumname specified");
-       }
-       if ($album_new == "") {
-               throw new BadRequestException("no new albumname specified");
-       }
-       // check if album is existing
-       if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
-               throw new BadRequestException("album not available");
-       }
-       // now let's update all photos to the albumname
-       $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
-
-       // return success of updating or error message
-       if ($result) {
-               $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
-               return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
-       } else {
-               throw new InternalServerErrorException("unknown error - updating in database failed");
-       }
-}
-
-
 /**
  * list all photos of the authenticated user
  *
@@ -4128,15 +3498,15 @@ function api_fr_photoalbum_update($type)
  */
 function api_fr_photos_list($type)
 {
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
-       $r = q(
+       $r = DBA::toArray(DBA::p(
                "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
                MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
-               WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
-               intval(local_user())
-       );
+               WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
+               local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
+       ));
        $typetoext = [
                'image/jpeg' => 'jpg',
                'image/png' => 'png',
@@ -4163,7 +3533,7 @@ function api_fr_photos_list($type)
                        }
                }
        }
-       return api_format_data("photos", $type, $data);
+       return DI::apiResponse()->formatData("photos", $type, $data);
 }
 
 /**
@@ -4179,7 +3549,7 @@ function api_fr_photos_list($type)
  */
 function api_fr_photo_create_update($type)
 {
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
        // input params
@@ -4214,7 +3584,7 @@ function api_fr_photo_create_update($type)
                $mode = "update";
 
                // check if photo is existing in databasei
-               if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
+               if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
                        throw new BadRequestException("photo not available");
                }
        }
@@ -4231,11 +3601,11 @@ function api_fr_photo_create_update($type)
        // now let's upload the new media in create-mode
        if ($mode == "create") {
                $media = $_FILES['media'];
-               $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
+               $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility);
 
                // return success of updating or error message
                if (!is_null($data)) {
-                       return api_format_data("photo_create", $type, $data);
+                       return DI::apiResponse()->formatData("photo_create", $type, $data);
                } else {
                        throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
                }
@@ -4276,7 +3646,7 @@ function api_fr_photo_create_update($type)
                $result = false;
                if (count($updated_fields) > 0) {
                        $nothingtodo = false;
-                       $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
+                       $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
                } else {
                        $nothingtodo = true;
                }
@@ -4284,20 +3654,20 @@ function api_fr_photo_create_update($type)
                if (!empty($_FILES['media'])) {
                        $nothingtodo = false;
                        $media = $_FILES['media'];
-                       $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
+                       $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
                        if (!is_null($data)) {
-                               return api_format_data("photo_update", $type, $data);
+                               return DI::apiResponse()->formatData("photo_update", $type, $data);
                        }
                }
 
                // return success of updating or error message
                if ($result) {
                        $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
-                       return api_format_data("photo_update", $type, ['$result' => $answer]);
+                       return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
                } else {
                        if ($nothingtodo) {
                                $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
-                               return api_format_data("photo_update", $type, ['$result' => $answer]);
+                               return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
                        }
                        throw new InternalServerErrorException("unknown error - update photo entry in database failed");
                }
@@ -4305,53 +3675,6 @@ function api_fr_photo_create_update($type)
        throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
 }
 
-/**
- * delete a single photo from the database through api
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws InternalServerErrorException
- */
-function api_fr_photo_delete($type)
-{
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-
-       // input params
-       $photo_id = $_REQUEST['photo_id'] ?? null;
-
-       // do several checks on input parameters
-       // we do not allow calls without photo id
-       if ($photo_id == null) {
-               throw new BadRequestException("no photo_id specified");
-       }
-
-       // check if photo is existing in database
-       if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
-               throw new BadRequestException("photo not available");
-       }
-
-       // now we can perform on the deletion of the photo
-       $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
-
-       // return success of deletion or error message
-       if ($result) {
-               // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
-               // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
-               $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
-               Item::deleteForUser($condition, api_user());
-
-               $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
-               return api_format_data("photo_delete", $type, ['$result' => $result]);
-       } else {
-               throw new InternalServerErrorException("unknown error on deleting photo from database table");
-       }
-}
-
-
 /**
  * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
  *
@@ -4364,7 +3687,7 @@ function api_fr_photo_delete($type)
  */
 function api_fr_photo_detail($type)
 {
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
        if (empty($_REQUEST['photo_id'])) {
@@ -4377,7 +3700,7 @@ function api_fr_photo_detail($type)
        // prepare json/xml output with data from database for the requested photo
        $data = prepare_photo_data($type, $scale, $photo_id);
 
-       return api_format_data("photo_detail", $type, $data);
+       return DI::apiResponse()->formatData("photo_detail", $type, $data);
 }
 
 
@@ -4396,7 +3719,7 @@ function api_fr_photo_detail($type)
  */
 function api_account_update_profile_image($type)
 {
-       if (api_user() === false) {
+       if (empty(BaseApi::getCurrentUserID())) {
                throw new ForbiddenException();
        }
        // input params
@@ -4409,7 +3732,7 @@ function api_account_update_profile_image($type)
 
        // check if specified profile id is valid
        if ($profile_id != 0) {
-               $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
+               $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
                // error message if specified profile id is not in database
                if (!DBA::isResult($profile)) {
                        throw new BadRequestException("profile_id not available");
@@ -4427,7 +3750,7 @@ function api_account_update_profile_image($type)
                $media = $_FILES['media'];
        }
        // save new profile image
-       $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
+       $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
 
        // get filetype
        if (is_array($media['type'])) {
@@ -4445,18 +3768,18 @@ function api_account_update_profile_image($type)
 
        // change specified profile or all profiles to the new resource-id
        if ($is_default_profile) {
-               $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
-               Photo::update(['profile' => false], $condition);
+               $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
+               Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
        } else {
                $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
                        'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
-               DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
+               DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
        }
 
-       Contact::updateSelfFromUserID(api_user(), true);
+       Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
 
        // Update global directory in background
-       Profile::publishUpdate(api_user());
+       Profile::publishUpdate(BaseApi::getCurrentUserID());
 
        // output for client
        if ($data) {
@@ -4468,12 +3791,9 @@ function api_account_update_profile_image($type)
 }
 
 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
-api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
-api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
-api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
 
@@ -4491,8 +3811,11 @@ api_register_func('api/account/update_profile_image', 'api_account_update_profil
  */
 function api_account_update_profile($type)
 {
-       $local_user = api_user();
-       $api_user = api_get_user(DI::app());
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
+
+       $local_user = BaseApi::getCurrentUserID();
+
+       $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        if (!empty($_POST['name'])) {
                DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
@@ -4537,7 +3860,7 @@ function check_acl_input($acl_string)
        foreach ($cid_array as $cid) {
                $cid = str_replace("<", "", $cid);
                $cid = str_replace(">", "", $cid);
-               $condition = ['id' => $cid, 'uid' => api_user()];
+               $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
                $contact_not_found |= !DBA::exists('contact', $condition);
        }
        return $contact_not_found;
@@ -4553,7 +3876,7 @@ function check_acl_input($acl_string)
  * @param string  $allow_gid
  * @param string  $deny_gid
  * @param string  $desc
- * @param integer $profile
+ * @param integer $phototype
  * @param boolean $visibility
  * @param string  $photo_id
  * @return array
@@ -4564,7 +3887,7 @@ function check_acl_input($acl_string)
  * @throws NotFoundException
  * @throws UnauthorizedException
  */
-function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
+function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
 {
        $visitor   = 0;
        $src = "";
@@ -4597,11 +3920,9 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
 
        $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
 
-       Logger::log(
+       logger::info(
                "File upload src: " . $src . " - filename: " . $filename .
-               " - size: " . $filesize . " - type: " . $filetype,
-               Logger::DEBUG
-       );
+               " - size: " . $filesize . " - type: " . $filetype);
 
        // check if there was a php upload error
        if ($filesize == 0 && $media['error'] == 1) {
@@ -4627,12 +3948,9 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
 
        // check max length of images on server
        $max_length = DI::config()->get('system', 'max_image_length');
-       if (!$max_length) {
-               $max_length = MAX_IMAGE_LENGTH;
-       }
        if ($max_length > 0) {
                $Image->scaleDown($max_length);
-               Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
+               logger::info("File upload: Scaling picture to new size " . $max_length);
        }
        $width = $Image->getWidth();
        $height = $Image->getHeight();
@@ -4642,57 +3960,57 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
 
        if ($mediatype == "photo") {
                // upload normal image (scales 0, 1, 2)
-               Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
+               logger::info("photo upload: starting new photo upload");
 
-               $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+               $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
                if (!$r) {
-                       Logger::log("photo upload: image upload with scale 0 (original size) failed");
+                       logger::notice("photo upload: image upload with scale 0 (original size) failed");
                }
                if ($width > 640 || $height > 640) {
                        $Image->scaleDown(640);
-                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
                        if (!$r) {
-                               Logger::log("photo upload: image upload with scale 1 (640x640) failed");
+                               logger::notice("photo upload: image upload with scale 1 (640x640) failed");
                        }
                }
 
                if ($width > 320 || $height > 320) {
                        $Image->scaleDown(320);
-                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
                        if (!$r) {
-                               Logger::log("photo upload: image upload with scale 2 (320x320) failed");
+                               logger::notice("photo upload: image upload with scale 2 (320x320) failed");
                        }
                }
-               Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
+               logger::info("photo upload: new photo upload ended");
        } elseif ($mediatype == "profileimage") {
                // upload profile image (scales 4, 5, 6)
-               Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
+               logger::info("photo upload: starting new profile image upload");
 
                if ($width > 300 || $height > 300) {
                        $Image->scaleDown(300);
-                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
                        if (!$r) {
-                               Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
+                               logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
                        }
                }
 
                if ($width > 80 || $height > 80) {
                        $Image->scaleDown(80);
-                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
                        if (!$r) {
-                               Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
+                               logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
                        }
                }
 
                if ($width > 48 || $height > 48) {
                        $Image->scaleDown(48);
-                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
+                       $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
                        if (!$r) {
-                               Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
+                               logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
                        }
                }
                $Image->__destruct();
-               Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
+               logger::info("photo upload: new profile image upload ended");
        }
 
        if (!empty($r)) {
@@ -4721,12 +4039,12 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
 {
        // get data about the api authenticated user
-       $uri = Item::newURI(intval(api_user()));
-       $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
+       $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
+       $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
 
        $arr = [];
        $arr['guid']          = System::createUUID();
-       $arr['uid']           = intval(api_user());
+       $arr['uid']           = intval(BaseApi::getCurrentUserID());
        $arr['uri']           = $uri;
        $arr['type']          = 'photo';
        $arr['wall']          = 1;
@@ -4777,30 +4095,25 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
  */
 function prepare_photo_data($type, $scale, $photo_id)
 {
-       $a = DI::app();
-       $user_info = api_get_user($a);
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
-       if ($user_info === false) {
-               throw new ForbiddenException();
-       }
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
        $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
        $data_sql = ($scale === false ? "" : "data, ");
 
        // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
        // clients needs to convert this in their way for further processing
-       $r = q(
-               "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
+       $r = DBA::toArray(DBA::p(
+               "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
                                        `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
                                        MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
-                       FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
-                              `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
-                              `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
-               $data_sql,
-               intval(local_user()),
-               DBA::escape($photo_id),
-               $scale_sql
-       );
+                       FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
+                                  `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
+                                  `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
+               local_user(),
+               $photo_id
+       ));
 
        $typetoext = [
                'image/jpeg' => 'jpg',
@@ -4841,7 +4154,7 @@ function prepare_photo_data($type, $scale, $photo_id)
        }
 
        // retrieve item element for getting activities (like, dislike etc.) related to photo
-       $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
+       $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
        $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
        if (!DBA::isResult($item)) {
                throw new NotFoundException('Photo-related item not found.');
@@ -4851,9 +4164,9 @@ function prepare_photo_data($type, $scale, $photo_id)
 
        // retrieve comments on photo
        $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
-               $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
+               $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
 
-       $statuses = Post::selectForUser(api_user(), [], $condition);
+       $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
 
        // prepare output of comments
        $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
@@ -5073,38 +4386,28 @@ function api_best_nickname(&$contacts)
  */
 function api_friendica_group_show($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $gid = $_REQUEST['gid'] ?? 0;
        $uid = $user_info['uid'];
 
        // get data of the specified group id or all groups if not specified
        if ($gid != 0) {
-               $r = q(
-                       "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
-                       intval($uid),
-                       intval($gid)
-               );
+               $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
+
                // error message if specified gid is not in database
-               if (!DBA::isResult($r)) {
+               if (!DBA::isResult($groups)) {
                        throw new BadRequestException("gid not available");
                }
        } else {
-               $r = q(
-                       "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
-                       intval($uid)
-               );
+               $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
        }
 
        // loop through all groups and retrieve all members for adding data in the user array
        $grps = [];
-       foreach ($r as $rr) {
+       foreach ($groups as $rr) {
                $members = Contact\Group::getById($rr['id']);
                $users = [];
 
@@ -5112,88 +4415,22 @@ function api_friendica_group_show($type)
                        $user_element = "users";
                        $k = 0;
                        foreach ($members as $member) {
-                               $user = api_get_user($a, $member['nurl']);
+                               $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
                                $users[$k++.":user"] = $user;
                        }
                } else {
                        $user_element = "user";
                        foreach ($members as $member) {
-                               $user = api_get_user($a, $member['nurl']);
+                               $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
                                $users[] = $user;
                        }
                }
                $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
        }
-       return api_format_data("groups", $type, ['group' => $grps]);
+       return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
 }
-api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
 
-
-/**
- * Delete the specified group of the user.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- */
-function api_friendica_group_delete($type)
-{
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-
-       // params
-       $user_info = api_get_user($a);
-       $gid = $_REQUEST['gid'] ?? 0;
-       $name = $_REQUEST['name'] ?? '';
-       $uid = $user_info['uid'];
-
-       // error if no gid specified
-       if ($gid == 0 || $name == "") {
-               throw new BadRequestException('gid or name not specified');
-       }
-
-       // get data of the specified group id
-       $r = q(
-               "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
-               intval($uid),
-               intval($gid)
-       );
-       // error message if specified gid is not in database
-       if (!DBA::isResult($r)) {
-               throw new BadRequestException('gid not available');
-       }
-
-       // get data of the specified group id and group name
-       $rname = q(
-               "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
-               intval($uid),
-               intval($gid),
-               DBA::escape($name)
-       );
-       // error message if specified gid is not in database
-       if (!DBA::isResult($rname)) {
-               throw new BadRequestException('wrong group name');
-       }
-
-       // delete group
-       $ret = Group::removeByName($uid, $name);
-       if ($ret) {
-               // return success
-               $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
-               return api_format_data("group_delete", $type, ['result' => $success]);
-       } else {
-               throw new BadRequestException('other API error');
-       }
-}
-api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
+api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
 
 /**
  * Delete a group.
@@ -5210,14 +4447,10 @@ api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', tr
  */
 function api_lists_destroy($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $gid = $_REQUEST['list_id'] ?? 0;
        $uid = $user_info['uid'];
 
@@ -5241,9 +4474,10 @@ function api_lists_destroy($type)
                        'user' => $user_info
                ];
 
-               return api_format_data("lists", $type, ['lists' => $list]);
+               return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
        }
 }
+
 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
 
 /**
@@ -5263,25 +4497,13 @@ function group_create($name, $uid, $users = [])
                throw new BadRequestException('group name not specified');
        }
 
-       // get data of the specified group name
-       $rname = q(
-               "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
-               intval($uid),
-               DBA::escape($name)
-       );
        // error message if specified group name already exists
-       if (DBA::isResult($rname)) {
+       if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
                throw new BadRequestException('group name already exists');
        }
 
-       // check if specified group name is a deleted group
-       $rname = q(
-               "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
-               intval($uid),
-               DBA::escape($name)
-       );
-       // error message if specified group name already exists
-       if (DBA::isResult($rname)) {
+       // Check if the group needs to be reactivated
+       if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
                $reactivate_group = true;
        }
 
@@ -5298,13 +4520,7 @@ function group_create($name, $uid, $users = [])
        $errorusers = [];
        foreach ($users as $user) {
                $cid = $user['cid'];
-               // check if user really exists as contact
-               $contact = q(
-                       "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
-                       intval($cid),
-                       intval($uid)
-               );
-               if (count($contact)) {
+               if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
                        Group::addMember($gid, $cid);
                } else {
                        $erroraddinguser = true;
@@ -5332,14 +4548,10 @@ function group_create($name, $uid, $users = [])
  */
 function api_friendica_group_create($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $name = $_REQUEST['name'] ?? '';
        $uid = $user_info['uid'];
        $json = json_decode($_POST['json'], true);
@@ -5347,8 +4559,9 @@ function api_friendica_group_create($type)
 
        $success = group_create($name, $uid, $users);
 
-       return api_format_data("group_create", $type, ['result' => $success]);
+       return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
 }
+
 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
 
 /**
@@ -5366,14 +4579,10 @@ api_register_func('api/friendica/group_create', 'api_friendica_group_create', tr
  */
 function api_lists_create($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $name = $_REQUEST['name'] ?? '';
        $uid = $user_info['uid'];
 
@@ -5386,9 +4595,10 @@ function api_lists_create($type)
                        'user' => $user_info
                ];
 
-               return api_format_data("lists", $type, ['lists'=>$grp]);
+               return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
        }
 }
+
 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
 
 /**
@@ -5405,14 +4615,10 @@ api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST)
  */
 function api_friendica_group_update($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $uid = $user_info['uid'];
        $gid = $_REQUEST['gid'] ?? 0;
        $name = $_REQUEST['name'] ?? '';
@@ -5437,7 +4643,8 @@ function api_friendica_group_update($type)
                        $found = ($user['cid'] == $cid ? true : false);
                }
                if (!isset($found) || !$found) {
-                       Group::removeMemberByName($uid, $name, $cid);
+                       $gid = Group::getIdByName($uid, $name);
+                       Group::removeMember($gid, $cid);
                }
        }
 
@@ -5446,14 +4653,8 @@ function api_friendica_group_update($type)
        $errorusers = [];
        foreach ($users as $user) {
                $cid = $user['cid'];
-               // check if user really exists as contact
-               $contact = q(
-                       "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
-                       intval($cid),
-                       intval($uid)
-               );
 
-               if (count($contact)) {
+               if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
                        Group::addMember($gid, $cid);
                } else {
                        $erroraddinguser = true;
@@ -5464,7 +4665,7 @@ function api_friendica_group_update($type)
        // return success message incl. missing users in array
        $status = ($erroraddinguser ? "missing user" : "ok");
        $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
-       return api_format_data("group_update", $type, ['result' => $success]);
+       return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
 }
 
 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
@@ -5484,14 +4685,10 @@ api_register_func('api/friendica/group_update', 'api_friendica_group_update', tr
  */
 function api_lists_update($type)
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $gid = $_REQUEST['list_id'] ?? 0;
        $name = $_REQUEST['name'] ?? '';
        $uid = $user_info['uid'];
@@ -5516,101 +4713,12 @@ function api_lists_update($type)
                        'user' => $user_info
                ];
 
-               return api_format_data("lists", $type, ['lists' => $list]);
+               return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
        }
 }
 
 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
 
-/**
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- */
-function api_friendica_activity($type)
-{
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-       $verb = strtolower(DI::args()->getArgv()[3]);
-       $verb = preg_replace("|\..*$|", "", $verb);
-
-       $id = $_REQUEST['id'] ?? 0;
-
-       $res = Item::performActivity($id, $verb, api_user());
-
-       if ($res) {
-               if ($type == "xml") {
-                       $ok = "true";
-               } else {
-                       $ok = "ok";
-               }
-               return api_format_data('ok', $type, ['ok' => $ok]);
-       } else {
-               throw new BadRequestException('Error adding activity');
-       }
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
-api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
-
-/**
- * Returns notifications
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- *
- * @return string|array
- * @throws ForbiddenException
- * @throws BadRequestException
- * @throws Exception
- */
-function api_friendica_notification($type)
-{
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-       if (DI::args()->getArgc()!==3) {
-               throw new BadRequestException("Invalid argument count");
-       }
-
-       $notifications = DI::notification()->getApiList(local_user());
-
-       if ($type == "xml") {
-               $xmlnotes = false;
-               if (!empty($notifications)) {
-                       foreach ($notifications as $notification) {
-                               $xmlnotes[] = ["@attributes" => $notification->toArray()];
-                       }
-               }
-
-               $result = $xmlnotes;
-       } elseif (count($notifications) > 0) {
-               $result = $notifications->getArrayCopy();
-       } else {
-               $result = false;
-       }
-
-       return api_format_data("notes", $type, ['note' => $result]);
-}
-
 /**
  * Set notification as seen and returns associated item (if possible)
  *
@@ -5626,33 +4734,41 @@ function api_friendica_notification($type)
  */
 function api_friendica_notification_seen($type)
 {
-       $a         = DI::app();
-       $user_info = api_get_user($a);
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
+
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
 
-       if (api_user() === false || $user_info === false) {
-               throw new ForbiddenException();
-       }
        if (DI::args()->getArgc() !== 4) {
-               throw new BadRequestException("Invalid argument count");
+               throw new BadRequestException('Invalid argument count');
        }
 
-       $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
+       $id = intval($_REQUEST['id'] ?? 0);
 
        try {
-               $notify = DI::notify()->getByID($id, api_user());
-               DI::notify()->setSeen(true, $notify);
+               $Notify = DI::notify()->selectOneById($id);
+               if ($Notify->uid !== BaseApi::getCurrentUserID()) {
+                       throw new NotFoundException();
+               }
 
-               if ($notify->otype === Notification\ObjectType::ITEM) {
-                       $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
+               if ($Notify->uriId) {
+                       DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
+               }
+
+               $Notify->setSeen();
+               DI::notify()->save($Notify);
+
+               if ($Notify->otype === Notification\ObjectType::ITEM) {
+                       $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
                        if (DBA::isResult($item)) {
                                // we found the item, return it to the user
                                $ret  = api_format_items([$item], $user_info, false, $type);
                                $data = ['status' => $ret];
-                               return api_format_data("status", $type, $data);
+                               return DI::apiResponse()->formatData('status', $type, $data);
                        }
                        // the item can't be found, but we set the notification as seen, so we count this as a success
                }
-               return api_format_data('result', $type, ['result' => "success"]);
+
+               return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
        } catch (NotFoundException $e) {
                throw new BadRequestException('Invalid argument', $e);
        } catch (Exception $e) {
@@ -5662,58 +4778,6 @@ function api_friendica_notification_seen($type)
 
 /// @TODO move to top of file or somewhere better
 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
-api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
-
-/**
- * update a direct_message to seen state
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array (success result=ok, error result=error with error message)
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- */
-function api_friendica_direct_messages_setseen($type)
-{
-       $a = DI::app();
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-
-       // params
-       $user_info = api_get_user($a);
-       $uid = $user_info['uid'];
-       $id = $_REQUEST['id'] ?? 0;
-
-       // return error if id is zero
-       if ($id == "") {
-               $answer = ['result' => 'error', 'message' => 'message id not specified'];
-               return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
-       }
-
-       // error message if specified id is not in database
-       if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
-               $answer = ['result' => 'error', 'message' => 'message id not in database'];
-               return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
-       }
-
-       // update seen indicator
-       $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
-
-       if ($result) {
-               // return success
-               $answer = ['result' => 'ok', 'message' => 'message set to seen'];
-               return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
-       } else {
-               $answer = ['result' => 'error', 'message' => 'unknown error'];
-               return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
-       }
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
 
 /**
  * search for direct_messages containing a searchstring through api
@@ -5731,29 +4795,25 @@ api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct
  */
 function api_friendica_direct_messages_search($type, $box = "")
 {
-       $a = DI::app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
+       BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
 
        // params
-       $user_info = api_get_user($a);
+       $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
        $searchstring = $_REQUEST['searchstring'] ?? '';
        $uid = $user_info['uid'];
 
        // error if no searchstring specified
        if ($searchstring == "") {
                $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
-               return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
+               return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
        }
 
        // get data for the specified searchstring
-       $r = q(
-               "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
-               intval($uid),
-               DBA::escape('%'.$searchstring.'%')
-       );
+       $r = DBA::toArray(DBA::p(
+               "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
+               $uid,
+               '%'.$searchstring.'%'
+       ));
 
        $profile_url = $user_info["url"];
 
@@ -5767,9 +4827,9 @@ function api_friendica_direct_messages_search($type, $box = "")
                foreach ($r as $item) {
                        if ($box == "inbox" || $item['from-url'] != $profile_url) {
                                $recipient = $user_info;
-                               $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+                               $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
                        } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
-                               $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
+                               $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
                                $sender = $user_info;
                        }
 
@@ -5780,46 +4840,12 @@ function api_friendica_direct_messages_search($type, $box = "")
                $success = ['success' => true, 'search_results' => $ret];
        }
 
-       return api_format_data("direct_message_search", $type, ['$result' => $success]);
+       return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
 }
 
 /// @TODO move to top of file or somewhere better
 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
 
-/**
- * Returns a list of saved searches.
- *
- * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
- *
- * @param  string $type Return format: json or xml
- *
- * @return string|array
- * @throws Exception
- */
-function api_saved_searches_list($type)
-{
-       $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
-
-       $result = [];
-       while ($term = DBA::fetch($terms)) {
-               $result[] = [
-                       'created_at' => api_date(time()),
-                       'id' => intval($term['id']),
-                       'id_str' => $term['id'],
-                       'name' => $term['term'],
-                       'position' => null,
-                       'query' => $term['term']
-               ];
-       }
-
-       DBA::close($terms);
-
-       return api_format_data("terms", $type, ['terms' => $result]);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
-
 /*
  * Number of comments
  *