]> git.mxchange.org Git - friendica.git/blobdiff - include/api.php
Remove orphaned avatar photo entries
[friendica.git] / include / api.php
index a6a6b505004dffc338262b5fe0b88d3671d5587c..92d35c001ec1b1236e436fa761cfb8b76e73eed5 100644 (file)
@@ -1,5 +1,22 @@
 <?php
 /**
+ * @copyright Copyright (C) 2020, Friendica
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ *
  * Friendica implementation of statusnet/twitter API
  *
  * @file include/api.php
 
 use Friendica\App;
 use Friendica\Content\ContactSelector;
-use Friendica\Content\Feature;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\HTML;
-use Friendica\Core\Config;
 use Friendica\Core\Hook;
-use Friendica\Core\L10n;
 use Friendica\Core\Logger;
-use Friendica\Core\PConfig;
 use Friendica\Core\Protocol;
 use Friendica\Core\Session;
 use Friendica\Core\System;
@@ -26,10 +39,12 @@ use Friendica\Model\Contact;
 use Friendica\Model\Group;
 use Friendica\Model\Item;
 use Friendica\Model\Mail;
+use Friendica\Model\Notify;
 use Friendica\Model\Photo;
-use Friendica\Model\Profile;
 use Friendica\Model\User;
-use Friendica\Network\FKOAuth1;
+use Friendica\Model\UserItem;
+use Friendica\Model\Verb;
+use Friendica\Security\FKOAuth1;
 use Friendica\Network\HTTPException;
 use Friendica\Network\HTTPException\BadRequestException;
 use Friendica\Network\HTTPException\ExpectationFailedException;
@@ -43,6 +58,8 @@ use Friendica\Network\HTTPException\UnauthorizedException;
 use Friendica\Object\Image;
 use Friendica\Protocol\Activity;
 use Friendica\Protocol\Diaspora;
+use Friendica\Security\OAuth1\OAuthRequest;
+use Friendica\Security\OAuth1\OAuthUtil;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Images;
 use Friendica\Util\Network;
@@ -50,7 +67,6 @@ use Friendica\Util\Proxy as ProxyUtils;
 use Friendica\Util\Strings;
 use Friendica\Util\XML;
 
-require_once __DIR__ . '/../mod/share.php';
 require_once __DIR__ . '/../mod/item.php';
 require_once __DIR__ . '/../mod/wall_upload.php';
 
@@ -65,11 +81,11 @@ $API = [];
 $called_api = [];
 
 /**
+ * Auth API user
+ *
  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
  * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
  * into a page, and visitors will post something without noticing it).
- *
- * @brief Auth API user
  */
 function api_user()
 {
@@ -81,13 +97,13 @@ function api_user()
 }
 
 /**
+ * Get source name from API client
+ *
  * Clients can send 'source' parameter to be show in post metadata
  * as "sent via <source>".
  * Some clients doesn't send a source param, we support ones we know
  * (only Twidere, atm)
  *
- * @brief Get source name from API client
- *
  * @return string
  *        Client source name, default to "api" if unset/unknown
  * @throws Exception
@@ -113,7 +129,7 @@ function api_source()
 }
 
 /**
- * @brief Format date for API
+ * Format date for API
  *
  * @param string $str Source date, as UTC
  * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
@@ -128,8 +144,6 @@ function api_date($str)
 /**
  * Register a function to be the endpoint for defined API path.
  *
- * @brief Register API endpoint
- *
  * @param string $path   API URL path, relative to DI::baseUrl()
  * @param string $func   Function name to call on path request
  * @param bool   $auth   API need logged user
@@ -161,8 +175,6 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY
  * Log in user via OAuth1 or Simple HTTP Auth.
  * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
  *
- * @brief Login API user
- *
  * @param App $a App
  * @throws ForbiddenException
  * @throws InternalServerErrorException
@@ -176,23 +188,6 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY
  */
 function api_login(App $a)
 {
-       $oauth1 = new FKOAuth1();
-       // login with oauth
-       try {
-               $request = OAuthRequest::from_request();
-               list($consumer, $token) = $oauth1->verify_request($request);
-               if (!is_null($token)) {
-                       $oauth1->loginUser($token->uid);
-                       Session::set('allow_api', true);
-                       return;
-               }
-               echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
-               var_dump($consumer, $token);
-               die();
-       } catch (Exception $e) {
-               Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
-       }
-
        // workaround for HTTP-auth in CGI mode
        if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
                $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
@@ -204,6 +199,24 @@ function api_login(App $a)
        }
 
        if (empty($_SERVER['PHP_AUTH_USER'])) {
+               // Try OAuth when no user is provided
+               $oauth1 = new FKOAuth1();
+               // login with oauth
+               try {
+                       $request = OAuthRequest::from_request();
+                       list($consumer, $token) = $oauth1->verify_request($request);
+                       if (!is_null($token)) {
+                               $oauth1->loginUser($token->uid);
+                               Session::set('allow_api', true);
+                               return;
+                       }
+                       echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
+                       var_dump($consumer, $token);
+                       die();
+               } catch (Exception $e) {
+                       Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
+               }
+
                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");
@@ -252,7 +265,10 @@ function api_login(App $a)
                throw new UnauthorizedException("This API requires login");
        }
 
-       DI::auth()->setForUser($a, $record);
+       // 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;
 
@@ -260,12 +276,12 @@ function api_login(App $a)
 }
 
 /**
+ * Check HTTP method of called API
+ *
  * API endpoints can define which HTTP method to accept when called.
  * This function check the current HTTP method agains endpoint
  * registered method.
  *
- * @brief Check HTTP method of called API
- *
  * @param string $method Required methods, uppercase, separated by comma
  * @return bool
  */
