]> git.mxchange.org Git - friendica.git/blobdiff - include/api.php
Merge pull request #5234 from fabrixxm/fix/api
[friendica.git] / include / api.php
index a7d8ab3ca3a3af8fec7c6b19190f3b41c21473f4..c89a5b16441c1447a086eef90c82573bcf323696 100644 (file)
@@ -10,6 +10,7 @@ use Friendica\App;
 use Friendica\Content\ContactSelector;
 use Friendica\Content\Feature;
 use Friendica\Content\Text\BBCode;
+use Friendica\Content\Text\HTML;
 use Friendica\Core\Addon;
 use Friendica\Core\Config;
 use Friendica\Core\L10n;
@@ -41,11 +42,9 @@ use Friendica\Util\Network;
 use Friendica\Util\XML;
 
 require_once 'include/conversation.php';
-require_once 'include/html2plain.php';
 require_once 'mod/share.php';
 require_once 'mod/item.php';
 require_once 'include/security.php';
-require_once 'include/html2bbcode.php';
 require_once 'mod/wall_upload.php';
 require_once 'mod/proxy.php';
 
@@ -55,7 +54,7 @@ define('API_METHOD_POST', 'POST,PUT');
 define('API_METHOD_DELETE', 'POST,DELETE');
 
 $API = [];
-$called_api = null;
+$called_api = [];
 
 /**
  * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
@@ -224,7 +223,7 @@ function api_login(App $a)
                $record = $addon_auth['user_record'];
        } else {
                $user_id = User::authenticate(trim($user), trim($password));
-               if ($user_id) {
+               if ($user_id !== false) {
                        $record = dba::selectFirst('user', [], ['uid' => $user_id]);
                }
        }
@@ -268,7 +267,7 @@ function api_check_method($method)
  * @brief Main API entry point
  *
  * @param object $a App
- * @return string API call result
+ * @return string|array API call result
  */
 function api_call(App $a)
 {
@@ -317,12 +316,16 @@ function api_call(App $a)
                                        /// @TODO round() really everywhere?
                                        logger(
                                                parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
-                                                       "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
+                                                       "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
                                                        round($a->performance["database"] - $a->performance["database_write"], 3),
                                                        round($a->performance["database_write"], 3),
+                                                       round($a->performance["cache"], 3),
+                                                       round($a->performance["cache_write"], 3),
                                                        round($a->performance["network"], 2),
                                                        round($a->performance["file"], 2),
-                                                       round($duration - ($a->performance["database"] + $a->performance["network"]     + $a->performance["file"]), 2),
+                                                       round($duration - ($a->performance["database"]
+                                                               + $a->performance["cache"] + $a->performance["cache_write"]
+                                                               + $a->performance["network"] + $a->performance["file"]), 2),
                                                        round($duration, 2)
                                                ),
                                                LOGGER_DEBUG
@@ -344,6 +347,21 @@ function api_call(App $a)
                                                        }
                                                }
 
