X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=include%2Fapi.php;h=e0cac831e5644b7fe492e5b55fde4de4402cd43a;hb=0bb169b4edc09a99d14fa9105412c114b1bcc6f6;hp=bcf14d6a829603e38054331a762f81bb08a46655;hpb=199f72ee3cd3c2ef7edfafa1d5a36a365bad93ad;p=friendica.git diff --git a/include/api.php b/include/api.php index bcf14d6a82..e0cac831e5 100644 --- a/include/api.php +++ b/include/api.php @@ -1,6 +1,6 @@ user@server, ignoring server part * * @param App $a App @@ -188,6 +190,8 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY */ function api_login(App $a) { + $_SESSION["allow_api"] = false; + // workaround for HTTP-auth in CGI mode if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) { $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)); @@ -199,24 +203,6 @@ function api_login(App $a) } if (empty($_SERVER['PHP_AUTH_USER'])) { - // Try OAuth when no user is provided - $oauth1 = new FKOAuth1(); - // login with oauth - try { - $request = OAuthRequest::from_request(); - list($consumer, $token) = $oauth1->verify_request($request); - if (!is_null($token)) { - $oauth1->loginUser($token->uid); - Session::set('allow_api', true); - return; - } - echo __FILE__.__LINE__.__FUNCTION__ . "
"; - var_dump($consumer, $token); - die(); - } catch (Exception $e) { - Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]); - } - Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]); header('WWW-Authenticate: Basic realm="Friendica"'); throw new UnauthorizedException("This API requires login"); @@ -248,7 +234,7 @@ function api_login(App $a) */ Hook::callAll('authenticate', $addon_auth); - if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) { + if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) { $record = $addon_auth['user_record']; } else { $user_id = User::authenticate(trim($user), trim($password), true); @@ -272,7 +258,7 @@ function api_login(App $a) $_SESSION["allow_api"] = true; - Hook::callAll('logged_in', $a->user); + Hook::callAll('logged_in', $record); } /** @@ -336,7 +322,7 @@ function api_call(App $a, App\Arguments $args = null) if (!empty($info['auth']) && api_user() === false) { api_login($a); - Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]); + Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]); } Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]); @@ -559,10 +545,10 @@ function api_get_user(App $a, $contact_id = null) } // $called_api is the API path exploded on / and is expected to have at least 2 elements - if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) { + if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) { $argid = count($called_api); - if (!empty($a->argv[$argid])) { - $data = explode(".", $a->argv[$argid]); + if (!empty(DI::args()->getArgv()[$argid])) { + $data = explode(".", DI::args()->getArgv()[$argid]); if (count($data) > 1) { list($user, $null) = $data; } @@ -593,7 +579,7 @@ function api_get_user(App $a, $contact_id = null) api_login($a); return false; } else { - $user = $_SESSION['uid']; + $user = api_user(); $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` "; } } @@ -1022,7 +1008,7 @@ function api_statuses_mediap($type) $_REQUEST['profile_uid'] = api_user(); $_REQUEST['api_source'] = true; - $txt = requestdata('status'); + $txt = requestdata('status') ?? ''; /// @TODO old-lost code? //$txt = urldecode(requestdata('status')); @@ -1035,7 +1021,7 @@ function api_statuses_mediap($type) } $txt = HTML::toBBCode($txt); - $a->argv[1] = $user_info['screen_name']; //should be set to username? + DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username? $picture = wall_upload_post($a, false); @@ -1077,7 +1063,7 @@ function api_statuses_update($type) // convert $_POST array items to the form we use for web posts. if (requestdata('htmlstatus')) { - $txt = requestdata('htmlstatus'); + $txt = requestdata('htmlstatus') ?? ''; if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) { $txt = HTML::toBBCodeVideo($txt); @@ -1119,8 +1105,8 @@ function api_statuses_update($type) if ($throttle_day > 0) { $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60); - $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom]; - $posts_day = DBA::count('thread', $condition); + $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom]; + $posts_day = Post::count($condition); if ($posts_day > $throttle_day) { Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG); @@ -1133,8 +1119,8 @@ function api_statuses_update($type) if ($throttle_week > 0) { $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7); - $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom]; - $posts_week = DBA::count('thread', $condition); + $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom]; + $posts_week = Post::count($condition); if ($posts_week > $throttle_week) { Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG); @@ -1147,8 +1133,8 @@ function api_statuses_update($type) if ($throttle_month > 0) { $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30); - $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom]; - $posts_month = DBA::count('thread', $condition); + $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom]; + $posts_month = Post::count($condition); if ($posts_month > $throttle_month) { Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG); @@ -1158,30 +1144,56 @@ function api_statuses_update($type) } } - if (!empty($_FILES['media'])) { + if (requestdata('media_ids')) { + $ids = explode(',', requestdata('media_ids') ?? ''); + } elseif (!empty($_FILES['media'])) { // upload the image if we have one $picture = wall_upload_post($a, false); if (is_array($picture)) { - $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]"; + $ids[] = $picture['id']; } } - if (requestdata('media_ids')) { - $ids = explode(',', requestdata('media_ids')); + $attachments = []; + $ressources = []; + + if (!empty($ids)) { foreach ($ids as $id) { - $r = q( - "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1", - intval($id), - api_user() - ); - if (DBA::isResult($r)) { + $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo` + INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN + (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ? + ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user())); + + if (!empty($media)) { + $ressources[] = $media[0]['resource-id']; $phototypes = Images::supportedTypes(); - $ext = $phototypes[$r[0]['type']]; - $description = $r[0]['desc'] ?? ''; - $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']'; - $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]'; + $ext = $phototypes[$media[0]['type']]; + + $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'], + 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext, + 'size' => $media[0]['datasize'], + 'name' => $media[0]['filename'] ?: $media[0]['resource-id'], + 'description' => $media[0]['desc'] ?? '', + 'width' => $media[0]['width'], + 'height' => $media[0]['height']]; + + if (count($media) > 1) { + $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext; + $attachment['preview-width'] = $media[1]['width']; + $attachment['preview-height'] = $media[1]['height']; + } + $attachments[] = $attachment; } } + + // We have to avoid that the post is rejected because of an empty body + if (empty($_REQUEST['body'])) { + $_REQUEST['body'] = '[hr]'; + } + } + + if (!empty($attachments)) { + $_REQUEST['attachments'] = $attachments; } // set this so that the item_post() function is quiet and doesn't redirect or emit json @@ -1195,6 +1207,13 @@ function api_statuses_update($type) // call out normal post function $item_id = item_post($a); + if (!empty($ressources) && !empty($item_id)) { + $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]); + foreach ($ressources as $ressource) { + Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']); + } + } + // output the post that we just posted. return api_status_show($type, $item_id); } @@ -1732,16 +1751,16 @@ function api_statuses_public_timeline($type) $start = max(0, ($page - 1) * $count); if ($exclude_replies && !$conversation_id) { - $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`", - GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC]; + $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`", + GRAVITY_PARENT, $since_id, Item::PUBLIC]; if ($max_id > 0) { - $condition[0] .= " AND `iid` <= ?"; + $condition[0] .= " AND `id` <= ?"; $condition[] = $max_id; } - $params = ['order' => ['iid' => true], 'limit' => [$start, $count]]; - $statuses = Post::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params); + $params = ['order' => ['id' => true], 'limit' => [$start, $count]]; + $statuses = Post::selectForUser(api_user(), [], $condition, $params); $r = Post::toArray($statuses); } else { @@ -1811,18 +1830,18 @@ function api_statuses_networkpublic_timeline($type) $start = max(0, ($page - 1) * $count); - $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `iid` > ? AND `private` = ?", + $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?", GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC]; if ($max_id > 0) { - $condition[0] .= " AND `iid` <= ?"; + $condition[0] .= " AND `id` <= ?"; $condition[] = $max_id; } - $params = ['order' => ['iid' => true], 'limit' => [$start, $count]]; - $statuses = Post::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params); + $params = ['order' => ['id' => true], 'limit' => [$start, $count]]; + $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params)); - $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type); + $ret = api_format_items($statuses, $user_info, false, $type); bindComments($ret); @@ -1864,7 +1883,7 @@ function api_statuses_show($type) } // params - $id = intval($a->argv[3] ?? 0); + $id = intval(DI::args()->getArgv()[3] ?? 0); if ($id == 0) { $id = intval($_REQUEST['id'] ?? 0); @@ -1872,7 +1891,7 @@ function api_statuses_show($type) // Hotot workaround if ($id == 0) { - $id = intval($a->argv[4] ?? 0); + $id = intval(DI::args()->getArgv()[4] ?? 0); } Logger::log('API: api_statuses_show: ' . $id); @@ -1943,7 +1962,7 @@ function api_conversation_show($type) } // params - $id = intval($a->argv[3] ?? 0); + $id = intval(DI::args()->getArgv()[3] ?? 0); $since_id = intval($_REQUEST['since_id'] ?? 0); $max_id = intval($_REQUEST['max_id'] ?? 0); $count = intval($_REQUEST['count'] ?? 20); @@ -1957,7 +1976,7 @@ function api_conversation_show($type) // Hotot workaround if ($id == 0) { - $id = intval($a->argv[4] ?? 0); + $id = intval(DI::args()->getArgv()[4] ?? 0); } Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]); @@ -2026,7 +2045,7 @@ function api_statuses_repeat($type) api_get_user($a); // params - $id = intval($a->argv[3] ?? 0); + $id = intval(DI::args()->getArgv()[3] ?? 0); if ($id == 0) { $id = intval($_REQUEST['id'] ?? 0); @@ -2034,20 +2053,20 @@ function api_statuses_repeat($type) // Hotot workaround if ($id == 0) { - $id = intval($a->argv[4] ?? 0); + $id = intval(DI::args()->getArgv()[4] ?? 0); } Logger::log('API: api_statuses_repeat: '.$id); $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink']; $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]); - + if (DBA::isResult($item) && !empty($item['body'])) { if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) { if (!Item::performActivity($id, 'announce', local_user())) { throw new InternalServerErrorException(); } - + $item_id = $id; } else { if (strpos($item['body'], "[/share]") !== false) { @@ -2109,7 +2128,7 @@ function api_statuses_destroy($type) api_get_user($a); // params - $id = intval($a->argv[3] ?? 0); + $id = intval(DI::args()->getArgv()[3] ?? 0); if ($id == 0) { $id = intval($_REQUEST['id'] ?? 0); @@ -2117,7 +2136,7 @@ function api_statuses_destroy($type) // Hotot workaround if ($id == 0) { - $id = intval($a->argv[4] ?? 0); + $id = intval(DI::args()->getArgv()[4] ?? 0); } Logger::log('API: api_statuses_destroy: '.$id); @@ -2170,24 +2189,21 @@ function api_statuses_mentions($type) $start = max(0, ($page - 1) * $count); - $query = "`gravity` IN (?, ?) AND `id` IN (SELECT `iid` FROM `user-item` - WHERE (`hidden` IS NULL OR NOT `hidden`) AND - `uid` = ? AND `notification-type` & ? != 0 - AND `iid` > ?"; + $query = "`gravity` IN (?, ?) AND `uri-id` IN + (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`) + AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?"; $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(), - UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED | - UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT | - UserItem::NOTIF_DIRECT_THREAD_COMMENT, - $since_id]; + Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED | + Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT | + Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT, + api_user(), $since_id]; if ($max_id > 0) { - $query .= " AND `iid` <= ?"; + $query .= " AND `id` <= ?"; $condition[] = $max_id; } - $query .= ")"; - array_unshift($condition, $query); $params = ['order' => ['id' => true], 'limit' => [$start, $count]]; @@ -2266,7 +2282,6 @@ function api_statuses_user_timeline($type) $condition[0] .= " AND `id` <= ?"; $condition[] = $max_id; } - $params = ['order' => ['id' => true], 'limit' => [$start, $count]]; $statuses = Post::selectForUser(api_user(), [], $condition, $params); @@ -2314,16 +2329,16 @@ function api_favorites_create_destroy($type) // for versioned api. /// @TODO We need a better global soluton $action_argv_id = 2; - if (count($a->argv) > 1 && $a->argv[1] == "1.1") { + if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") { $action_argv_id = 3; } - if ($a->argc <= $action_argv_id) { + if (DI::args()->getArgc() <= $action_argv_id) { throw new BadRequestException("Invalid request."); } - $action = str_replace("." . $type, "", $a->argv[$action_argv_id]); - if ($a->argc == $action_argv_id + 2) { - $itemid = intval($a->argv[$action_argv_id + 1] ?? 0); + $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]); + if (DI::args()->getArgc() == $action_argv_id + 2) { + $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0); } else { $itemid = intval($_REQUEST['id'] ?? 0); } @@ -2489,12 +2504,12 @@ function api_format_messages($item, $recipient, $sender) if (!empty($_GET['getText'])) { $ret['title'] = $item['title']; if ($_GET['getText'] == 'html') { - $ret['text'] = BBCode::convert($item['body'], false); + $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API); } elseif ($_GET['getText'] == 'plain') { - $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0)); + $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0)); } } else { - $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0); + $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0); } if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') { unset($ret['sender']); @@ -2513,14 +2528,15 @@ function api_format_messages($item, $recipient, $sender) */ function api_convert_item($item) { - $body = $item['body']; - $entities = api_get_entitities($statustext, $body); + $body = api_add_attachments_to_body($item); + + $entities = api_get_entitities($statustext, $body, $item['uri-id']); // Add pictures to the attachment array and remove them from the body - $attachments = api_get_attachments($body); + $attachments = api_get_attachments($body, $item['uri-id']); // Workaround for ostatus messages where the title is identically to the body - $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true); + $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API); $statusbody = trim(HTML::toPlaintext($html, 0)); // handle data: images @@ -2538,7 +2554,7 @@ function api_convert_item($item) $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? ''); } - $statushtml = BBCode::convert(BBCode::removeAttachment($body), false); + $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API); // Workaround for clients with limited HTML parser functionality $search = ["
", "", "", @@ -2552,7 +2568,7 @@ function api_convert_item($item) $statushtml = str_replace($search, $replace, $statushtml); if ($item['title'] != "") { - $statushtml = "" . BBCode::convert($item['title']) . "
" . $statushtml; + $statushtml = "" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "
" . $statushtml; } do { @@ -2570,7 +2586,7 @@ function api_convert_item($item) // feeds without body should contain the link if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) { - $statushtml .= BBCode::convert($item['plink']); + $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']); } return [ @@ -2581,14 +2597,43 @@ function api_convert_item($item) ]; } +/** + * Add media attachments to the body + * + * @param array $item + * @return string body with added media + */ +function api_add_attachments_to_body(array $item) +{ + $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']); + + if (strpos($body, '[/img]') !== false) { + return $body; + } + + foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) { + if (!empty($media['preview'])) { + $description = $media['description'] ?: $media['name']; + if (!empty($description)) { + $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]'; + } else { + $body .= "\n[img]" . $media['preview'] .'[/img]'; + } + } + } + + return $body; +} + /** * * @param string $body + * @param int $uriid * * @return array * @throws InternalServerErrorException */ -function api_get_attachments(&$body) +function api_get_attachments(&$body, $uriid) { $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body); $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body); @@ -2609,7 +2654,7 @@ function api_get_attachments(&$body) $imagedata = Images::getInfoFromURLCached($image); if ($imagedata) { - $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]]; + $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]]; } } @@ -2625,7 +2670,7 @@ function api_get_attachments(&$body) * @throws InternalServerErrorException * @todo Links at the first character of the post */ -function api_get_entitities(&$text, $bbcode) +function api_get_entitities(&$text, $bbcode, $uriid) { $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false'); @@ -2633,7 +2678,7 @@ function api_get_entitities(&$text, $bbcode) preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images); foreach ($images[1] as $image) { - $replace = ProxyUtils::proxifyUrl($image); + $replace = Post\Link::getByLink($uriid, $image); $text = str_replace($image, $replace, $text); } return []; @@ -2745,31 +2790,8 @@ function api_get_entitities(&$text, $bbcode) if (!($start === false)) { $image = Images::getInfoFromURLCached($url); if ($image) { - // If image cache is activated, then use the following sizes: - // thumb (150), small (340), medium (600) and large (1024) - if (!DI::config()->get("system", "proxy_disabled")) { - $media_url = ProxyUtils::proxifyUrl($url); - - $sizes = []; - $scale = Images::getScalingDimensions($image[0], $image[1], 150); - $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - - if (($image[0] > 150) || ($image[1] > 150)) { - $scale = Images::getScalingDimensions($image[0], $image[1], 340); - $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - } - - $scale = Images::getScalingDimensions($image[0], $image[1], 600); - $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - - if (($image[0] > 600) || ($image[1] > 600)) { - $scale = Images::getScalingDimensions($image[0], $image[1], 1024); - $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"]; - } - } else { - $media_url = $url; - $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"]; - } + $media_url = Post\Link::getByLink($uriid, $url); + $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"]; $entities["media"][] = [ "id" => $start+1, @@ -2935,6 +2957,10 @@ function api_format_items($items, $user_info, $filter_user = false, $type = "jso $ret = []; + if (empty($items)) { + return $ret; + } + foreach ((array)$items as $item) { list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item); @@ -3007,7 +3033,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use 'external_url' => DI::baseUrl() . "/display/" . $item['guid'], 'friendica_activities' => api_format_items_activities($item, $type), 'friendica_title' => $item['title'], - 'friendica_html' => BBCode::convert($item['body'], false) + 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL) ]; if (count($converted["attachments"]) > 0) { @@ -4010,48 +4036,6 @@ api_register_func('api/direct_messages/all', 'api_direct_messages_all', true); api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true); api_register_func('api/direct_messages', 'api_direct_messages_inbox', true); -/** - * Returns an OAuth Request Token. - * - * @see https://oauth.net/core/1.0/#auth_step1 - */ -function api_oauth_request_token() -{ - $oauth1 = new FKOAuth1(); - try { - $r = $oauth1->fetch_request_token(OAuthRequest::from_request()); - } catch (Exception $e) { - echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage()); - exit(); - } - echo $r; - exit(); -} - -/** - * Returns an OAuth Access Token. - * - * @return array|string - * @see https://oauth.net/core/1.0/#auth_step3 - */ -function api_oauth_access_token() -{ - $oauth1 = new FKOAuth1(); - try { - $r = $oauth1->fetch_access_token(OAuthRequest::from_request()); - } catch (Exception $e) { - echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); - exit(); - } - echo $r; - exit(); -} - -/// @TODO move to top of file or somewhere better -api_register_func('api/oauth/request_token', 'api_oauth_request_token', false); -api_register_func('api/oauth/access_token', 'api_oauth_access_token', false); - - /** * delete a complete photoalbum with all containing photos from database through api * @@ -4479,12 +4463,7 @@ function api_account_update_profile_image($type) Contact::updateSelfFromUserID(api_user(), true); // Update global directory in background - $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname']; - if ($url && strlen(DI::config()->get('system', 'directory'))) { - Worker::add(PRIORITY_LOW, "Directory", $url); - } - - Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user()); + Profile::publishUpdate(api_user()); // output for client if ($data) { @@ -4535,11 +4514,7 @@ function api_account_update_profile($type) DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]); } - Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user); - // Update global directory in background - if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) { - Worker::add(PRIORITY_LOW, "Directory", $api_user['url']); - } + Profile::publishUpdate($local_user); return api_account_verify_credentials($type); } @@ -4825,7 +4800,7 @@ function prepare_photo_data($type, $scale, $photo_id) "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`, `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`, MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale` - FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY + FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`, `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`", $data_sql, @@ -4873,7 +4848,7 @@ function prepare_photo_data($type, $scale, $photo_id) } // retrieve item element for getting activities (like, dislike etc.) related to photo - $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo']; + $condition = ['uid' => api_user(), 'resource-id' => $photo_id]; $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition); if (!DBA::isResult($item)) { throw new NotFoundException('Photo-related item not found.'); @@ -4882,7 +4857,7 @@ function prepare_photo_data($type, $scale, $photo_id) $data['photo']['friendica_activities'] = api_format_items_activities($item, $type); // retrieve comments on photo - $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')", + $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)", $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT]; $statuses = Post::selectForUser(api_user(), [], $condition); @@ -4912,70 +4887,6 @@ function prepare_photo_data($type, $scale, $photo_id) return $data; } - -/** - * Similar as /mod/redir.php - * redirect to 'url' after dfrn auth - * - * Why this when there is mod/redir.php already? - * This use api_user() and api_login() - * - * params - * c_url: url of remote contact to auth to - * url: string, url to redirect after auth - */ -function api_friendica_remoteauth() -{ - $url = $_GET['url'] ?? ''; - $c_url = $_GET['c_url'] ?? ''; - - if ($url === '' || $c_url === '') { - throw new BadRequestException("Wrong parameters."); - } - - $c_url = Strings::normaliseLink($c_url); - - // traditional DFRN - - $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]); - if (!DBA::isResult($contact)) { - throw new BadRequestException("Unknown contact"); - } - - $cid = $contact['id']; - - $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id']; - - if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) { - System::externalRedirect($url ?: $c_url); - } - - if ($contact['duplex'] && $contact['issued-id']) { - $orig_id = $contact['issued-id']; - $dfrn_id = '1:' . $orig_id; - } - if ($contact['duplex'] && $contact['dfrn-id']) { - $orig_id = $contact['dfrn-id']; - $dfrn_id = '0:' . $orig_id; - } - - $sec = Strings::getRandomHex(); - - $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, - 'sec' => $sec, 'expire' => time() + 45]; - DBA::insert('profile_check', $fields); - - Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]); - $dest = ($url ? '&destination_url=' . $url : ''); - - System::externalRedirect( - $contact['poll'] . '?dfrn_id=' . $dfrn_id - . '&dfrn_version=' . DFRN_PROTOCOL_VERSION - . '&type=profile&sec=' . $sec . $dest - ); -} -api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true); - /** * Return an item with announcer data if it had been announced * @@ -5705,7 +5616,7 @@ function api_friendica_activity($type) if (api_user() === false) { throw new ForbiddenException(); } - $verb = strtolower($a->argv[3]); + $verb = strtolower(DI::args()->getArgv()[3]); $verb = preg_replace("|\..*$|", "", $verb); $id = $_REQUEST['id'] ?? 0; @@ -5753,7 +5664,7 @@ function api_friendica_notification($type) if (api_user() === false) { throw new ForbiddenException(); } - if ($a->argc!==3) { + if (DI::args()->getArgc()!==3) { throw new BadRequestException("Invalid argument count"); } @@ -5798,7 +5709,7 @@ function api_friendica_notification_seen($type) if (api_user() === false || $user_info === false) { throw new ForbiddenException(); } - if ($a->argc !== 4) { + if (DI::args()->getArgc() !== 4) { throw new BadRequestException("Invalid argument count"); } @@ -5995,12 +5906,12 @@ api_register_func('api/saved_searches/list', 'api_saved_searches_list', true); * * @return void */ -function bindComments(&$data) +function bindComments(&$data) { if (count($data) == 0) { return; } - + $ids = []; $comments = []; foreach ($data as $item) { @@ -6008,7 +5919,7 @@ function bindComments(&$data) } $idStr = DBA::escape(implode(', ', $ids)); - $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`"; + $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`"; $items = DBA::p($sql, 0, GRAVITY_COMMENT); $itemsData = DBA::toArray($items);