@@ -278,9 +294,9 @@ function api_check_method($method)
 }
 
 /**
- * Authenticate user, call registered API function, set HTTP headers
+ * Main API entry point
  *
- * @brief Main API entry point
+ * Authenticate user, call registered API function, set HTTP headers
  *
  * @param App $a App
  * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
@@ -296,42 +312,40 @@ function api_call(App $a, App\Arguments $args = null)
        }
 
        $type = "json";
-       if (strpos($args->getQueryString(), ".xml") > 0) {
+       if (strpos($args->getCommand(), ".xml") > 0) {
                $type = "xml";
        }
-       if (strpos($args->getQueryString(), ".json") > 0) {
+       if (strpos($args->getCommand(), ".json") > 0) {
                $type = "json";
        }
-       if (strpos($args->getQueryString(), ".rss") > 0) {
+       if (strpos($args->getCommand(), ".rss") > 0) {
                $type = "rss";
        }
-       if (strpos($args->getQueryString(), ".atom") > 0) {
+       if (strpos($args->getCommand(), ".atom") > 0) {
                $type = "atom";
        }
 
        try {
                foreach ($API as $p => $info) {
-                       if (strpos($args->getQueryString(), $p) === 0) {
+                       if (strpos($args->getCommand(), $p) === 0) {
                                if (!api_check_method($info['method'])) {
                                        throw new MethodNotAllowedException();
                                }
 
                                $called_api = explode("/", $p);
-                               //unset($_SERVER['PHP_AUTH_USER']);
 
-                               /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
                                if (!empty($info['auth']) && api_user() === false) {
                                        api_login($a);
+                                       Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
                                }
 
-                               Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
                                Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
 
                                $stamp =  microtime(true);
                                $return = call_user_func($info['func'], $type);
                                $duration = floatval(microtime(true) - $stamp);
 
-                               Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
+                               Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
 
                                DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
 
@@ -371,7 +385,7 @@ 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 NotImplementedException();
+               throw new NotFoundException();
        } catch (HTTPException $e) {
                header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
                return api_error($type, $e, $args);
@@ -379,7 +393,7 @@ function api_call(App $a, App\Arguments $args = null)
 }
 
 /**
- * @brief Format API error string
+ * Format API error string
  *
  * @param string $type Return type (xml, json, rss, as)
  * @param object $e    HTTPException Error object
@@ -417,7 +431,7 @@ function api_error($type, $e, App\Arguments $args)
 }
 
 /**
- * @brief Set values for RSS template
+ * Set values for RSS template
  *
  * @param App   $a
  * @param array $arr       Array to be passed to template
@@ -451,7 +465,7 @@ function api_rss_extra(App $a, $arr, $user_info)
 
 
 /**
- * @brief Unique contact to contact url.
+ * Unique contact to contact url.
  *
  * @param int $id Contact id
  * @return bool|string
@@ -470,7 +484,7 @@ function api_unique_id_to_nurl($id)
 }
 
 /**
- * @brief Get user info array.
+ * Get user info array.
  *
  * @param App        $a          App
  * @param int|string $contact_id Contact ID or URL
@@ -614,7 +628,7 @@ function api_get_user(App $a, $contact_id = null)
                                '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"]),
+                               'description' => BBCode::toPlaintext($contact["about"] ?? ''),
                                'profile_image_url' => $contact["micro"],
                                'profile_image_url_https' => $contact["micro"],
                                'profile_image_url_profile_size' => $contact["thumb"],
@@ -641,8 +655,8 @@ function api_get_user(App $a, $contact_id = null)
                                'notifications' => false,
                                'statusnet_profile_url' => $contact["url"],
                                'uid' => 0,
-                               'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
-                               'pid' => Contact::getIdForURL($contact["url"], 0, true),
+                               'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
+                               'pid' => Contact::getIdForURL($contact["url"], 0, false),
                                'self' => 0,
                                'network' => $contact["network"],
                        ];
@@ -666,7 +680,7 @@ function api_get_user(App $a, $contact_id = null)
        $countfollowers = 0;
        $starred = 0;
 
-       $pcontact_id  = Contact::getIdForURL($uinfo[0]['url'], 0, true);
+       $pcontact_id  = Contact::getIdForURL($uinfo[0]['url'], 0, false);
 
        if (!empty($profile['about'])) {
                $description = $profile['about'];
@@ -688,7 +702,7 @@ function api_get_user(App $a, $contact_id = null)
                '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),
+               '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"],
@@ -718,7 +732,7 @@ function api_get_user(App $a, $contact_id = null)
                'statusnet_profile_url' => $uinfo[0]['url'],
                'uid' => intval($uinfo[0]['uid']),
                'cid' => intval($uinfo[0]['cid']),
-               'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
+               'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
                'self' => $uinfo[0]['self'],
                'network' => $uinfo[0]['network'],
        ];
@@ -727,7 +741,7 @@ function api_get_user(App $a, $contact_id = null)
        if ($ret['self']) {
                $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
                if ($theme_info['theme'] === 'frio') {
-                       $schema = PConfig::get($ret['uid'], 'frio', 'schema');
+                       $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
 
                        if ($schema && ($schema != '---')) {
                                if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
@@ -735,9 +749,9 @@ function api_get_user(App $a, $contact_id = null)
                                        require_once $schemefile;
                                }
                        } else {
-                               $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
-                               $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
-                               $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
+                               $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";
@@ -759,7 +773,7 @@ function api_get_user(App $a, $contact_id = null)
 }
 
 /**
- * @brief return api-formatted array for item's author and owner
+ * return api-formatted array for item's author and owner
  *
  * @param App   $a    App
  * @param array $item item from db
@@ -775,7 +789,7 @@ function api_item_get_user(App $a, $item)
 
        $author_user = $status_user;
 
-       $status_user["protected"] = $item['private'] ?? 0;
+       $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);
@@ -787,7 +801,7 @@ function api_item_get_user(App $a, $item)
 }
 
 /**
- * @brief walks recursively through an array with the possibility to change value and key
+ * 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
@@ -815,7 +829,7 @@ function api_walk_recursive(array &$array, callable $callback)
 }
 
 /**
- * @brief Callback function to transform the array in an array that can be transformed in a XML file
+ * 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
@@ -841,7 +855,7 @@ function api_reformat_xml(&$item, &$key)
 }
 
 /**
- * @brief Creates the XML from a JSON style array
+ * Creates the XML from a JSON style array
  *
  * @param array  $data         JSON style array
  * @param string $root_element Name of the root element
@@ -886,7 +900,7 @@ function api_create_xml(array $data, $root_element)
 }
 
 /**
- * @brief Formats the data according to the data type
+ * 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)
@@ -930,7 +944,7 @@ function api_format_data($root_element, $type, $data)
  */
 function api_account_verify_credentials($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -998,7 +1012,7 @@ function requestdata($k)
  */
 function api_statuses_mediap($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                Logger::log('api_statuses_update: no user');
@@ -1052,7 +1066,7 @@ api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD
  */
 function api_statuses_update($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                Logger::log('api_statuses_update: no user');
@@ -1101,7 +1115,7 @@ function api_statuses_update($type)
 
        if (!$parent) {
                // Check for throttling (maximum posts per day, week and month)
-               $throttle_day = Config::get('system', 'throttle_limit_day');
+               $throttle_day = DI::config()->get('system', 'throttle_limit_day');
                if ($throttle_day > 0) {
                        $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
 
@@ -1110,12 +1124,12 @@ function api_statuses_update($type)
 
                        if ($posts_day > $throttle_day) {
                                Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
-                               // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
-                               throw new TooManyRequestsException(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));
+                               // 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));
                        }
                }
 
-               $throttle_week = Config::get('system', 'throttle_limit_week');
+               $throttle_week = DI::config()->get('system', 'throttle_limit_week');
                if ($throttle_week > 0) {
                        $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
 
@@ -1124,12 +1138,12 @@ function api_statuses_update($type)
 
                        if ($posts_week > $throttle_week) {
                                Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
-                               // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
-                               throw new TooManyRequestsException(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));
+                               // 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));
                        }
                }
 
-               $throttle_month = Config::get('system', 'throttle_limit_month');
+               $throttle_month = DI::config()->get('system', 'throttle_limit_month');
                if ($throttle_month > 0) {
                        $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
 
@@ -1138,8 +1152,8 @@ function api_statuses_update($type)
 
                        if ($posts_month > $throttle_month) {
                                Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
-                               // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
-                               throw new TooManyRequestsException(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));
+                               // 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));
                        }
                }
        }