+                                               $o = "Cache Read:\n";
+                                               foreach ($a->callstack["cache"] as $func => $time) {
+                                                       $time = round($time, 3);
+                                                       if ($time > 0) {
+                                                               $o .= $func . ": " . $time . "\n";
+                                                       }
+                                               }
+                                               $o .= "\nCache Write:\n";
+                                               foreach ($a->callstack["cache_write"] as $func => $time) {
+                                                       $time = round($time, 3);
+                                                       if ($time > 0) {
+                                                               $o .= $func . ": " . $time . "\n";
+                                                       }
+                                               }
+
                                                $o .= "\nNetwork:\n";
                                                foreach ($a->callstack["network"] as $func => $time) {
                                                        $time = round($time, 3);
@@ -369,9 +387,7 @@ function api_call(App $a)
                                                break;
                                        case "json":
                                                header("Content-Type: application/json");
-                                               foreach ($return as $rr) {
-                                                       $json = json_encode($rr);
-                                               }
+                                               $json = json_encode(end($return));
                                                if (x($_GET, 'callback')) {
                                                        $json = $_GET['callback'] . "(" . $json . ")";
                                                }
@@ -403,7 +419,7 @@ function api_call(App $a)
  *
  * @param string $type Return type (xml, json, rss, as)
  * @param object $e    HTTPException Error object
- * @return string error message formatted as $type
+ * @return string|array error message formatted as $type
  */
 function api_error($type, $e)
 {
@@ -476,7 +492,7 @@ function api_rss_extra(App $a, $arr, $user_info)
  */
 function api_unique_id_to_nurl($id)
 {
-       $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
+       $r = dba::selectFirst('contact', ['nurl'], ['id' => $id]);
 
        if (DBM::is_result($r)) {
                return $r["nurl"];
@@ -513,10 +529,10 @@ function api_get_user(App $a, $contact_id = null)
 
        // Searching for contact id with uid = 0
        if (!is_null($contact_id) && (intval($contact_id) != 0)) {
-               $user = dbesc(api_unique_id_to_nurl($contact_id));
+               $user = dbesc(api_unique_id_to_nurl(intval($contact_id)));
 
                if ($user == "") {
-                       throw new BadRequestException("User not found.");
+                       throw new BadRequestException("User ID ".$contact_id." not found.");
                }
 
                $url = $user;
@@ -530,7 +546,7 @@ function api_get_user(App $a, $contact_id = null)
                $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
 
                if ($user == "") {
-                       throw new BadRequestException("User not found.");
+                       throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
                }
 
                $url = $user;
@@ -559,16 +575,14 @@ function api_get_user(App $a, $contact_id = null)
                $argid = count($called_api);
                list($user, $null) = explode(".", $a->argv[$argid]);
                if (is_numeric($user)) {
-                       $user = dbesc(api_unique_id_to_nurl($user));
-
-                       if ($user == "") {
-                               return false;
-                       }
+                       $user = dbesc(api_unique_id_to_nurl(intval($user)));
 
-                       $url = $user;
-                       $extra_query = "AND `contact`.`nurl` = '%s' ";
-                       if (api_user() !== false) {
-                               $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
+                       if ($user != "") {
+                               $url = $user;
+                               $extra_query = "AND `contact`.`nurl` = '%s' ";
+                               if (api_user() !== false) {
+                                       $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
+                               }
                        }
                } else {
                        $user = dbesc($user);
@@ -602,7 +616,9 @@ function api_get_user(App $a, $contact_id = null)
        );
 
        // Selecting the id by priority, friendica first
-       api_best_nickname($uinfo);
+       if (is_array($uinfo)) {
+               api_best_nickname($uinfo);
+       }
 
        // if the contact wasn't found, fetch it from the contacts with uid = 0
        if (!DBM::is_result($uinfo)) {
@@ -629,6 +645,8 @@ function api_get_user(App $a, $contact_id = null)
                                'description' => $r[0]["about"],
                                'profile_image_url' => $r[0]["micro"],
                                'profile_image_url_https' => $r[0]["micro"],
+                               'profile_image_url_profile_size' => $r[0]["thumb"],
+                               'profile_image_url_large' => $r[0]["photo"],
                                'url' => $r[0]["url"],
                                'protected' => false,
                                'followers_count' => 0,
@@ -652,13 +670,14 @@ function api_get_user(App $a, $contact_id = null)
                                'statusnet_profile_url' => $r[0]["url"],
                                'uid' => 0,
                                'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
+                               'pid' => Contact::getIdForURL($r[0]["url"], 0, true),
                                'self' => 0,
                                'network' => $r[0]["network"],
                        ];
 
                        return $ret;
                } else {
-                       throw new BadRequestException("User not found.");
+                       throw new BadRequestException("User ".$url." not found.");
                }
        }
 
@@ -667,14 +686,8 @@ function api_get_user(App $a, $contact_id = null)
                        $uinfo[0]['network'] = NETWORK_DFRN;
                }
 
-               $usr = q(
-                       "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
-                       intval(api_user())
-               );
-               $profile = q(
-                       "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
-                       intval(api_user())
-               );
+               $usr = dba::selectFirst('user', ['default-location'], ['uid' => api_user()]);
+               $profile = dba::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
 
                /// @TODO old-lost code? (twice)
                // Counting is deactivated by now, due to performance issues
@@ -741,14 +754,14 @@ function api_get_user(App $a, $contact_id = null)
 
        $pcontact_id  = Contact::getIdForURL($uinfo[0]['url'], 0, true);
 
-       if (!empty($profile[0]['about'])) {
-               $description = $profile[0]['about'];
+       if (!empty($profile['about'])) {
+               $description = $profile['about'];
        } else {
                $description = $uinfo[0]["about"];
        }
 
-       if (!empty($usr[0]['default-location'])) {
-               $location = $usr[0]['default-location'];
+       if (!empty($usr['default-location'])) {
+               $location = $usr['default-location'];
        } elseif (!empty($uinfo[0]["location"])) {
                $location = $uinfo[0]["location"];
        } else {
@@ -764,6 +777,8 @@ function api_get_user(App $a, $contact_id = null)
                'description' => $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),
@@ -789,6 +804,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),
                'self' => $uinfo[0]['self'],
                'network' => $uinfo[0]['network'],
        ];
@@ -836,16 +852,12 @@ 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-link"]);
+       $status_user = api_get_user($a, $item["author-id"]);
 
-       $status_user["protected"] = (($item["allow_cid"] != "") ||
-                                       ($item["allow_gid"] != "") ||
-                                       ($item["deny_cid"] != "") ||
-                                       ($item["deny_gid"] != "") ||
-                                       $item["private"]);
+       $status_user["protected"] = $item["private"];
 
        if ($item['thr-parent'] == $item['uri']) {
-               $owner_user = api_get_user($a, $item["owner-link"]);
+               $owner_user = api_get_user($a, $item["owner-id"]);
        } else {
                $owner_user = $status_user;
        }
@@ -915,7 +927,7 @@ function api_reformat_xml(&$item, &$key)
  *
  * @return string The XML data
  */
-function api_create_xml($data, $root_element)
+function api_create_xml(array $data, $root_element)
 {
        $childname = key($data);
        $data2 = array_pop($data);
@@ -940,7 +952,7 @@ function api_create_xml($data, $root_element)
                $i = 1;
 
                foreach ($data2 as $item) {
-                       $data4[$i++.":".$childname] = $item;
+                       $data4[$i++ . ":" . $childname] = $item;
                }
 
                $data2 = $data4;
@@ -959,7 +971,7 @@ function api_create_xml($data, $root_element)
  * @param string $type         Return type (atom, rss, xml, json)
  * @param array  $data         JSON style array
  *
- * @return (string|object|array) XML data or JSON data
+ * @return (string|array) XML data or JSON data
  */
 function api_format_data($root_element, $type, $data)
 {
@@ -970,6 +982,7 @@ function api_format_data($root_element, $type, $data)
                        $ret = api_create_xml($data, $root_element);
                        break;
                case "json":
+               default:
                        $ret = $data;
                        break;
        }
@@ -1047,7 +1060,7 @@ function requestdata($k)
 }
 
 /**
- * Waitman Gobble Mod
+ * Deprecated function to upload media.
  *
  * @param string $type Return type (atom, rss, xml, json)
  *
@@ -1077,16 +1090,14 @@ function api_statuses_mediap($type)
                $purifier = new HTMLPurifier($config);
                $txt = $purifier->purify($txt);
        }
-       $txt = html2bbcode($txt);
+       $txt = HTML::toBBCode($txt);
 
-       $a->argv[1]=$user_info['screen_name']; //should be set to username?
+       $a->argv[1] = $user_info['screen_name']; //should be set to username?
 
-       // tell wall_upload function to return img info instead of echo
-       $_REQUEST['hush'] = 'yeah';
-       $bebop = wall_upload_post($a);
+       $picture = wall_upload_post($a, false);
 
        // now that we have the img url in bbcode we can add it to the status and insert the wall item.
-       $_REQUEST['body'] = $txt . "\n\n" . $bebop;
+       $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
        item_post($a);
 
        // this should output the last post (the one we just posted).
@@ -1128,7 +1139,7 @@ function api_statuses_update($type)
                        $purifier = new HTMLPurifier($config);
                        $txt = $purifier->purify($txt);
 
-                       $_REQUEST['body'] = html2bbcode($txt);
+                       $_REQUEST['body'] = HTML::toBBCode($txt);
                }
        } else {
                $_REQUEST['body'] = requestdata('status');
@@ -1235,10 +1246,9 @@ function api_statuses_update($type)
 
        if (x($_FILES, 'media')) {
                // upload the image if we have one
-               $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
-               $media = wall_upload_post($a);
-               if (strlen($media) > 0) {
-                       $_REQUEST['body'] .= "\n\n" . $media;
+               $picture = wall_upload_post($a, false);
+               if (is_array($picture)) {
+                       $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
                }
        }
 
@@ -1335,31 +1345,17 @@ function api_status_show($type)
        logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
 
        if ($type == "raw") {
-               $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
+               $privacy_sql = "AND NOT `private`";
        } else {
                $privacy_sql = "";
        }
 
        // get last public wall message
-       $lastwall = q(
-               "SELECT `item`.*
-                       FROM `item`
-                       WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
-                               AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
-                               AND `item`.`type` != 'activity' $privacy_sql
-                       ORDER BY `item`.`id` DESC
-                       LIMIT 1",
-               intval($user_info['cid']),
-               intval(api_user()),
-               dbesc($user_info['url']),
-               dbesc(normalise_link($user_info['url'])),
-               dbesc($user_info['url']),
-               dbesc(normalise_link($user_info['url']))
-       );
+       $condition = ["`owner-id` = ? AND `uid` = ? AND `type` != 'activity' ".$privacy_sql,
+               $user_info['pid'], api_user()];
+       $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
 
        if (DBM::is_result($lastwall)) {
-               $lastwall = $lastwall[0];
-
                $in_reply_to = api_in_reply_to($lastwall);
 
                $converted = api_convert_item($lastwall);
@@ -1407,24 +1403,24 @@ function api_status_show($type)
                        $status_info["entities"] = $converted["entities"];
                }
 
-               if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
-                       $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
-               } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
-                       $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
+               if ($status_info["source"] == 'web') {
+                       $status_info["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
+               } elseif (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $status_info["source"]) {
+                       $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['network'], $user_info['url']).')');
                }
 
                // "uid" and "self" are only needed for some internal stuff, so remove it from here
                unset($status_info["user"]["uid"]);
                unset($status_info["user"]["self"]);
-       }
 
-       logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
+               logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
 
-       if ($type == "raw") {
-               return $status_info;
-       }
+               if ($type == "raw") {
+                       return $status_info;
+               }
 
-       return api_format_data("statuses", $type, ['status' => $status_info]);
+               return api_format_data("statuses", $type, ['status' => $status_info]);
+       }
 }
 
 /**
@@ -1439,28 +1435,12 @@ function api_users_show($type)
        $a = get_app();
 
        $user_info = api_get_user($a);
-       $lastwall = q(
-               "SELECT `item`.*
-                       FROM `item`
-                       INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
-                               AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
-                               AND `type`!='activity'
-                               AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
-                       ORDER BY `id` DESC
-                       LIMIT 1",
-               intval(api_user()),
-               dbesc(ACTIVITY_POST),
-               intval($user_info['cid']),
-               dbesc($user_info['url']),
-               dbesc(normalise_link($user_info['url'])),
-               dbesc($user_info['url']),
-               dbesc(normalise_link($user_info['url']))
-       );
 
-       if (DBM::is_result($lastwall)) {
-               $lastwall = $lastwall[0];
+       $condition = ["`owner-id` = ? AND `uid` = ? AND `verb` = ? AND `type` != 'activity' AND NOT `private`",
+               $user_info['pid'], api_user(), ACTIVITY_POST];
+       $lastwall = dba::selectFirst('item', [], $condition, ['order' => ['id' => true]]);
 
+       if (DBM::is_result($lastwall)) {
                $in_reply_to = api_in_reply_to($lastwall);
 
                $converted = api_convert_item($lastwall);
@@ -1498,12 +1478,12 @@ function api_users_show($type)
                        $user_info["status"]["entities"] = $converted["entities"];
                }
 
-               if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
-                       $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
+               if ($user_info["status"]["source"] == 'web') {
+                       $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['network'], $user_info['url']);
                }
 
-               if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
-                       $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
+               if (ContactSelector::networkToName($lastwall['network'], $user_info['url']) != $user_info["status"]["source"]) {
+                       $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['network'], $user_info['url']) . ')');
                }
        }
 
@@ -1552,10 +1532,10 @@ function api_users_search($type)
                        }
                        $userlist = ["users" => $userlist];
                } else {
-                       throw new BadRequestException("User not found.");
+                       throw new BadRequestException("User ".$_GET["q"]." not found.");
                }
        } else {
-               throw new BadRequestException("User not found.");
+               throw new BadRequestException("No user specified.");
        }
 
        return api_format_data("users", $type, $userlist);
@@ -1608,8 +1588,14 @@ api_register_func('api/users/lookup', 'api_users_lookup', true);
  */
 function api_search($type)
 {
+       $a = get_app();
+       $user_info = api_get_user($a);
+
+       if (api_user() === false || $user_info === false) {
+               throw new ForbiddenException();
+       }
+
        $data = [];
-       $sql_extra = '';
 
        if (!x($_REQUEST, 'q')) {
                throw new BadRequestException("q parameter is required.");
@@ -1629,24 +1615,20 @@ function api_search($type)
 
        $start = $page * $count;
 
+       $condition = ["`verb` = ? AND `item`.`id` > ?
+               AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
+               AND `item`.`body` LIKE CONCAT('%',?,'%')",
+               ACTIVITY_POST, $since_id, api_user(), $_REQUEST['q']];
+
        if ($max_id > 0) {
-               $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
+               $condition[0] .= " AND `item`.`id` <= ?";
+               $condition[] = $max_id;
        }
 
-       $r = dba::p(
-               "SELECT ".item_fieldlists()."
-               FROM `item` ".item_joins()."
-               WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
-               AND `item`.`body` LIKE CONCAT('%',?,'%')
-               $sql_extra
-               AND `item`.`id`>?
-               ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
-               api_user(),
-               $_REQUEST['q'],
-               $since_id
-       );
+       $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
-       $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
+       $data['status'] = api_format_items(dba::inArray($statuses), $user_info);
 
        return api_format_data("statuses", $type, $data);
 }
@@ -1668,8 +1650,9 @@ api_register_func('api/search', 'api_search', true);
 function api_statuses_home_timeline($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
@@ -1679,8 +1662,7 @@ function api_statuses_home_timeline($type)
        unset($_REQUEST["screen_name"]);
        unset($_GET["screen_name"]);
 
-       $user_info = api_get_user($a);
-       // get last newtork messages
+       // get last network messages
 
        // params
        $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
@@ -1696,52 +1678,37 @@ function api_statuses_home_timeline($type)
 
        $start = $page * $count;
 
-       $sql_extra = '';
+       $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ?", api_user(), ACTIVITY_POST, $since_id];
+
        if ($max_id > 0) {
-               $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
+               $condition[0] .= " AND `item`.`id` <= ?";
+               $condition[] = $max_id;
        }
        if ($exclude_replies > 0) {
-               $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
+               $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
        }
        if ($conversation_id > 0) {
-               $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
+               $condition[0] .= " AND `item`.`parent` = ?";
+               $condition[] = $conversation_id;
        }
 
-       $r = q(
-               "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
-               `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
-               `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-               `contact`.`id` AS `cid`
-               FROM `item`
-               STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-               WHERE `item`.`uid` = %d AND `verb` = '%s'
-               AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
-               $sql_extra
-               AND `item`.`id`>%d
-               ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
-               intval(api_user()),
-               dbesc(ACTIVITY_POST),
-               intval($since_id),
-               intval($start),
-               intval($count)
-       );
+       $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
-       $ret = api_format_items($r, $user_info, false, $type);
+       $items = dba::inArray($statuses);
+
+       $ret = api_format_items($items, $user_info, false, $type);
 
        // Set all posts from the query above to seen
        $idarray = [];
-       foreach ($r as $item) {
+       foreach ($items as $item) {
                $idarray[] = intval($item["id"]);
        }
 
-       $idlist = implode(",", $idarray);
-
-       if ($idlist != "") {
-               $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
-
+       if (!empty($idarray)) {
+               $unseen = dba::exists('item', ['unseen' => true, 'id' => $idarray]);
                if ($unseen) {
-                       q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
+                       Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
                }
        }
 
@@ -1770,13 +1737,13 @@ api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline',
 function api_statuses_public_timeline($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
-       $user_info = api_get_user($a);
-       // get last newtork messages
+       // get last network messages
 
        // params
        $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
@@ -1794,61 +1761,35 @@ function api_statuses_public_timeline($type)
        $sql_extra = '';
 
        if ($exclude_replies && !$conversation_id) {
+               $condition = ["`verb` = ? AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall`",
+                       ACTIVITY_POST, $since_id];
+
                if ($max_id > 0) {
-                       $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
-               }
-
-               $r = dba::p(
-                       "SELECT " . item_fieldlists() . "
-                       FROM `thread`
-                       STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
-                       " . item_joins() . "
-                       STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
-                               AND NOT `user`.`hidewall`
-                       AND `verb` = ?
-                       AND NOT `thread`.`private`
-                       AND `thread`.`wall`
-                       AND `thread`.`visible`
-                       AND NOT `thread`.`deleted`
-                       AND NOT `thread`.`moderated`
-                       AND `thread`.`iid` > ?
-                       $sql_extra
-                       ORDER BY `thread`.`iid` DESC
-                       LIMIT " . intval($start) . ", " . intval($count),
-                       ACTIVITY_POST,
-                       $since_id
-               );
+                       $condition[0] .= " AND `thread`.`iid` <= ?";
+                       $condition[] = $max_id;
+               }
+
+               $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
+               $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
 
-               $r = dba::inArray($r);
+               $r = dba::inArray($statuses);
        } else {
+               $condition = ["`verb` = ? AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin`",
+                       ACTIVITY_POST, $since_id];
+
                if ($max_id > 0) {
-                       $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
+                       $condition[0] .= " AND `item`.`id` <= ?";
+                       $condition[] = $max_id;
                }
                if ($conversation_id > 0) {
-                       $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
-               }
-
-               $r = dba::p(
-                       "SELECT " . item_fieldlists() . "
-                       FROM `item`
-                       " . item_joins() . "
-                       STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
-                               AND NOT `user`.`hidewall`
-                       AND `verb` = ?
-                       AND NOT `item`.`private`
-                       AND `item`.`wall`
-                       AND `item`.`visible`
-                       AND NOT `item`.`deleted`
-                       AND NOT `item`.`moderated`
-                       AND `item`.`id` > ?
-                       $sql_extra
-                       ORDER BY `item`.`id` DESC
-                       LIMIT " . intval($start) . ", " . intval($count),
-                       ACTIVITY_POST,
-                       $since_id
-               );
+                       $condition[0] .= " AND `item`.`parent` = ?";
+                       $condition[] = $conversation_id;
+               }
+
+               $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+               $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
-               $r = dba::inArray($r);
+               $r = dba::inArray($statuses);
        }
 
        $ret = api_format_items($r, $user_info, false, $type);
@@ -1879,13 +1820,12 @@ api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline'
 function api_statuses_networkpublic_timeline($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
-       $user_info = api_get_user($a);
-
        $since_id        = x($_REQUEST, 'since_id')        ? $_REQUEST['since_id']        : 0;
        $max_id          = x($_REQUEST, 'max_id')          ? $_REQUEST['max_id']          : 0;
 
@@ -1897,33 +1837,18 @@ function api_statuses_networkpublic_timeline($type)
        }
        $start = ($page - 1) * $count;
 
-       $sql_extra = '';
+       $condition = ["`uid` = 0 AND `verb` = ? AND `thread`.`iid` > ? AND NOT `private`",
+               ACTIVITY_POST, $since_id];
+
        if ($max_id > 0) {
-               $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
-       }
-
-       $r = dba::p(
-               "SELECT " . item_fieldlists() . "
-               FROM `thread`
-               STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
-               " . item_joins() . "
-               WHERE `thread`.`uid` = 0
-               AND `verb` = ?
-               AND NOT `thread`.`private`
-               AND `thread`.`visible`
-               AND NOT `thread`.`deleted`
-               AND NOT `thread`.`moderated`
-               AND `thread`.`iid` > ?
-               $sql_extra
-               ORDER BY `thread`.`iid` DESC
-               LIMIT " . intval($start) . ", " . intval($count),
-               ACTIVITY_POST,
-               $since_id
-       );
+               $condition[0] .= " AND `thread`.`iid` <= ?";
+               $condition[] = $max_id;
+       }
 
-       $r = dba::inArray($r);
+       $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
+       $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
 
-       $ret = api_format_items($r, $user_info, false, $type);
+       $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
 
        $data = ['status' => $ret];
        switch ($type) {
@@ -1949,13 +1874,12 @@ api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpu
 function api_statuses_show($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
-       $user_info = api_get_user($a);
-
        // params
        $id = intval($a->argv[3]);
 
@@ -1972,35 +1896,35 @@ function api_statuses_show($type)
 
        $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
 
-       $sql_extra = '';
+       // try to fetch the item for the local user - or the public item, if there is no local one
+       $uri_item = dba::selectFirst('item', ['uri'], ['id' => $id]);
+       if (!DBM::is_result($uri_item)) {
+               throw new BadRequestException("There is no status with this id.");
+       }
+
+       $item = dba::selectFirst('item', ['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
+       if (!DBM::is_result($item)) {
+               throw new BadRequestException("There is no status with this id.");
+       }
+
+       $id = $item['id'];
+
        if ($conversation) {
-               $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
+               $condition = ['parent' => $id, 'verb' => ACTIVITY_POST];
+               $params = ['order' => ['id' => true]];
        } else {
-               $sql_extra .= " AND `item`.`id` = %d";
+               $condition = ['id' => $id, 'verb' => ACTIVITY_POST];
+               $params = [];
        }
 
-       $r = q(
-               "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
-               `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
-               `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-               `contact`.`id` AS `cid`
-               FROM `item`
-               INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-               WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
-               AND `item`.`uid` = %d AND `item`.`verb` = '%s'
-               $sql_extra",
-               intval(api_user()),
-               dbesc(ACTIVITY_POST),
-               intval($id)
-       );
+       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
        /// @TODO How about copying this to above methods which don't check $r ?
-       if (!DBM::is_result($r)) {
+       if (!DBM::is_result($statuses)) {
                throw new BadRequestException("There is no status with this id.");
        }
 
-       $ret = api_format_items($r, $user_info, false, $type);
+       $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
 
        if ($conversation) {
                $data = ['status' => $ret];
@@ -2023,13 +1947,12 @@ api_register_func('api/statuses/show', 'api_statuses_show', true);
 function api_conversation_show($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
-       $user_info = api_get_user($a);
-
        // params
        $id = intval($a->argv[3]);
        $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
@@ -2053,48 +1976,35 @@ function api_conversation_show($type)
 
        logger('API: api_conversation_show: '.$id);
 
-       $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
-       if (DBM::is_result($r)) {
-               $id = $r[0]["parent"];
+       // try to fetch the item for the local user - or the public item, if there is no local one
+       $item = dba::selectFirst('item', ['parent-uri'], ['id' => $id]);
+       if (!DBM::is_result($item)) {
+               throw new BadRequestException("There is no status with this id.");
        }
 
-       $sql_extra = '';
+       $parent = dba::selectFirst('item', ['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
+       if (!DBM::is_result($parent)) {
+               throw new BadRequestException("There is no status with this id.");
+       }
+
+       $id = $parent['id'];
+
+       $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `verb` = ? AND `item`.`id` > ?",
+               $id, api_user(), ACTIVITY_POST, $since_id];
 
        if ($max_id > 0) {
-               $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
+               $condition[0] .= " AND `item`.`id` <= ?";
+               $condition[] = $max_id;
        }
 
-       // Not sure why this query was so complicated. We should keep it here for a while,
-       // just to make sure that we really don't need it.
-       //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
-       //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
-
-       $r = q(
-               "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
-               `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
-               `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-               `contact`.`id` AS `cid`
-               FROM `item`
-               STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-               WHERE `item`.`parent` = %d AND `item`.`visible`
-               AND NOT `item`.`moderated` AND NOT `item`.`deleted`
-               AND `item`.`uid` = %d AND `item`.`verb` = '%s'
-               AND `item`.`id`>%d $sql_extra
-               ORDER BY `item`.`id` DESC LIMIT %d ,%d",
-               intval($id),
-               intval(api_user()),
-               dbesc(ACTIVITY_POST),
-               intval($since_id),
-               intval($start),
-               intval($count)
-       );
+       $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
-       if (!DBM::is_result($r)) {
-               throw new BadRequestException("There is no status with this id.");
+       if (!DBM::is_result($statuses)) {
+               throw new BadRequestException("There is no status with id $id.");
        }
 
-       $ret = api_format_items($r, $user_info, false, $type);
+       $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
 
        $data = ['status' => $ret];
        return api_format_data("statuses", $type, $data);
@@ -2137,30 +2047,17 @@ function api_statuses_repeat($type)
 
        logger('API: api_statuses_repeat: '.$id);
 
-       $r = q(
-               "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
-               `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
-               `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-               `contact`.`id` AS `cid`
-               FROM `item`
-               INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-               WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
-               AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
-               AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
-               AND `item`.`id`=%d",
-               intval($id)
-       );
+       $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
+       $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
 
-       /// @TODO other style than above functions!
-       if (DBM::is_result($r) && $r[0]['body'] != "") {
-               if (strpos($r[0]['body'], "[/share]") !== false) {
-                       $pos = strpos($r[0]['body'], "[share");
-                       $post = substr($r[0]['body'], $pos);
+       if (DBM::is_result($item) && $item['body'] != "") {
+               if (strpos($item['body'], "[/share]") !== false) {
+                       $pos = strpos($item['body'], "[share");
+                       $post = substr($item['body'], $pos);
                } else {
-                       $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
+                       $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
 
-                       $post .= $r[0]['body'];
+                       $post .= $item['body'];
                        $post .= "[/share]";
                }
                $_REQUEST['body'] = $post;
@@ -2178,7 +2075,7 @@ function api_statuses_repeat($type)
        }
 
        // this should output the last post (the one we just posted).
-       $called_api = null;
+       $called_api = [];
        return api_status_show($type);
 }
 
@@ -2218,7 +2115,7 @@ function api_statuses_destroy($type)
 
        $ret = api_statuses_show($type);
 
-       Item::deleteById($id);
+       Item::deleteForUser(['id' => $id], api_user());
 
        return $ret;
 }
@@ -2236,8 +2133,9 @@ api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METH
 function api_statuses_mentions($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
@@ -2247,9 +2145,7 @@ function api_statuses_mentions($type)
        unset($_REQUEST["screen_name"]);
        unset($_GET["screen_name"]);
 
-       $user_info = api_get_user($a);
-       // get last newtork messages
-
+       // get last network messages
 
        // params
        $since_id = defaults($_REQUEST, 'since_id', 0);
@@ -2262,43 +2158,19 @@ function api_statuses_mentions($type)
 
        $start = ($page - 1) * $count;
 
-       // Ugly code - should be changed
-       $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
-       $myurl = substr($myurl, strpos($myurl, '://') + 3);
-       $myurl = str_replace('www.', '', $myurl);
-
-       $sql_extra = '';
+       $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `author-id` != ?
+               AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = ? AND `mention` AND NOT `ignored`)",
+               api_user(), ACTIVITY_POST, $since_id, $user_info['pid'], api_user()];
 
        if ($max_id > 0) {
-               $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
+               $condition[0] .= " AND `item`.`id` <= ?";
+               $condition[] = $max_id;
        }
 
-       $r = q(
-               "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
-               `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
-               `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-               `contact`.`id` AS `cid`
-               FROM `item` FORCE INDEX (`uid_id`)
-               STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-               WHERE `item`.`uid` = %d AND `verb` = '%s'
-               AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
-               AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
-               AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
-               $sql_extra
-               AND `item`.`id`>%d
-               ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
-               intval(api_user()),
-               dbesc(ACTIVITY_POST),
-               dbesc(protect_sprintf($myurl)),
-               dbesc(protect_sprintf($myurl)),
-               intval(api_user()),
-               intval($since_id),
-               intval($start),
-               intval($count)
-       );
+       $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
-       $ret = api_format_items($r, $user_info, false, $type);
+       $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
 
        $data = ['status' => $ret];
        switch ($type) {
@@ -2328,13 +2200,12 @@ api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
 function api_statuses_user_timeline($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
-       $user_info = api_get_user($a);
-
        logger(
                "api_statuses_user_timeline: api_user: ". api_user() .
                        "\nuser_info: ".print_r($user_info, true) .
@@ -2355,46 +2226,31 @@ function api_statuses_user_timeline($type)
        }
        $start = ($page - 1) * $count;
 
-       $sql_extra = '';
+       $condition = ["`uid` = ? AND `verb` = ? AND `item`.`id` > ? AND `item`.`contact-id` = ?",
+               api_user(), ACTIVITY_POST, $since_id, $user_info['cid']];
+
        if ($user_info['self'] == 1) {
-               $sql_extra .= " AND `item`.`wall` = 1 ";
+               $condition[0] .= ' AND `item`.`wall` ';
        }
 
        if ($exclude_replies > 0) {
-               $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
+               $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
        }
 
        if ($conversation_id > 0) {
-               $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
+               $condition[0] .= " AND `item`.`parent` = ?";
+               $condition[] = $conversation_id;
        }
 
        if ($max_id > 0) {
-               $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
+               $condition[0] .= " AND `item`.`id` <= ?";
+               $condition[] = $max_id;
        }
 
-       $r = q(
-               "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
-               `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
-               `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-               `contact`.`id` AS `cid`
-               FROM `item` FORCE INDEX (`uid_contactid_id`)
-               STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-               WHERE `item`.`uid` = %d AND `verb` = '%s'
-               AND `item`.`contact-id` = %d
-               AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
-               $sql_extra
-               AND `item`.`id` > %d
-               ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
-               intval(api_user()),
-               dbesc(ACTIVITY_POST),
-               intval($user_info['cid']),
-               intval($since_id),
-               intval($start),
-               intval($count)
-       );
+       $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
-       $ret = api_format_items($r, $user_info, true, $type);
+       $ret = api_format_items(dba::inArray($statuses), $user_info, true, $type);
 
        $data = ['status' => $ret];
        switch ($type) {
@@ -2444,24 +2300,24 @@ function api_favorites_create_destroy($type)
                $itemid = intval($_REQUEST['id']);
        }
 
-       $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
+       $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
 
-       if (!DBM::is_result($item) || count($item) == 0) {
+       if (!DBM::is_result($item)) {
                throw new BadRequestException("Invalid item.");
        }
 
        switch ($action) {
                case "create":
-                       $item[0]['starred'] = 1;
+                       $item['starred'] = 1;
                        break;
                case "destroy":
-                       $item[0]['starred'] = 0;
+                       $item['starred'] = 0;
                        break;
                default:
                        throw new BadRequestException("Invalid action ".$action);
        }
 
-       $r = Item::update(['starred' => $item[0]['starred']], ['id' => $itemid]);
+       $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
 
        if ($r === false) {
                throw new InternalServerErrorException("DB error");
@@ -2469,7 +2325,7 @@ function api_favorites_create_destroy($type)
 
 
        $user_info = api_get_user($a);
-       $rets = api_format_items($item, $user_info, false, $type);
+       $rets = api_format_items([$item], $user_info, false, $type);
        $ret = $rets[0];
 
        $data = ['status' => $ret];
@@ -2498,15 +2354,14 @@ function api_favorites($type)
        global $called_api;
 
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
 
        $called_api = [];
 
-       $user_info = api_get_user($a);
-
        // in friendica starred item are private
        // return favorites only for self
        logger('api_favorites: self:' . $user_info['self']);
@@ -2514,8 +2369,6 @@ function api_favorites($type)
        if ($user_info['self'] == 0) {
                $ret = [];
        } else {
-               $sql_extra = "";
-
                // params
                $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
                $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
@@ -2527,31 +2380,19 @@ function api_favorites($type)
 
                $start = $page*$count;
 
+               $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `starred`",
+                       api_user(), ACTIVITY_POST, $since_id];
+
+               $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+
                if ($max_id > 0) {
-                       $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
+                       $condition[0] .= " AND `item`.`id` <= ?";
+                       $condition[] = $max_id;
                }
 
-               $r = q(
-                       "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
-                       `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
-                       `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-                       `contact`.`id` AS `cid`
-                       FROM `item`, `contact`
-                       WHERE `item`.`uid` = %d
-                       AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
-                       AND `item`.`starred` = 1
-                       AND `contact`.`id` = `item`.`contact-id`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-                       $sql_extra
-                       AND `item`.`id`>%d
-                       ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
-                       intval(api_user()),
-                       intval($since_id),
-                       intval($start),
-                       intval($count)
-               );
+               $statuses = Item::selectForUser(api_user(), [], $condition, $params);
 
-               $ret = api_format_items($r, $user_info, false, $type);
+               $ret = api_format_items(dba::inArray($statuses), $user_info, false, $type);
        }
 
        $data = ['status' => $ret];
@@ -2605,10 +2446,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(html2plain(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, 2, true), 0));
                }
        } else {
-               $ret['text'] = $item['title'] . "\n" . html2plain(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, 2, true), 0);
        }
        if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
                unset($ret['sender']);
@@ -2631,7 +2472,7 @@ function api_convert_item($item)
 
        // Workaround for ostatus messages where the title is identically to the body
        $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
-       $statusbody = trim(html2plain($html, 0));
+       $statusbody = trim(HTML::toPlaintext($html, 0));
 
        // handle data: images
        $statusbody = api_format_items_embeded_images($item, $statusbody);
@@ -2697,7 +2538,7 @@ function api_convert_item($item)
  *
  * @param string $body
  *
- * @return array|false
+ * @return array
  */
 function api_get_attachments(&$body)
 {
@@ -2708,7 +2549,7 @@ function api_get_attachments(&$body)
        $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
 
        if (!$ret) {
-               return false;
+               return [];
        }
 
        $attachments = [];
@@ -2966,8 +2807,8 @@ function api_format_items_activities(&$item, $type = "json")
        ];
 
        $items = q(
-               'SELECT * FROM item
-                       WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
+               'SELECT * FROM `item`
+                       WHERE `uid` = %d AND `thr-parent` = "%s" AND `visible` AND NOT `deleted`',
                intval($item['uid']),
                dbesc($item['uri'])
        );
@@ -2977,7 +2818,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, $i['author-link']);
+               $user = api_get_user($a, $i['author-id']);
                switch ($i['verb']) {
                        case ACTIVITY_LIKE:
                                $activities['like'][] = $user;
@@ -3133,26 +2974,18 @@ function api_format_items($r, $user_info, $filter_user = false, $type = "json")
                        $status["entities"] = $converted["entities"];
                }
 
-               if (($item['item_network'] != "") && ($status["source"] == 'web')) {
-                       $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
-               } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
-                       $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
+               if ($status["source"] == 'web') {
+                       $status["source"] = ContactSelector::networkToName($item['network'], $user_info['url']);
+               } elseif (ContactSelector::networkToName($item['network'], $user_info['url']) != $status["source"]) {
+                       $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $user_info['url']).')');
                }
 
-
-               // Retweets are only valid for top postings
-               // It doesn't work reliable with the link if its a feed
-               //$IsRetweet = ($item['owner-link'] != $item['author-link']);
-               //if ($IsRetweet)
-               //      $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
-
-
                if ($item["id"] == $item["parent"]) {
                        $retweeted_item = api_share_as_retweet($item);
                        if ($retweeted_item !== false) {
                                $retweeted_status = $status;
                                try {
-                                       $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
+                                       $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
                                } catch (BadRequestException $e) {
                                        // user not found. should be found?
                                        /// @todo check if the user should be always found
@@ -3247,12 +3080,14 @@ function api_help_test($type)
 api_register_func('api/help/test', 'api_help_test', false);
 
 /**
+ * Returns all lists the user subscribes to.
  *
  * @param string $type Return type (atom, rss, xml, json)
  *
  * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
  */
-function api_lists($type)
+function api_lists_list($type)
 {
        $ret = [];
        /// @TODO $ret is not filled here?
@@ -3260,25 +3095,126 @@ function api_lists($type)
 }
 
 /// @TODO move to top of file or somewhere better
-api_register_func('api/lists', 'api_lists', true);
+api_register_func('api/lists/list', 'api_lists_list', true);
+api_register_func('api/lists/subscriptions', 'api_lists_list', true);
 
 /**
- * Returns all lists the user subscribes to.
+ * Returns all groups the user owns.
  *
  * @param string $type Return type (atom, rss, xml, json)
  *
  * @return array|string
- * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
  */
-function api_lists_list($type)
+function api_lists_ownerships($type)
 {
-       $ret = [];
-       /// @TODO $ret is not filled here?
-       return api_format_data('lists', $type, ["lists_list" => $ret]);
+       $a = get_app();
+
+       if (api_user() === false) {
+               throw new ForbiddenException();
+       }
+
+       // params
+       $user_info = api_get_user($a);
+       $uid = $user_info['uid'];
+
+       $groups = dba::select('group', [], ['deleted' => 0, 'uid' => $uid]);
+
+       // loop through all groups
+       $lists = [];
+       foreach ($groups as $group) {
+               if ($group['visible']) {
+                       $mode = 'public';
+               } else {
+                       $mode = 'private';
+               }
+               $lists[] = [
+                       'name' => $group['name'],
+                       'id' => intval($group['id']),
+                       'id_str' => (string) $group['id'],
+                       'user' => $user_info,
+                       'mode' => $mode
+               ];
+       }
+       return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
 }
 
 /// @TODO move to top of file or somewhere better
-api_register_func('api/lists/list', 'api_lists_list', true);
+api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
+
+/**
+ * Returns recent statuses from users in the specified group.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
+ */
+function api_lists_statuses($type)
+{
+       $a = get_app();
+
+       $user_info = api_get_user($a);
+       if (api_user() === false || $user_info === false) {
+               throw new ForbiddenException();
+       }
+
+       unset($_REQUEST["user_id"]);
+       unset($_GET["user_id"]);
+
+       unset($_REQUEST["screen_name"]);
+       unset($_GET["screen_name"]);
+
+       if (empty($_REQUEST['list_id'])) {
+               throw new BadRequestException('list_id not specified');
+       }
+
+       // params
+       $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
+       $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
+       if ($page < 0) {
+               $page = 0;
+       }
+       $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
+       $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
+       $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
+       $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
+
+       $start = $page * $count;
+
+       $condition = ["`uid` = ? AND `verb` = ? AND `id` > ? AND `group_member`.`gid` = ?",
+               api_user(), ACTIVITY_POST, $since_id, $_REQUEST['list_id']];
+
+       if ($max_id > 0) {
+               $condition[0] .= " AND `item`.`id` <= ?";
+               $condition[] = $max_id;
+       }
+       if ($exclude_replies > 0) {
+               $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
+       }
+       if ($conversation_id > 0) {
+               $condition[0] .= " AND `item`.`parent` = ?";
+               $condition[] = $conversation_id;
+       }
+
+       $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
+       $statuses = Item::selectForUser(api_user(), [], $condition, $params);
+
+       $items = api_format_items(dba::inArray($statuses), $user_info, false, $type);
+
+       $data = ['status' => $items];
+       switch ($type) {
+               case "atom":
+               case "rss":
+                       $data = api_rss_extra($a, $data, $user_info);
+                       break;
+       }
+
+       return api_format_data("statuses", $type, $data);
+}
+
+/// @TODO move to top of file or somewhere better
+api_register_func('api/lists/statuses', 'api_lists_statuses', true);
 
 /**
  * Considers friends and followers lists to be private and won't return
@@ -3678,7 +3614,7 @@ api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, AP
  * @brief delete a direct_message from mail table through api
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
  * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
  */
 function api_direct_messages_destroy($type)
@@ -3764,11 +3700,9 @@ api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy',
 function api_direct_messages_box($type, $box, $verbose)
 {
        $a = get_app();
-
        if (api_user() === false) {
                throw new ForbiddenException();
        }
-
        // params
        $count = (x($_GET, 'count') ? $_GET['count'] : 20);
        $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
@@ -3790,6 +3724,9 @@ function api_direct_messages_box($type, $box, $verbose)
        unset($_GET["screen_name"]);
 
        $user_info = api_get_user($a);
+       if ($user_info === false) {
+               throw new ForbiddenException();
+       }
        $profile_url = $user_info["url"];
 
        // pagination
@@ -3840,7 +3777,9 @@ function api_direct_messages_box($type, $box, $verbose)
                        $sender = $user_info;
                }
 
-               $ret[] = api_format_messages($item, $recipient, $sender);
+               if (isset($recipient) && isset($sender)) {
+                       $ret[] = api_format_messages($item, $recipient, $sender);
+               }
        }
 
 
@@ -3958,7 +3897,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
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
  */
 function api_fr_photoalbum_delete($type)
 {
@@ -3994,7 +3933,7 @@ function api_fr_photoalbum_delete($type)
                if (!DBM::is_result($photo_item)) {
                        throw new InternalServerErrorException("problem with deleting items occured");
                }
-               Item::deleteById($photo_item[0]['id']);
+               Item::deleteForUser(['id' => $photo_item[0]['id']], api_user());
        }
 
        // now let's delete all photos from the album
@@ -4013,7 +3952,7 @@ function api_fr_photoalbum_delete($type)
  * @brief 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
+ * @return string|array
  */
 function api_fr_photoalbum_update($type)
 {
@@ -4032,21 +3971,11 @@ function api_fr_photoalbum_update($type)
                throw new BadRequestException("no new albumname specified");
        }
        // check if album is existing
-       $r = q(
-               "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
-               intval(api_user()),
-               dbesc($album)
-       );
-       if (!DBM::is_result($r)) {
+       if (!dba::exists('photo', ['uid' => api_user(), 'album' => $album])) {
                throw new BadRequestException("album not available");
        }
        // now let's update all photos to the albumname
-       $result = q(
-               "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
-               dbesc($album_new),
-               intval(api_user()),
-               dbesc($album)
-       );
+       $result = dba::update('photo', ['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
 
        // return success of updating or error message
        if ($result) {
@@ -4062,7 +3991,7 @@ function api_fr_photoalbum_update($type)
  * @brief list all photos of the authenticated user
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
  */
 function api_fr_photos_list($type)
 {
@@ -4108,7 +4037,7 @@ function api_fr_photos_list($type)
  * @brief upload a new photo or change an existing photo
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
  */
 function api_fr_photo_create_update($type)
 {
@@ -4251,12 +4180,11 @@ function api_fr_photo_create_update($type)
        throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
 }
 
-
 /**
  * @brief delete a single photo from the database through api
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
  */
 function api_fr_photo_delete($type)
 {
@@ -4297,7 +4225,7 @@ function api_fr_photo_delete($type)
                }
                // 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::deleteById($photo_item[0]['id']);
+               Item::deleteForUser(['id' => $photo_item[0]['id']], 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]);
@@ -4339,7 +4267,7 @@ function api_fr_photo_detail($type)
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  *
- * @return string
+ * @return string|array
  * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
  */
 function api_account_update_profile_image($type)
@@ -4348,7 +4276,7 @@ function api_account_update_profile_image($type)
                throw new ForbiddenException();
        }
        // input params
-       $profileid = defaults($_REQUEST, 'profile_id', 0);
+       $profile_id = defaults($_REQUEST, 'profile_id', 0);
 
        // error if image data is missing
        if (!x($_FILES, 'image')) {
@@ -4356,17 +4284,13 @@ function api_account_update_profile_image($type)
        }
 
        // check if specified profile id is valid
-       if ($profileid != 0) {
-               $r = q(
-                       "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
-                       intval(api_user()),
-                       intval($profileid)
-               );
+       if ($profile_id != 0) {
+               $profile = dba::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
                // error message if specified profile id is not in database
-               if (!DBM::is_result($r)) {
+               if (!DBM::is_result($profile)) {
                        throw new BadRequestException("profile_id not available");
                }
-               $is_default_profile = $r['profile'];
+               $is_default_profile = $profile['is-default'];
        } else {
                $is_default_profile = 1;
        }
@@ -4391,43 +4315,23 @@ function api_account_update_profile_image($type)
                $fileext = "jpg";
        } elseif ($filetype == "image/png") {
                $fileext = "png";
+       } else {
+               throw new InternalServerErrorException('Unsupported filetype');
        }
+
        // change specified profile or all profiles to the new resource-id
        if ($is_default_profile) {
-               q(
-                       "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
-                       dbesc($data['photo']['id']),
-                       intval(local_user())
-               );
-
-               q(
-                       "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s'  WHERE `self` AND `uid` = %d",
-                       dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
-                       dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
-                       dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
-                       intval(local_user())
-               );
+               $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
+               dba::update('photo', ['profile' => false], $condition);
        } else {
-               q(
-                       "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
-                       dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
-                       dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
-                       intval($_REQUEST['profile']),
-                       intval(local_user())
-               );
+               $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype,
+                       'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype];
+               dba::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
        }
 
-       // we'll set the updated profile-photo timestamp even if it isn't the default profile,
-       // so that browsers will do a cache update unconditionally
-
-       q(
-               "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
-               dbesc(DateTimeFormat::utcNow()),
-               intval(local_user())
-       );
+       Contact::updateSelfFromUserID(api_user(), true);
 
        // Update global directory in background
-       //$user = api_get_user(get_app());
        $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
        if ($url && strlen(Config::get('system', 'directory'))) {
                Worker::add(PRIORITY_LOW, "Directory", $url);
@@ -4671,7 +4575,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
                logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
        }
 
-       if ($r) {
+       if (isset($r) && $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($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
@@ -4696,7 +4600,7 @@ 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_new_uri(get_app()->get_hostname(), intval(api_user()));
+       $uri = Item::newURI(intval(api_user()));
        $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
 
        $arr = [];
@@ -4747,6 +4651,13 @@ 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();
+       $user_info = api_get_user($a);
+
+       if ($user_info === false) {
+               throw new ForbiddenException();
+       }
+
        $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
        $data_sql = ($scale === false ? "" : "data, ");
 
@@ -4810,24 +4721,13 @@ function prepare_photo_data($type, $scale, $photo_id)
        $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
 
        // retrieve comments on photo
-       $r = q(
-               "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
-               `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
-               `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-               `contact`.`id` AS `cid`
-               FROM `item`
-               STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-               WHERE `item`.`parent` = %d AND `item`.`visible`
-               AND NOT `item`.`moderated` AND NOT `item`.`deleted`
-               AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
-               intval($item[0]['parent']),
-               intval(api_user()),
-               dbesc(ACTIVITY_POST)
-       );
+       $condition = ["`parent` = ? AND `uid` = ? AND (`verb` = ? OR `type`='photo')",
+               $item[0]['parent'], api_user(), ACTIVITY_POST];
+
+       $statuses = Item::selectForUser(api_user(), [], $condition);
 
        // prepare output of comments
-       $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
+       $commentData = api_format_items(dba::inArray($statuses), $user_info, false, $type);
        $comments = [];
        if ($type == "xml") {
                $k = 0;
@@ -4897,15 +4797,9 @@ function api_friendica_remoteauth()
 
        $sec = random_string();
 
-       q(
-               "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
-               VALUES( %d, %s, '%s', '%s', %d )",
-               intval(api_user()),
-               intval($cid),
-               dbesc($dfrn_id),
-               dbesc($sec),
-               intval(time() + 45)
-       );
+       $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
+               'sec' => $sec, 'expire' => time() + 45];
+       dba::insert('profile_check', $fields);
 
        logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
        $dest = ($url ? '&destination_url=' . $url : '');
@@ -5134,7 +5028,7 @@ function api_in_reply_to($item)
                $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
 
                $r = q(
-                       "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
+                       "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM `item`
                        STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
                        WHERE `item`.`id` = %d LIMIT 1",
                        intval($in_reply_to['status_id'])
@@ -5168,27 +5062,27 @@ function api_in_reply_to($item)
 
 /**
  *
- * @param string $Text
+ * @param string $text
  *
  * @return string
  */
-function api_clean_plain_items($Text)
+function api_clean_plain_items($text)
 {
        $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
 
-       $Text = BBCode::cleanPictureLinks($Text);
+       $text = BBCode::cleanPictureLinks($text);
        $URLSearchString = "^\[\]";
 
-       $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
+       $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
 
        if ($include_entities == "true") {
-               $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
+               $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
        }
 
        // Simplify "attachment" element
-       $Text = api_clean_attachments($Text);
+       $text = api_clean_attachments($text);
 
-       return($Text);
+       return $text;
 }
 
 /**
@@ -5202,7 +5096,7 @@ function api_clean_attachments($body)
 {
        $data = BBCode::getAttachmentData($body);
 
-       if (!$data) {
+       if (empty($data)) {
                return $body;
        }
        $body = "";
@@ -5328,6 +5222,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']);
                $users = [];
@@ -5414,15 +5309,15 @@ function api_friendica_group_delete($type)
 }
 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
 
-
 /**
- * Create the specified group with the posted array of contacts.
+ * Delete a group.
  *
  * @param string $type Return type (atom, rss, xml, json)
  *
  * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
  */
-function api_friendica_group_create($type)
+function api_lists_destroy($type)
 {
        $a = get_app();
 
@@ -5432,11 +5327,45 @@ function api_friendica_group_create($type)
 
        // params
        $user_info = api_get_user($a);
-       $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
+       $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
        $uid = $user_info['uid'];
-       $json = json_decode($_POST['json'], true);
-       $users = $json['user'];
 
+       // error if no gid specified
+       if ($gid == 0) {
+               throw new BadRequestException('gid not specified');
+       }
+
+       // get data of the specified group id
+       $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
+       // error message if specified gid is not in database
+       if (!$group) {
+               throw new BadRequestException('gid not available');
+       }
+
+       if (Group::remove($gid)) {
+               $list = [
+                       'name' => $group['name'],
+                       'id' => intval($gid),
+                       'id_str' => (string) $gid,
+                       'user' => $user_info
+               ];
+
+               return api_format_data("lists", $type, ['lists' => $list]);
+       }
+}
+api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
+
+/**
+ * Add a new group to the database.
+ *
+ * @param  string $name  Group name
+ * @param  int   $uid   User ID
+ * @param  array  $users List of users to add to the group
+ *
+ * @return array
+ */
+function group_create($name, $uid, $users = [])
+{
        // error if no name specified
        if ($name == "") {
                throw new BadRequestException('group name not specified');
@@ -5492,12 +5421,73 @@ function api_friendica_group_create($type)
        }
 
        // return success message incl. missing users in array
-       $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
-       $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
+       $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
+
+       return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
+}
+
+/**
+ * Create the specified group with the posted array of contacts.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ */
+function api_friendica_group_create($type)
+{
+       $a = get_app();
+
+       if (api_user() === false) {
+               throw new ForbiddenException();
+       }
+
+       // params
+       $user_info = api_get_user($a);
+       $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
+       $uid = $user_info['uid'];
+       $json = json_decode($_POST['json'], true);
+       $users = $json['user'];
+
+       $success = group_create($name, $uid, $users);
+
        return api_format_data("group_create", $type, ['result' => $success]);
 }
 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
 
+/**
+ * Create a new group.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
+ */
+function api_lists_create($type)
+{
+       $a = get_app();
+
+       if (api_user() === false) {
+               throw new ForbiddenException();
+       }
+
+       // params
+       $user_info = api_get_user($a);
+       $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
+       $uid = $user_info['uid'];
+
+       $success = group_create($name, $uid);
+       if ($success['success']) {
+               $grp = [
+                       'name' => $success['name'],
+                       'id' => intval($success['gid']),
+                       'id_str' => (string) $success['gid'],
+                       'user' => $user_info
+               ];
+
+               return api_format_data("lists", $type, ['lists'=>$grp]);
+       }
+}
+api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
 
 /**
  * Update the specified group with the posted array of contacts.
@@ -5539,7 +5529,7 @@ function api_friendica_group_update($type)
                foreach ($users as $user) {
                        $found = ($user['cid'] == $cid ? true : false);
                }
-               if (!$found) {
+               if (!isset($found) || !$found) {
                        Group::removeMemberByName($uid, $name, $cid);
                }
        }
@@ -5572,6 +5562,54 @@ function api_friendica_group_update($type)
 
 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
 
+/**
+ * Update information about a group.
+ *
+ * @param string $type Return type (atom, rss, xml, json)
+ *
+ * @return array|string
+ * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
+ */
+function api_lists_update($type)
+{
+       $a = get_app();
+
+       if (api_user() === false) {
+               throw new ForbiddenException();
+       }
+
+       // params
+       $user_info = api_get_user($a);
+       $gid = (x($_REQUEST, 'list_id') ? $_REQUEST['list_id'] : 0);
+       $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
+       $uid = $user_info['uid'];
+
+       // error if no gid specified
+       if ($gid == 0) {
+               throw new BadRequestException('gid not specified');
+       }
+
+       // get data of the specified group id
+       $group = dba::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
+       // error message if specified gid is not in database
+       if (!$group) {
+               throw new BadRequestException('gid not available');
+       }
+
+       if (Group::update($gid, $name)) {
+               $list = [
+                       'name' => $name,
+                       'id' => intval($gid),
+                       'id_str' => (string) $gid,
+                       'user' => $user_info
+               ];
+
+               return api_format_data("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)
@@ -5620,7 +5658,7 @@ api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activit
  * @brief Returns notifications
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
 */
 function api_friendica_notification($type)
 {
@@ -5654,13 +5692,14 @@ function api_friendica_notification($type)
  * @brief Set notification as seen and returns associated item (if possible)
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string
+ * @return string|array
  */
 function api_friendica_notification_seen($type)
 {
        $a = get_app();
+       $user_info = api_get_user($a);
 
-       if (api_user() === false) {
+       if (api_user() === false || $user_info === false) {
                throw new ForbiddenException();
        }
        if ($a->argc!==4) {
@@ -5678,15 +5717,10 @@ function api_friendica_notification_seen($type)
        $nm->setSeen($note);
        if ($note['otype']=='item') {
                // would be really better with an ItemsManager and $im->getByID() :-P
-               $r = q(
-                       "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
-                       intval($note['iid']),
-                       intval(local_user())
-               );
-               if ($r!==false) {
+               $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
+               if (DBM::is_result($$item)) {
                        // we found the item, return it to the user
-                       $user_info = api_get_user($a);
-                       $ret = api_format_items($r, $user_info, false, $type);
+                       $ret = api_format_items([$item], $user_info, false, $type);
                        $data = ['status' => $ret];
                        return api_format_data("status", $type, $data);
                }
@@ -5703,7 +5737,7 @@ api_register_func('api/friendica/notification', 'api_friendica_notification', tr
  * @brief update a direct_message to seen state
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
- * @return string (success result=ok, error result=error with error message)
+ * @return string|array (success result=ok, error result=error with error message)
  */
 function api_friendica_direct_messages_setseen($type)
 {
@@ -5723,25 +5757,14 @@ function api_friendica_direct_messages_setseen($type)
                return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
        }
 
-       // get data of the specified message id
-       $r = q(
-               "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
-               intval($id),
-               intval($uid)
-       );
-
        // error message if specified id is not in database
-       if (!DBM::is_result($r)) {
+       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 = q(
-               "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
-               intval($id),
-               intval($uid)
-       );
+       $result = dba::update('mail', ['seen' => true], ['id' => $id]);
 
        if ($result) {
                // return success
@@ -5761,7 +5784,7 @@ api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct
  *
  * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
  * @param string $box
- * @return string (success: success=true if found and search_result contains found messages,
+ * @return string|array (success: success=true if found and search_result contains found messages,
  *                          success=false if nothing was found, search_result='nothing found',
  *                error: result=error with error message)
  */
@@ -5809,7 +5832,9 @@ function api_friendica_direct_messages_search($type, $box = "")
                                $sender = $user_info;
                        }
 
-                       $ret[] = api_format_messages($item, $recipient, $sender);
+                       if (isset($recipient) && isset($sender)) {
+                               $ret[] = api_format_messages($item, $recipient, $sender);
+                       }
                }
                $success = ['success' => true, 'search_results' => $ret];
        }
@@ -5824,7 +5849,7 @@ api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_
  * @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
+ * @return string|array
  */
 function api_friendica_profile_show($type)
 {
@@ -5835,18 +5860,18 @@ function api_friendica_profile_show($type)
        }
 
        // input params
-       $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
+       $profile_id = (x($_REQUEST, '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 ($profileid != 0) {
+       if ($profile_id != 0) {
                $r = q(
                        "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
                        intval(api_user()),
-                       intval($profileid)
+                       intval($profile_id)
                );
 
                // error message if specified gid is not in database
@@ -5861,19 +5886,20 @@ function api_friendica_profile_show($type)
        }
        // loop through all returned profiles and retrieve data and users
        $k = 0;
+       $profiles = [];
        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 = [];
-               $r = q(
+               $nurls = q(
                        "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
                        intval(api_user()),
                        intval($rr['profile_id'])
                );
 
-               foreach ($r as $rr) {
-                       $user = api_get_user($a, $rr['nurl']);
+               foreach ($nurls as $nurl) {
+                       $user = api_get_user($a, $nurl['nurl']);
                        ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
                }
                $profile['users'] = $users;