@@ -1202,7 +1216,7 @@ api_register_func('api/statuses/update_with_media', 'api_statuses_update', true,
  */
 function api_media_upload()
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                Logger::log('no user');
@@ -1231,7 +1245,7 @@ function api_media_upload()
                                "image_type" => $media["type"],
                                "friendica_preview_url" => $media["preview"]];
 
-       Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
+       Logger::info('Media uploaded', ['return' => $returndata]);
 
        return ["media" => $returndata];
 }
@@ -1257,7 +1271,7 @@ api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST)
  */
 function api_media_metadata_create($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                Logger::info('no user');
@@ -1301,7 +1315,7 @@ api_register_func('api/media/metadata/create', 'api_media_metadata_create', true
 /**
  * @param string $type    Return format (atom, rss, xml, json)
  * @param int    $item_id
- * @return string
+ * @return array|string
  * @throws Exception
  */
 function api_status_show($type, $item_id)
@@ -1334,7 +1348,7 @@ function api_get_last_status($ownerId, $uid)
                'author-id'=> $ownerId,
                'uid'      => $uid,
                'gravity'  => [GRAVITY_PARENT, GRAVITY_COMMENT],
-               'private'  => false
+               'private'  => [Item::PUBLIC, Item::UNLISTED]
        ];
 
        $item = api_get_item($condition);
@@ -1404,7 +1418,7 @@ api_register_func('api/externalprofile/show', 'api_users_show');
  */
 function api_users_search($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        $userlist = [];
 
@@ -1466,7 +1480,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(get_app(), $id);
+                               $users[] = api_get_user(DI::app(), $id);
                        }
                }
        }
@@ -1497,7 +1511,7 @@ api_register_func('api/users/lookup', 'api_users_lookup', true);
  */
 function api_search($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -1519,7 +1533,7 @@ function api_search($type)
        } elseif (!empty($_REQUEST['count'])) {
                $count = $_REQUEST['count'];
        }
-       
+
        $since_id = $_REQUEST['since_id'] ?? 0;
        $max_id = $_REQUEST['max_id'] ?? 0;
        $page = $_REQUEST['page'] ?? 1;
@@ -1529,34 +1543,27 @@ function api_search($type)
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
        if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
                $searchTerm = $matches[1];
-               $condition = ["`oid` > ?
-                       AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) 
-                       AND `otype` = ? AND `type` = ? AND `term` = ?",
-                       $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
-               if ($max_id > 0) {
-                       $condition[0] .= ' AND `oid` <= ?';
-                       $condition[] = $max_id;
+               $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
+               $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
+               $uriids = [];
+               while ($tag = DBA::fetch($tags)) {
+                       $uriids[] = $tag['uri-id'];
                }
-               $terms = DBA::select('term', ['oid'], $condition, []);
-               $itemIds = [];
-               while ($term = DBA::fetch($terms)) {
-                       $itemIds[] = $term['oid'];
-               }
-               DBA::close($terms);
+               DBA::close($tags);
 
-               if (empty($itemIds)) {
+               if (empty($uriids)) {
                        return api_format_data('statuses', $type, $data);
                }
 
-               $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
+               $condition = ['uri-id' => $uriids];
                if ($exclude_replies) {
-                       $preCondition[] = '`id` = `parent`';
+                       $condition['gravity'] = GRAVITY_PARENT;
                }
 
-               $condition = [implode(' AND ', $preCondition)];
+               $params['group_by'] = ['uri-id'];
        } else {
-               $condition = ["`id` > ? 
-                       " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
+               $condition = ["`id` > ?
+                       " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
                        AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
                        AND `body` LIKE CONCAT('%',?,'%')",
                        $since_id, api_user(), $_REQUEST['q']];
@@ -1611,7 +1618,7 @@ api_register_func('api/search', 'api_search', true);
  */
 function api_statuses_home_timeline($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -1644,7 +1651,8 @@ function api_statuses_home_timeline($type)
                $condition[] = $max_id;
        }
        if ($exclude_replies) {
-               $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
+               $condition[0] .= ' AND `item`.`gravity` = ?';
+               $condition[] = GRAVITY_PARENT;
        }
        if ($conversation_id > 0) {
                $condition[0] .= " AND `item`.`parent` = ?";
@@ -1704,7 +1712,7 @@ api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline',
  */
 function api_statuses_public_timeline($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -1724,8 +1732,8 @@ function api_statuses_public_timeline($type)
        $start = max(0, ($page - 1) * $count);
 
        if ($exclude_replies && !$conversation_id) {
-               $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
-                       GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
+               $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`",
+                       GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
 
                if ($max_id > 0) {
                        $condition[0] .= " AND `thread`.`iid` <= ?";
@@ -1737,8 +1745,8 @@ function api_statuses_public_timeline($type)
 
                $r = Item::inArray($statuses);
        } else {
-               $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
-                       GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
+               $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`",
+                       GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
 
                if ($max_id > 0) {
                        $condition[0] .= " AND `item`.`id` <= ?";
@@ -1777,8 +1785,6 @@ api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline'
 /**
  * Returns the most recent statuses posted by users this node knows about.
  *
- * @brief Returns the list of public federated posts this node knows about
- *
  * @param string $type Return format: json, xml, atom, rss
  * @return array|string
  * @throws BadRequestException
@@ -1789,7 +1795,7 @@ api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline'
  */
 function api_statuses_networkpublic_timeline($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -1805,8 +1811,8 @@ function api_statuses_networkpublic_timeline($type)
 
        $start = max(0, ($page - 1) * $count);
 
-       $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
-               GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
+       $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?",
+               GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
 
        if ($max_id > 0) {
                $condition[0] .= " AND `thread`.`iid` <= ?";
@@ -1850,7 +1856,7 @@ api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpu
  */
 function api_statuses_show($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -1929,7 +1935,7 @@ api_register_func('api/statuses/show', 'api_statuses_show', true);
  */
 function api_conversation_show($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -2011,7 +2017,7 @@ function api_statuses_repeat($type)
 {
        global $called_api;
 
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -2033,34 +2039,40 @@ function api_statuses_repeat($type)
 
        Logger::log('API: api_statuses_repeat: '.$id);
 
-       $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
-       $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
+       $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
+       $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
 
        if (DBA::isResult($item) && $item['body'] != "") {
-               if (strpos($item['body'], "[/share]") !== false) {
-                       $pos = strpos($item['body'], "[share");
-                       $post = substr($item['body'], $pos);
+               if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
+                       if (!Item::performActivity($id, 'announce', local_user())) {
+                               throw new InternalServerErrorException();
+                       }
+               
+                       $item_id = $id;
                } else {
-                       $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
+                       if (strpos($item['body'], "[/share]") !== false) {
+                               $pos = strpos($item['body'], "[share");
+                               $post = substr($item['body'], $pos);
+                       } else {
+                               $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
+
+                               if (!empty($item['title'])) {
+                                       $post .= '[h3]' . $item['title'] . "[/h3]\n";
+                               }
 
-                       if (!empty($item['title'])) {
-                               $post .= '[h3]' . $item['title'] . "[/h3]\n";
+                               $post .= $item['body'];
+                               $post .= "[/share]";
                        }
+                       $_REQUEST['body'] = $post;
+                       $_REQUEST['profile_uid'] = api_user();
+                       $_REQUEST['api_source'] = true;
 
-                       $post .= $item['body'];
-                       $post .= "[/share]";
-               }
-               $_REQUEST['body'] = $post;
-               $_REQUEST['tag'] = $item['tag'];
-               $_REQUEST['attach'] = $item['attach'];
-               $_REQUEST['profile_uid'] = api_user();
-               $_REQUEST['api_source'] = true;
-
-               if (empty($_REQUEST['source'])) {
-                       $_REQUEST["source"] = api_source();
-               }
+                       if (empty($_REQUEST['source'])) {
+                               $_REQUEST["source"] = api_source();
+                       }
 
-               $item_id = item_post($a);
+                       $item_id = item_post($a);
+               }
        } else {
                throw new ForbiddenException();
        }
@@ -2088,7 +2100,7 @@ api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHO
  */
 function api_statuses_destroy($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -2135,7 +2147,7 @@ api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METH
  */
 function api_statuses_mentions($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -2151,24 +2163,42 @@ function api_statuses_mentions($type)
        // get last network messages
 
        // params
-       $since_id = $_REQUEST['since_id'] ?? 0;
-       $max_id   = $_REQUEST['max_id']   ?? 0;
-       $count    = $_REQUEST['count']    ?? 20;
-       $page     = $_REQUEST['page']     ?? 1;
+       $since_id = intval($_REQUEST['since_id'] ?? 0);
+       $max_id   = intval($_REQUEST['max_id']   ?? 0);
+       $count    = intval($_REQUEST['count']    ?? 20);
+       $page     = intval($_REQUEST['page']     ?? 1);
 
        $start = max(0, ($page - 1) * $count);
 
-       $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ? AND `mention`
-               AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND NOT `thread`.`ignored`)",
-               api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
+       $query = "SELECT `item`.`id` FROM `user-item`
+               INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
+               WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
+                       `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
+                       AND `user-item`.`iid` > ?";
+       $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
+               UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
+               UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
+               UserItem::NOTIF_DIRECT_THREAD_COMMENT,
+               $since_id];
 
        if ($max_id > 0) {
-               $condition[0] .= " AND `item`.`id` <= ?";
+               $query .= " AND `item`.`id` <= ?";
                $condition[] = $max_id;
        }
 
+       $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
+       $condition[] = $start;
+       $condition[] = $count;
+
+       $useritems = DBA::p($query, $condition);
+       $itemids = [];
+       while ($useritem = DBA::fetch($useritems)) {
+               $itemids[] = $useritem['id'];
+       }
+       DBA::close($useritems);
+
        $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
-       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
+       $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
 
        $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
 
@@ -2191,8 +2221,6 @@ api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
 /**
  * Returns the most recent statuses posted by the user.
  *
- * @brief Returns a user's public timeline
- *
  * @param string $type Either "json" or "xml"
  * @return string|array
  * @throws BadRequestException
@@ -2204,19 +2232,14 @@ api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
  */
 function api_statuses_user_timeline($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
-       Logger::log(
-               "api_statuses_user_timeline: api_user: ". api_user() .
-                       "\nuser_info: ".print_r($user_info, true) .
-                       "\n_REQUEST:  ".print_r($_REQUEST, true),
-               Logger::DEBUG
-       );
+       Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
 
        $since_id        = $_REQUEST['since_id'] ?? 0;
        $max_id          = $_REQUEST['max_id'] ?? 0;
@@ -2237,7 +2260,8 @@ function api_statuses_user_timeline($type)
        }
 
        if ($exclude_replies) {
-               $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
+               $condition[0] .= ' AND `item`.`gravity` = ?';
+               $condition[] = GRAVITY_PARENT;
        }
 
        if ($conversation_id > 0) {
@@ -2288,7 +2312,7 @@ api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', tr
  */
 function api_favorites_create_destroy($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -2371,7 +2395,7 @@ function api_favorites($type)
 {
        global $called_api;
 
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
@@ -2474,10 +2498,10 @@ function api_format_messages($item, $recipient, $sender)
                if ($_GET['getText'] == 'html') {
                        $ret['text'] = BBCode::convert($item['body'], false);
                } elseif ($_GET['getText'] == 'plain') {
-                       $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
+                       $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
                }
        } else {
-               $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
+               $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
        }
        if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
                unset($ret['sender']);
@@ -2503,7 +2527,7 @@ function api_convert_item($item)
        $attachments = api_get_attachments($body);
 
        // Workaround for ostatus messages where the title is identically to the body
-       $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
+       $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
        $statusbody = trim(HTML::toPlaintext($html, 0));
 
        // handle data: images
@@ -2730,7 +2754,7 @@ function api_get_entitities(&$text, $bbcode)
                        if ($image) {
                                // If image cache is activated, then use the following sizes:
                                // thumb  (150), small (340), medium (600) and large (1024)
-                               if (!Config::get("system", "proxy_disabled")) {
+                               if (!DI::config()->get("system", "proxy_disabled")) {
                                        $media_url = ProxyUtils::proxifyUrl($url);
 
                                        $sizes = [];
@@ -2794,7 +2818,7 @@ function api_format_items_embeded_images($item, $text)
 }
 
 /**
- * @brief return <a href='url'>name</a> as array
+ * return <a href='url'>name</a> as array
  *
  * @param string $txt text
  * @return array
@@ -2821,7 +2845,7 @@ function api_contactlink_to_array($txt)
 
 
 /**
- * @brief return likes, dislikes and attend status for item
+ * return likes, dislikes and attend status for item
  *
  * @param array  $item array
  * @param string $type Return type (atom, rss, xml, json)
@@ -2836,7 +2860,7 @@ function api_contactlink_to_array($txt)
  */
 function api_format_items_activities($item, $type = "json")
 {
-       $a = \get_app();
+       $a = DI::app();
 
        $activities = [
                'like' => [],
@@ -2899,62 +2923,8 @@ function api_format_items_activities($item, $type = "json")
        return $activities;
 }
 
-
-/**
- * @brief return data from profiles
- *
- * @param array $profile_row array containing data from db table 'profile'
- * @return array
- * @throws InternalServerErrorException
- */
-function api_format_items_profiles($profile_row)
-{
-       $profile = [
-               'profile_id'       => $profile_row['id'],
-               'profile_name'     => $profile_row['profile-name'],
-               'is_default'       => $profile_row['is-default'] ? true : false,
-               'hide_friends'     => $profile_row['hide-friends'] ? true : false,
-               'profile_photo'    => $profile_row['photo'],
-               'profile_thumb'    => $profile_row['thumb'],
-               'publish'          => $profile_row['publish'] ? true : false,
-               'net_publish'      => $profile_row['net-publish'] ? true : false,
-               'description'      => $profile_row['pdesc'],
-               'date_of_birth'    => $profile_row['dob'],
-               'address'          => $profile_row['address'],
-               'city'             => $profile_row['locality'],
-               'region'           => $profile_row['region'],
-               'postal_code'      => $profile_row['postal-code'],
-               'country'          => $profile_row['country-name'],
-               'hometown'         => $profile_row['hometown'],
-               'gender'           => $profile_row['gender'],
-               'marital'          => $profile_row['marital'],
-               'marital_with'     => $profile_row['with'],
-               'marital_since'    => $profile_row['howlong'],
-               'sexual'           => $profile_row['sexual'],
-               'politic'          => $profile_row['politic'],
-               'religion'         => $profile_row['religion'],
-               'public_keywords'  => $profile_row['pub_keywords'],
-               'private_keywords' => $profile_row['prv_keywords'],
-               'likes'            => BBCode::convert(api_clean_plain_items($profile_row['likes'])    , false, 2),
-               'dislikes'         => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
-               'about'            => BBCode::convert(api_clean_plain_items($profile_row['about'])    , false, 2),
-               'music'            => BBCode::convert(api_clean_plain_items($profile_row['music'])    , false, 2),
-               'book'             => BBCode::convert(api_clean_plain_items($profile_row['book'])     , false, 2),
-               'tv'               => BBCode::convert(api_clean_plain_items($profile_row['tv'])       , false, 2),
-               'film'             => BBCode::convert(api_clean_plain_items($profile_row['film'])     , false, 2),
-               'interest'         => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
-               'romance'          => BBCode::convert(api_clean_plain_items($profile_row['romance'])  , false, 2),
-               'work'             => BBCode::convert(api_clean_plain_items($profile_row['work'])     , false, 2),
-               'education'        => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
-               'social_networks'  => BBCode::convert(api_clean_plain_items($profile_row['contact'])  , false, 2),
-               'homepage'         => $profile_row['homepage'],
-               'users'            => null
-       ];
-       return $profile;
-}
-
 /**
- * @brief format items to be returned by api
+ * format items to be returned by api
  *
  * @param array  $items       array of items
  * @param array  $user_info
@@ -3037,7 +3007,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
                'user' =>  $status_user,
                'friendica_author' => $author_user,
                'friendica_owner' => $owner_user,
-               'friendica_private' => $item['private'] == 1,
+               'friendica_private' => $item['private'] == Item::PRIVATE,
                //'entities' => NULL,
                'statusnet_html' => $converted["html"],
                'statusnet_conversation_id' => $item['parent'],
@@ -3064,7 +3034,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
        $retweeted_item = [];
        $quoted_item = [];
 
-       if ($item["id"] == $item["parent"]) {
+       if ($item['gravity'] == GRAVITY_PARENT) {
                $body = $item['body'];
                $retweeted_item = api_share_as_retweet($item);
                if ($body != $item['body']) {
@@ -3257,7 +3227,7 @@ api_register_func('api/lists/subscriptions', 'api_lists_list', true);
  */
 function api_lists_ownerships($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -3306,7 +3276,7 @@ api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
  */
 function api_lists_statuses($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        $user_info = api_get_user($a);
        if (api_user() === false || $user_info === false) {
@@ -3341,7 +3311,8 @@ function api_lists_statuses($type)
                $condition[] = $max_id;
        }
        if ($exclude_replies > 0) {
-               $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
+               $condition[0] .= ' AND `item`.`gravity` = ?';
+               $condition[] = GRAVITY_PARENT;
        }
        if ($conversation_id > 0) {
                $condition[0] .= " AND `item`.`parent` = ?";
@@ -3369,11 +3340,11 @@ function api_lists_statuses($type)
 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
 
 /**
+ * Returns either the friends of the follower list
+ *
  * Considers friends and followers lists to be private and won't return
  * anything if any user_id parameter is passed.
  *
- * @brief Returns either the friends of the follower list
- *
  * @param string $qtype Either "friends" or "followers"
  * @return boolean|array
  * @throws BadRequestException
@@ -3384,7 +3355,7 @@ api_register_func('api/lists/statuses', 'api_lists_statuses', true);
  */
 function api_statuses_f($qtype)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -3460,9 +3431,7 @@ function api_statuses_f($qtype)
 
 
 /**
- * Returns the user's friends.
- *
- * @brief      Returns the list of friends of the provided user
+ * Returns the list of friends of the provided user
  *
  * @deprecated By Twitter API in favor of friends/list
  *
@@ -3481,9 +3450,7 @@ function api_statuses_friends($type)
 }
 
 /**
- * Returns the user's followers.
- *
- * @brief      Returns the list of followers of the provided user
+ * Returns the list of followers of the provided user
  *
  * @deprecated By Twitter API in favor of friends/list
  *
@@ -3567,15 +3534,15 @@ api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
  */
 function api_statusnet_config($type)
 {
-       $name      = Config::get('config', 'sitename');
+       $name      = DI::config()->get('config', 'sitename');
        $server    = DI::baseUrl()->getHostname();
        $logo      = DI::baseUrl() . '/images/friendica-64.png';
-       $email     = Config::get('config', 'admin_email');
-       $closed    = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
-       $private   = Config::get('system', 'block_public') ? 'true' : 'false';
-       $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
-       $ssl       = Config::get('system', 'have_ssl') ? 'true' : 'false';
-       $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
+       $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' => '',
@@ -3617,96 +3584,6 @@ function api_statusnet_version($type)
 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
 
-/**
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @param int $rel A contact relationship constant
- * @return array|string|void
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- * @todo use api_format_data() to return data
- */
-function api_ff_ids($type, int $rel)
-{
-       if (!api_user()) {
-               throw new ForbiddenException();
-       }
-
-       $a = \get_app();
-
-       api_get_user($a);
-
-       $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
-
-       $contacts = DBA::p("SELECT `pcontact`.`id`
-               FROM `contact`
-               INNER JOIN `contact` AS `pcontact`
-                   ON `contact`.`nurl` = `pcontact`.`nurl`
-                   AND `pcontact`.`uid` = 0
-               WHERE `contact`.`uid` = ?
-               AND NOT `contact`.`self`
-               AND `contact`.`rel` IN (?, ?)",
-               api_user(),
-               $rel,
-               Contact::FRIEND
-       );
-
-       $ids = [];
-       foreach (DBA::toArray($contacts) as $contact) {
-               if ($stringify_ids) {
-                       $ids[] = $contact['id'];
-               } else {
-                       $ids[] = intval($contact['id']);
-               }
-       }
-
-       return api_format_data('ids', $type, ['id' => $ids]);
-}
-
-/**
- * Returns the ID of every user the user is following.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
- */
-function api_friends_ids($type)
-{
-       return api_ff_ids($type, Contact::SHARING);
-}
-
-/**
- * Returns the ID of every user following the user.
- *
- * @param string $type Return type (atom, rss, xml, json)
- *
- * @return array|string
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
- */
-function api_followers_ids($type)
-{
-       return api_ff_ids($type, Contact::FOLLOWER);
-}
-
-/// @TODO move to top of file or somewhere better
-api_register_func('api/friends/ids', 'api_friends_ids', true);
-api_register_func('api/followers/ids', 'api_followers_ids', true);
-
 /**
  * Sends a new direct message.
  *
@@ -3723,7 +3600,7 @@ api_register_func('api/followers/ids', 'api_followers_ids', true);
  */
 function api_direct_messages_new($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -3800,9 +3677,7 @@ function api_direct_messages_new($type)
 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
 
 /**
- * Destroys a direct message.
- *
- * @brief delete a direct_message from mail table through api
+ * delete a direct_message from mail table through api
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @return string|array
@@ -3815,7 +3690,7 @@ api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, AP
  */
 function api_direct_messages_destroy($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -3888,8 +3763,6 @@ api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy',
 /**
  * Unfollow Contact
  *
- * @brief unfollow contact
- *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @return string|array
  * @throws BadRequestException
@@ -3983,7 +3856,7 @@ api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, AP
  */
 function api_direct_messages_box($type, $box, $verbose)
 {
-       $a = \get_app();
+       $a = DI::app();
        if (api_user() === false) {
                throw new ForbiddenException();
        }
@@ -4185,7 +4058,7 @@ api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
 
 
 /**
- * @brief delete a complete photoalbum with all containing photos from database through api
+ * 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
@@ -4206,26 +4079,18 @@ function api_fr_photoalbum_delete($type)
                throw new BadRequestException("no albumname specified");
        }
        // check if album is existing
-       $r = q(
-               "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
-               intval(api_user()),
-               DBA::escape($album)
-       );
-       if (!DBA::isResult($r)) {
+
+       $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
-       foreach ($r as $rr) {
-               $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
-               $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
-
-               if (!DBA::isResult($photo_item)) {
-                       throw new InternalServerErrorException("problem with deleting items occured");
-               }
-               Item::deleteForUser(['id' => $photo_item['id']], api_user());
-       }
+       $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]);
@@ -4240,7 +4105,7 @@ function api_fr_photoalbum_delete($type)
 }
 
 /**
- * @brief update the name of the album for all photos of an album
+ * 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
@@ -4282,7 +4147,7 @@ function api_fr_photoalbum_update($type)
 
 
 /**
- * @brief list all photos of the authenticated user
+ * list all photos of the authenticated user
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @return string|array
@@ -4330,7 +4195,7 @@ function api_fr_photos_list($type)
 }
 
 /**
- * @brief upload a new photo or change an existing photo
+ * upload a new photo or change an existing photo
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @return string|array
@@ -4469,7 +4334,7 @@ function api_fr_photo_create_update($type)
 }
 
 /**
- * @brief delete a single photo from the database through api
+ * delete a single photo from the database through api
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @return string|array
@@ -4502,19 +4367,13 @@ function api_fr_photo_delete($type)
 
        // return success of deletion or error message
        if ($result) {
-               // retrieve the id of the parent element (the photo element)
-               $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
-               $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
-
-               if (!DBA::isResult($photo_item)) {
-                       throw new InternalServerErrorException("problem with deleting items occured");
-               }
                // 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)
-               Item::deleteForUser(['id' => $photo_item['id']], api_user());
+               $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
+               Item::deleteForUser($condition, api_user());
 
-               $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
-               return api_format_data("photo_delete", $type, ['$result' => $answer]);
+               $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");
        }
@@ -4522,7 +4381,7 @@ function api_fr_photo_delete($type)
 
 
 /**
- * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
+ * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @return string|array
@@ -4551,9 +4410,7 @@ function api_fr_photo_detail($type)
 
 
 /**
- * Updates the user’s profile image.
- *
- * @brief updates the profile image for the user (either a specified profile or the default profile)
+ * updates the profile image for the user (either a specified profile or the default profile)
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  *
@@ -4598,7 +4455,7 @@ function api_account_update_profile_image($type)
                $media = $_FILES['media'];
        }
        // save new profile image
-       $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
+       $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
 
        // get filetype
        if (is_array($media['type'])) {
@@ -4627,8 +4484,8 @@ function api_account_update_profile_image($type)
        Contact::updateSelfFromUserID(api_user(), true);
 
        // Update global directory in background
-       $url = DI::baseUrl() . '/profile/' . \get_app()->user['nickname'];
-       if ($url && strlen(Config::get('system', 'directory'))) {
+       $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
+       if ($url && strlen(DI::config()->get('system', 'directory'))) {
                Worker::add(PRIORITY_LOW, "Directory", $url);
        }
 
@@ -4668,7 +4525,7 @@ 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(get_app());
+       $api_user = api_get_user(DI::app());
 
        if (!empty($_POST['name'])) {
                DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
@@ -4685,7 +4542,7 @@ function api_account_update_profile($type)
 
        Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
        // Update global directory in background
-       if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
+       if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
                Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
        }
 
@@ -4775,13 +4632,8 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
                }
        }
 
-       if ($filetype == "") {
-               $filetype = Images::guessType($filename);
-       }
-       $imagedata = @getimagesize($src);
-       if ($imagedata) {
-               $filetype = $imagedata['mime'];
-       }
+       $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
+
        Logger::log(
                "File upload src: " . $src . " - filename: " . $filename .
                " - size: " . $filesize . " - type: " . $filetype,
@@ -4793,7 +4645,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
                throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
        }
        // check against max upload size within Friendica instance
-       $maximagesize = Config::get('system', 'maximagesize');
+       $maximagesize = DI::config()->get('system', 'maximagesize');
        if ($maximagesize && ($filesize > $maximagesize)) {
                $formattedBytes = Strings::formatBytes($maximagesize);
                throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
@@ -4811,7 +4663,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
        @unlink($src);
 
        // check max length of images on server
-       $max_length = Config::get('system', 'max_image_length');
+       $max_length = DI::config()->get('system', 'max_image_length');
        if (!$max_length) {
                $max_length = MAX_IMAGE_LENGTH;
        }
@@ -4880,7 +4732,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
                Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
        }
 
-       if (isset($r) && $r) {
+       if (!empty($r)) {
                // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
                if ($photo_id == null && $mediatype == "photo") {
                        post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
@@ -4913,7 +4765,6 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
        $arr['guid']          = System::createUUID();
        $arr['uid']           = intval(api_user());
        $arr['uri']           = $uri;
-       $arr['parent-uri']    = $uri;
        $arr['type']          = 'photo';
        $arr['wall']          = 1;
        $arr['resource-id']   = $hash;
@@ -4963,7 +4814,7 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
  */
 function prepare_photo_data($type, $scale, $photo_id)
 {
-       $a = \get_app();
+       $a = DI::app();
        $user_info = api_get_user($a);
 
        if ($user_info === false) {
@@ -5027,14 +4878,17 @@ function prepare_photo_data($type, $scale, $photo_id)
        }
 
        // retrieve item element for getting activities (like, dislike etc.) related to photo
-       $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
-       $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
+       $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
+       $item = Item::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.');
+       }
 
        $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
 
        // retrieve comments on photo
        $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
-               $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
+               $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
 
        $statuses = Item::selectForUser(api_user(), [], $condition);
 
@@ -5054,10 +4908,10 @@ function prepare_photo_data($type, $scale, $photo_id)
        $data['photo']['friendica_comments'] = $comments;
 
        // include info if rights on photo and rights on item are mismatching
-       $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
-               $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
-               $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
-               $data['photo']['deny_cid'] != $item[0]['deny_cid'];
+       $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
+               $data['photo']['deny_cid'] != $item['deny_cid'] ||
+               $data['photo']['allow_gid'] != $item['allow_gid'] ||
+               $data['photo']['deny_gid'] != $item['deny_gid'];
        $data['photo']['rights_mismatch'] = $rights_mismatch;
 
        return $data;
@@ -5151,8 +5005,7 @@ function api_get_announce($item)
        }
 
        $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
-       $activity = Item::activityToIndex(Activity::ANNOUNCE);
-       $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
+       $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
        $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
        if (!DBA::isResult($announce)) {
                return [];
@@ -5162,7 +5015,7 @@ function api_get_announce($item)
 }
 
 /**
- * @brief Return the item shared, if the item contains only the [share] tag
+ * Return the item shared, if the item contains only the [share] tag
  *
  * @param array $item Sharer item
  * @return array|false Shared item or false if not a reshare
@@ -5204,7 +5057,7 @@ function api_share_as_retweet(&$item)
 
        $reshared_item["share-pre-body"] = $reshared['comment'];
        $reshared_item["body"] = $reshared['shared'];
-       $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
+       $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
        $reshared_item["author-name"] = $reshared['author'];
        $reshared_item["author-link"] = $reshared['profile'];
        $reshared_item["author-avatar"] = $reshared['avatar'];
@@ -5248,7 +5101,7 @@ function api_in_reply_to($item)
        $in_reply_to['user_id_str'] = null;
        $in_reply_to['screen_name'] = null;
 
-       if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
+       if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
                $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
                if (DBA::isResult($parent)) {
                        $in_reply_to['status_id'] = intval($parent['id']);
@@ -5391,7 +5244,7 @@ function api_best_nickname(&$contacts)
  */
 function api_friendica_group_show($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5423,7 +5276,7 @@ function api_friendica_group_show($type)
        // loop through all groups and retrieve all members for adding data in the user array
        $grps = [];
        foreach ($r as $rr) {
-               $members = Contact::getByGroupId($rr['id']);
+               $members = Contact\Group::getById($rr['id']);
                $users = [];
 
                if ($type == "xml") {
@@ -5461,7 +5314,7 @@ api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
  */
 function api_friendica_group_delete($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5528,7 +5381,7 @@ api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', tr
  */
 function api_lists_destroy($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5650,7 +5503,7 @@ function group_create($name, $uid, $users = [])
  */
 function api_friendica_group_create($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5684,7 +5537,7 @@ api_register_func('api/friendica/group_create', 'api_friendica_group_create', tr
  */
 function api_lists_create($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5723,7 +5576,7 @@ api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST)
  */
 function api_friendica_group_update($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5748,7 +5601,7 @@ function api_friendica_group_update($type)
        }
 
        // remove members
-       $members = Contact::getByGroupId($gid);
+       $members = Contact\Group::getById($gid);
        foreach ($members as $member) {
                $cid = $member['id'];
                foreach ($users as $user) {
@@ -5802,7 +5655,7 @@ api_register_func('api/friendica/group_update', 'api_friendica_group_update', tr
  */
 function api_lists_update($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5852,7 +5705,7 @@ api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST)
  */
 function api_friendica_activity($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5862,7 +5715,7 @@ function api_friendica_activity($type)
 
        $id = $_REQUEST['id'] ?? 0;
 
-       $res = Item::performLike($id, $verb);
+       $res = Item::performActivity($id, $verb, api_user());
 
        if ($res) {
                if ($type == "xml") {
@@ -5889,17 +5742,18 @@ api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity',
 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
 
 /**
- * @brief Returns notifications
+ * Returns notifications
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
+ *
  * @return string|array
- * @throws BadRequestException
  * @throws ForbiddenException
- * @throws InternalServerErrorException
+ * @throws BadRequestException
+ * @throws Exception
  */
 function api_friendica_notification($type)
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -5907,25 +5761,31 @@ function api_friendica_notification($type)
        if ($a->argc!==3) {
                throw new BadRequestException("Invalid argument count");
        }
-       $notes = DI::notify()->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
+
+       $notifications = DI::notification()->getApiList(local_user());
 
        if ($type == "xml") {
-               $xmlnotes = [];
-               if (!empty($notes)) {
-                       foreach ($notes as $note) {
-                               $xmlnotes[] = ["@attributes" => $note];
+               $xmlnotes = false;
+               if (!empty($notifications)) {
+                       foreach ($notifications as $notification) {
+                               $xmlnotes[] = ["@attributes" => $notification->toArray()];
                        }
                }
 
-               $notes = $xmlnotes;
+               $result = $xmlnotes;
+       } elseif (count($notifications) > 0) {
+               $result = $notifications->getArrayCopy();
+       } else {
+               $result = false;
        }
-       return api_format_data("notes", $type, ['note' => $notes]);
+
+       return api_format_data("notes", $type, ['note' => $result]);
 }
 
 /**
- * POST request with 'id' param as notification id
+ * Set notification as seen and returns associated item (if possible)
  *
- * @brief Set notification as seen and returns associated item (if possible)
+ * POST request with 'id' param as notification id
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @return string|array
@@ -5937,37 +5797,38 @@ function api_friendica_notification($type)
  */
 function api_friendica_notification_seen($type)
 {
-       $a = \get_app();
+       $a         = DI::app();
        $user_info = api_get_user($a);
 
        if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
-       if ($a->argc!==4) {
+       if ($a->argc !== 4) {
                throw new BadRequestException("Invalid argument count");
        }
 
        $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
 
-       $nm = DI::notify();
-       $note = $nm->getByID($id);
-       if (is_null($note)) {
-               throw new BadRequestException("Invalid argument");
-       }
-
-       $nm->setSeen($note);
-       if ($note['otype']=='item') {
-               // would be really better with an ItemsManager and $im->getByID() :-P
-               $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
-               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);
+       try {
+               $notify = DI::notify()->getByID($id, api_user());
+               DI::notify()->setSeen(true, $notify);
+
+               if ($notify->otype === Notify\ObjectType::ITEM) {
+                       $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
+                       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);
+                       }
+                       // the item can't be found, but we set the notification as seen, so we count this as a success
                }
-               // the item can't be found, but we set the note as seen, so we count this as a success
+               return api_format_data('result', $type, ['result' => "success"]);
+       } catch (NotFoundException $e) {
+               throw new BadRequestException('Invalid argument', $e);
+       } catch (Exception $e) {
+               throw new InternalServerErrorException('Internal Server exception', $e);
        }
-       return api_format_data('result', $type, ['result' => "success"]);
 }
 
 /// @TODO move to top of file or somewhere better
@@ -5975,7 +5836,7 @@ api_register_func('api/friendica/notification/seen', 'api_friendica_notification
 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
 
 /**
- * @brief update a direct_message to seen state
+ * 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)
@@ -5987,7 +5848,7 @@ api_register_func('api/friendica/notification', 'api_friendica_notification', tr
  */
 function api_friendica_direct_messages_setseen($type)
 {
-       $a = \get_app();
+       $a = DI::app();
        if (api_user() === false) {
                throw new ForbiddenException();
        }
@@ -6026,7 +5887,7 @@ function api_friendica_direct_messages_setseen($type)
 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
 
 /**
- * @brief search for direct_messages containing a searchstring through api
+ * search for direct_messages containing a searchstring through api
  *
  * @param string $type      Known types are 'atom', 'rss', 'xml' and 'json'
  * @param string $box
@@ -6041,7 +5902,7 @@ api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct
  */
 function api_friendica_direct_messages_search($type, $box = "")
 {
-       $a = \get_app();
+       $a = DI::app();
 
        if (api_user() === false) {
                throw new ForbiddenException();
@@ -6096,78 +5957,6 @@ function api_friendica_direct_messages_search($type, $box = "")
 /// @TODO move to top of file or somewhere better
 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
 
-/**
- * @brief return data of all the profiles a user has to the client
- *
- * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string|array
- * @throws BadRequestException
- * @throws ForbiddenException
- * @throws ImagickException
- * @throws InternalServerErrorException
- * @throws UnauthorizedException
- */
-function api_friendica_profile_show($type)
-{
-       $a = \get_app();
-
-       if (api_user() === false) {
-               throw new ForbiddenException();
-       }
-
-       // input params
-       $profile_id = $_REQUEST['profile_id'] ?? 0;
-
-       // retrieve general information about profiles for user
-       $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
-       $directory = Config::get('system', 'directory');
-
-       // get data of the specified profile id or all profiles of the user if not specified
-       if ($profile_id != 0) {
-               $r = Profile::getById(api_user(), $profile_id);
-               // error message if specified gid is not in database
-               if (!DBA::isResult($r)) {
-                       throw new BadRequestException("profile_id not available");
-               }
-       } else {
-               $r = Profile::getListByUser(api_user());
-       }
-       // loop through all returned profiles and retrieve data and users
-       $k = 0;
-       $profiles = [];
-       if (DBA::isResult($r)) {
-               foreach ($r as $rr) {
-                       $profile = api_format_items_profiles($rr);
-
-                       // select all users from contact table, loop and prepare standard return for user data
-                       $users = [];
-                       $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
-                       foreach ($nurls as $nurl) {
-                               $user = api_get_user($a, $nurl['nurl']);
-                               ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
-                       }
-                       $profile['users'] = $users;
-
-                       // add prepared profile data to array for final return
-                       if ($type == "xml") {
-                               $profiles[$k++ . ":profile"] = $profile;
-                       } else {
-                               $profiles[] = $profile;
-                       }
-               }
-       }
-
-       // return settings, authenticated user and profiles data
-       $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
-
-       $result = ['multi_profiles' => $multi_profiles ? true : false,
-                                       'global_dir' => $directory,
-                                       'friendica_owner' => api_get_user($a, $self['nurl']),
-                                       'profiles' => $profiles];
-       return api_format_data("friendica_profiles", $type, ['$result' => $result]);
-}
-api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
-
 /**
  * Returns a list of saved searches.
  *
@@ -6203,9 +5992,9 @@ function api_saved_searches_list($type)
 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
 
 /*
- * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
+ * Number of comments
  *
- * @brief Number of comments
+ * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
  *
  * @param object $data [Status, Status]
  *