X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=include%2Fapi.php;h=a69bd01b4971edfcea66cb166a3542111c3cd931;hb=9827e933a2a1b8e93f293d4e6293384126e5784c;hp=a32efa37e4a247973b09369ba2fd211a29064f38;hpb=5197833c5513fe70481bd170b8c840f5a834c8c2;p=friendica.git diff --git a/include/api.php b/include/api.php index a32efa37e4..a69bd01b49 100644 --- a/include/api.php +++ b/include/api.php @@ -7,21 +7,18 @@ */ use Friendica\App; -use Friendica\BaseObject; use Friendica\Content\ContactSelector; use Friendica\Content\Feature; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; -use Friendica\Core\Config; use Friendica\Core\Hook; -use Friendica\Core\L10n; use Friendica\Core\Logger; -use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\Session; use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Model\Contact; use Friendica\Model\Group; use Friendica\Model\Item; @@ -30,6 +27,7 @@ use Friendica\Model\Notify; use Friendica\Model\Photo; use Friendica\Model\Profile; use Friendica\Model\User; +use Friendica\Model\UserItem; use Friendica\Network\FKOAuth1; use Friendica\Network\HTTPException; use Friendica\Network\HTTPException\BadRequestException; @@ -66,11 +64,11 @@ $API = []; $called_api = []; /** + * Auth API user + * * It is not sufficient to use local_user() to check whether someone is allowed to use the API, * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF * into a page, and visitors will post something without noticing it). - * - * @brief Auth API user */ function api_user() { @@ -82,13 +80,13 @@ function api_user() } /** + * Get source name from API client + * * Clients can send 'source' parameter to be show in post metadata * as "sent via ". * Some clients doesn't send a source param, we support ones we know * (only Twidere, atm) * - * @brief Get source name from API client - * * @return string * Client source name, default to "api" if unset/unknown * @throws Exception @@ -114,7 +112,7 @@ function api_source() } /** - * @brief Format date for API + * Format date for API * * @param string $str Source date, as UTC * @return string Date in UTC formatted as "D M d H:i:s +0000 Y" @@ -129,9 +127,7 @@ function api_date($str) /** * Register a function to be the endpoint for defined API path. * - * @brief Register API endpoint - * - * @param string $path API URL path, relative to System::baseUrl() + * @param string $path API URL path, relative to DI::baseUrl() * @param string $func Function name to call on path request * @param bool $auth API need logged user * @param string $method HTTP method reqiured to call this endpoint. @@ -162,8 +158,6 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY * Log in user via OAuth1 or Simple HTTP Auth. * Simple Auth allow username in form of
user@server
, ignoring server part * - * @brief Login API user - * * @param App $a App * @throws ForbiddenException * @throws InternalServerErrorException @@ -253,7 +247,7 @@ function api_login(App $a) throw new UnauthorizedException("This API requires login"); } - Session::setAuthenticatedForUser($a, $record); + DI::auth()->setForUser($a, $record); $_SESSION["allow_api"] = true; @@ -261,12 +255,12 @@ function api_login(App $a) } /** + * Check HTTP method of called API + * * API endpoints can define which HTTP method to accept when called. * This function check the current HTTP method agains endpoint * registered method. * - * @brief Check HTTP method of called API - * * @param string $method Required methods, uppercase, separated by comma * @return bool */ @@ -279,43 +273,46 @@ function api_check_method($method) } /** - * Authenticate user, call registered API function, set HTTP headers + * Main API entry point * - * @brief Main API entry point + * Authenticate user, call registered API function, set HTTP headers * * @param App $a App + * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing) * @return string|array API call result * @throws Exception */ -function api_call(App $a) +function api_call(App $a, App\Arguments $args = null) { global $API, $called_api; + if ($args == null) { + $args = DI::args(); + } + $type = "json"; - if (strpos($a->query_string, ".xml") > 0) { + if (strpos($args->getQueryString(), ".xml") > 0) { $type = "xml"; } - if (strpos($a->query_string, ".json") > 0) { + if (strpos($args->getQueryString(), ".json") > 0) { $type = "json"; } - if (strpos($a->query_string, ".rss") > 0) { + if (strpos($args->getQueryString(), ".rss") > 0) { $type = "rss"; } - if (strpos($a->query_string, ".atom") > 0) { + if (strpos($args->getQueryString(), ".atom") > 0) { $type = "atom"; } try { foreach ($API as $p => $info) { - if (strpos($a->query_string, $p) === 0) { + if (strpos($args->getQueryString(), $p) === 0) { if (!api_check_method($info['method'])) { throw new MethodNotAllowedException(); } $called_api = explode("/", $p); - //unset($_SERVER['PHP_AUTH_USER']); - /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even. if (!empty($info['auth']) && api_user() === false) { api_login($a); } @@ -329,7 +326,7 @@ function api_call(App $a) Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]); - $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance'); + DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance'); if (false === $return) { /* @@ -366,31 +363,30 @@ function api_call(App $a) } } - Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]); + Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]); throw new NotImplementedException(); } catch (HTTPException $e) { header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}"); - return api_error($type, $e); + return api_error($type, $e, $args); } } /** - * @brief Format API error string + * Format API error string * * @param string $type Return type (xml, json, rss, as) * @param object $e HTTPException Error object + * @param App\Arguments $args The App arguments * @return string|array error message formatted as $type */ -function api_error($type, $e) +function api_error($type, $e, App\Arguments $args) { - $a = \get_app(); - $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc); /// @TODO: https://dev.twitter.com/overview/api/response-codes $error = ["error" => $error, "code" => $e->getCode() . " " . $e->httpdesc, - "request" => $a->query_string]; + "request" => $args->getQueryString()]; $return = api_format_data('status', $type, ['status' => $error]); @@ -414,7 +410,7 @@ function api_error($type, $e) } /** - * @brief Set values for RSS template + * Set values for RSS template * * @param App $a * @param array $arr Array to be passed to template @@ -435,12 +431,12 @@ function api_rss_extra(App $a, $arr, $user_info) $arr['$user'] = $user_info; $arr['$rss'] = [ 'alternate' => $user_info['url'], - 'self' => System::baseUrl() . "/" . $a->query_string, - 'base' => System::baseUrl(), + 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(), + 'base' => DI::baseUrl(), 'updated' => api_date(null), 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), 'language' => $user_info['lang'], - 'logo' => System::baseUrl() . "/images/friendica-32.png", + 'logo' => DI::baseUrl() . "/images/friendica-32.png", ]; return $arr; @@ -448,7 +444,7 @@ function api_rss_extra(App $a, $arr, $user_info) /** - * @brief Unique contact to contact url. + * Unique contact to contact url. * * @param int $id Contact id * @return bool|string @@ -467,7 +463,7 @@ function api_unique_id_to_nurl($id) } /** - * @brief Get user info array. + * Get user info array. * * @param App $a App * @param int|string $contact_id Contact ID or URL @@ -605,17 +601,12 @@ function api_get_user(App $a, $contact_id = null) $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]); if (DBA::isResult($contact)) { - // If no nick where given, extract it from the address - if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) { - $contact['nick'] = api_get_nick($contact["url"]); - } - $ret = [ 'id' => $contact["id"], 'id_str' => (string) $contact["id"], 'name' => $contact["name"], 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']), - 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']), + 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']), 'description' => BBCode::toPlaintext($contact["about"]), 'profile_image_url' => $contact["micro"], 'profile_image_url_https' => $contact["micro"], @@ -668,11 +659,6 @@ function api_get_user(App $a, $contact_id = null) $countfollowers = 0; $starred = 0; - // Add a nick if it isn't present there - if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) { - $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]); - } - $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true); if (!empty($profile['about'])) { @@ -686,7 +672,7 @@ function api_get_user(App $a, $contact_id = null) } elseif (!empty($uinfo[0]["location"])) { $location = $uinfo[0]["location"]; } else { - $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']); + $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']); } $ret = [ @@ -721,7 +707,7 @@ function api_get_user(App $a, $contact_id = null) 'statusnet_blocking' => false, 'notifications' => false, /// @TODO old way? - //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'], + //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'], 'statusnet_profile_url' => $uinfo[0]['url'], 'uid' => intval($uinfo[0]['uid']), 'cid' => intval($uinfo[0]['cid']), @@ -734,7 +720,7 @@ function api_get_user(App $a, $contact_id = null) if ($ret['self']) { $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]); if ($theme_info['theme'] === 'frio') { - $schema = PConfig::get($ret['uid'], 'frio', 'schema'); + $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema'); if ($schema && ($schema != '---')) { if (file_exists('view/theme/frio/schema/'.$schema.'.php')) { @@ -742,9 +728,9 @@ function api_get_user(App $a, $contact_id = null) require_once $schemefile; } } else { - $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg'); - $link_color = PConfig::get($ret['uid'], 'frio', 'link_color'); - $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color'); + $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg'); + $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color'); + $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color'); } if (empty($nav_bg)) { $nav_bg = "#708fa0"; @@ -766,7 +752,7 @@ function api_get_user(App $a, $contact_id = null) } /** - * @brief return api-formatted array for item's author and owner + * return api-formatted array for item's author and owner * * @param App $a App * @param array $item item from db @@ -794,7 +780,7 @@ function api_item_get_user(App $a, $item) } /** - * @brief walks recursively through an array with the possibility to change value and key + * walks recursively through an array with the possibility to change value and key * * @param array $array The array to walk through * @param callable $callback The callback function @@ -822,7 +808,7 @@ function api_walk_recursive(array &$array, callable $callback) } /** - * @brief Callback function to transform the array in an array that can be transformed in a XML file + * Callback function to transform the array in an array that can be transformed in a XML file * * @param mixed $item Array item value * @param string $key Array key @@ -848,7 +834,7 @@ function api_reformat_xml(&$item, &$key) } /** - * @brief Creates the XML from a JSON style array + * Creates the XML from a JSON style array * * @param array $data JSON style array * @param string $root_element Name of the root element @@ -893,7 +879,7 @@ function api_create_xml(array $data, $root_element) } /** - * @brief Formats the data according to the data type + * Formats the data according to the data type * * @param string $root_element Name of the root element * @param string $type Return type (atom, rss, xml, json) @@ -937,7 +923,7 @@ function api_format_data($root_element, $type, $data) */ function api_account_verify_credentials($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -1005,7 +991,7 @@ function requestdata($k) */ function api_statuses_mediap($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { Logger::log('api_statuses_update: no user'); @@ -1059,7 +1045,7 @@ api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD */ function api_statuses_update($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { Logger::log('api_statuses_update: no user'); @@ -1108,7 +1094,7 @@ function api_statuses_update($type) if (!$parent) { // Check for throttling (maximum posts per day, week and month) - $throttle_day = Config::get('system', 'throttle_limit_day'); + $throttle_day = DI::config()->get('system', 'throttle_limit_day'); if ($throttle_day > 0) { $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60); @@ -1117,12 +1103,12 @@ function api_statuses_update($type) if ($posts_day > $throttle_day) { Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG); - // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day)); - throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day)); + // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day)); + throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day)); } } - $throttle_week = Config::get('system', 'throttle_limit_week'); + $throttle_week = DI::config()->get('system', 'throttle_limit_week'); if ($throttle_week > 0) { $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7); @@ -1131,12 +1117,12 @@ function api_statuses_update($type) if ($posts_week > $throttle_week) { Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG); - // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week))); - throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)); + // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week))); + throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)); } } - $throttle_month = Config::get('system', 'throttle_limit_month'); + $throttle_month = DI::config()->get('system', 'throttle_limit_month'); if ($throttle_month > 0) { $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30); @@ -1145,8 +1131,8 @@ function api_statuses_update($type) if ($posts_month > $throttle_month) { Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG); - // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month)); - throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month)); + // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month)); + throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month)); } } } @@ -1171,8 +1157,8 @@ function api_statuses_update($type) $phototypes = Images::supportedTypes(); $ext = $phototypes[$r[0]['type']]; $description = $r[0]['desc'] ?? ''; - $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']'; - $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]'; + $_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]'; } } } @@ -1209,7 +1195,7 @@ api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, */ function api_media_upload() { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { Logger::log('no user'); @@ -1264,7 +1250,7 @@ api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST) */ function api_media_metadata_create($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { Logger::info('no user'); @@ -1377,7 +1363,7 @@ function api_get_item(array $condition) */ function api_users_show($type) { - $a = BaseObject::getApp(); + $a = Friendica\DI::app(); $user_info = api_get_user($a); @@ -1411,7 +1397,7 @@ api_register_func('api/externalprofile/show', 'api_users_show'); */ function api_users_search($type) { - $a = \get_app(); + $a = DI::app(); $userlist = []; @@ -1473,7 +1459,7 @@ function api_users_lookup($type) if (!empty($_REQUEST['user_id'])) { foreach (explode(',', $_REQUEST['user_id']) as $id) { if (!empty($id)) { - $users[] = api_get_user(get_app(), $id); + $users[] = api_get_user(DI::app(), $id); } } } @@ -1504,7 +1490,7 @@ api_register_func('api/users/lookup', 'api_users_lookup', true); */ function api_search($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -1526,7 +1512,7 @@ function api_search($type) } elseif (!empty($_REQUEST['count'])) { $count = $_REQUEST['count']; } - + $since_id = $_REQUEST['since_id'] ?? 0; $max_id = $_REQUEST['max_id'] ?? 0; $page = $_REQUEST['page'] ?? 1; @@ -1562,7 +1548,7 @@ function api_search($type) $condition = [implode(' AND ', $preCondition)]; } else { - $condition = ["`id` > ? + $condition = ["`id` > ? " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . " AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `body` LIKE CONCAT('%',?,'%')", @@ -1618,7 +1604,7 @@ api_register_func('api/search', 'api_search', true); */ function api_statuses_home_timeline($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -1711,7 +1697,7 @@ api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', */ function api_statuses_public_timeline($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -1784,8 +1770,6 @@ api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline' /** * Returns the most recent statuses posted by users this node knows about. * - * @brief Returns the list of public federated posts this node knows about - * * @param string $type Return format: json, xml, atom, rss * @return array|string * @throws BadRequestException @@ -1796,7 +1780,7 @@ api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline' */ function api_statuses_networkpublic_timeline($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -1857,7 +1841,7 @@ api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpu */ function api_statuses_show($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -1936,7 +1920,7 @@ api_register_func('api/statuses/show', 'api_statuses_show', true); */ function api_conversation_show($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -2018,7 +2002,7 @@ function api_statuses_repeat($type) { global $called_api; - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -2095,7 +2079,7 @@ api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHO */ function api_statuses_destroy($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -2142,7 +2126,7 @@ api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METH */ function api_statuses_mentions($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -2165,17 +2149,35 @@ function api_statuses_mentions($type) $start = max(0, ($page - 1) * $count); - $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ? AND `mention` - AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND NOT `thread`.`ignored`)", - api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()]; + $query = "SELECT `item`.`id` FROM `user-item` + INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?) + WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND + `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0 + AND `user-item`.`iid` > ?"; + $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(), + UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED | + UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT | + UserItem::NOTIF_DIRECT_THREAD_COMMENT, + $since_id]; if ($max_id > 0) { - $condition[0] .= " AND `item`.`id` <= ?"; + $query .= " AND `item`.`id` <= ?"; $condition[] = $max_id; } + $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?"; + $condition[] = $start; + $condition[] = $count; + + $useritems = DBA::p($query, $condition); + $itemids = []; + while ($useritem = DBA::fetch($useritems)) { + $itemids[] = $useritem['id']; + } + DBA::close($useritems); + $params = ['order' => ['id' => true], 'limit' => [$start, $count]]; - $statuses = Item::selectForUser(api_user(), [], $condition, $params); + $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params); $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type); @@ -2198,8 +2200,6 @@ api_register_func('api/statuses/replies', 'api_statuses_mentions', true); /** * Returns the most recent statuses posted by the user. * - * @brief Returns a user's public timeline - * * @param string $type Either "json" or "xml" * @return string|array * @throws BadRequestException @@ -2211,7 +2211,7 @@ api_register_func('api/statuses/replies', 'api_statuses_mentions', true); */ function api_statuses_user_timeline($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -2295,7 +2295,7 @@ api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', tr */ function api_favorites_create_destroy($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -2378,7 +2378,7 @@ function api_favorites($type) { global $called_api; - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -2737,7 +2737,7 @@ function api_get_entitities(&$text, $bbcode) if ($image) { // If image cache is activated, then use the following sizes: // thumb (150), small (340), medium (600) and large (1024) - if (!Config::get("system", "proxy_disabled")) { + if (!DI::config()->get("system", "proxy_disabled")) { $media_url = ProxyUtils::proxifyUrl($url); $sizes = []; @@ -2793,7 +2793,7 @@ function api_format_items_embeded_images($item, $text) $text = preg_replace_callback( '|data:image/([^;]+)[^=]+=*|m', function () use ($item) { - return System::baseUrl() . '/display/' . $item['guid']; + return DI::baseUrl() . '/display/' . $item['guid']; }, $text ); @@ -2801,7 +2801,7 @@ function api_format_items_embeded_images($item, $text) } /** - * @brief return name as array + * return name as array * * @param string $txt text * @return array @@ -2828,7 +2828,7 @@ function api_contactlink_to_array($txt) /** - * @brief return likes, dislikes and attend status for item + * return likes, dislikes and attend status for item * * @param array $item array * @param string $type Return type (atom, rss, xml, json) @@ -2843,7 +2843,7 @@ function api_contactlink_to_array($txt) */ function api_format_items_activities($item, $type = "json") { - $a = \get_app(); + $a = DI::app(); $activities = [ 'like' => [], @@ -2851,9 +2851,10 @@ function api_format_items_activities($item, $type = "json") 'attendyes' => [], 'attendno' => [], 'attendmaybe' => [], + 'announce' => [], ]; - $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']]; + $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY]; $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition); while ($parent_item = Item::fetch($ret)) { @@ -2878,6 +2879,9 @@ function api_format_items_activities($item, $type = "json") case Activity::ATTENDMAYBE: $activities['attendmaybe'][] = $user; break; + case Activity::ANNOUNCE: + $activities['announce'][] = $user; + break; default: break; } @@ -2904,7 +2908,7 @@ function api_format_items_activities($item, $type = "json") /** - * @brief return data from profiles + * return data from profiles * * @param array $profile_row array containing data from db table 'profile' * @return array @@ -2957,7 +2961,7 @@ function api_format_items_profiles($profile_row) } /** - * @brief format items to be returned by api + * format items to be returned by api * * @param array $items array of items * @param array $user_info @@ -2971,7 +2975,7 @@ function api_format_items_profiles($profile_row) */ function api_format_items($items, $user_info, $filter_user = false, $type = "json") { - $a = BaseObject::getApp(); + $a = Friendica\DI::app(); $ret = []; @@ -3005,7 +3009,7 @@ function api_format_items($items, $user_info, $filter_user = false, $type = "jso */ function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null) { - $a = BaseObject::getApp(); + $a = Friendica\DI::app(); if (empty($status_user) || empty($author_user) || empty($owner_user)) { list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item); @@ -3044,7 +3048,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use //'entities' => NULL, 'statusnet_html' => $converted["html"], 'statusnet_conversation_id' => $item['parent'], - 'external_url' => System::baseUrl() . "/display/" . $item['guid'], + '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) @@ -3059,9 +3063,9 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use } if ($status["source"] == 'web') { - $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']); - } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) { - $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')'); + $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']); + } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) { + $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')'); } $retweeted_item = []; @@ -3260,7 +3264,7 @@ api_register_func('api/lists/subscriptions', 'api_lists_list', true); */ function api_lists_ownerships($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -3309,7 +3313,7 @@ api_register_func('api/lists/ownerships', 'api_lists_ownerships', true); */ function api_lists_statuses($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { @@ -3372,11 +3376,11 @@ function api_lists_statuses($type) api_register_func('api/lists/statuses', 'api_lists_statuses', true); /** + * Returns either the friends of the follower list + * * Considers friends and followers lists to be private and won't return * anything if any user_id parameter is passed. * - * @brief Returns either the friends of the follower list - * * @param string $qtype Either "friends" or "followers" * @return boolean|array * @throws BadRequestException @@ -3387,7 +3391,7 @@ api_register_func('api/lists/statuses', 'api_lists_statuses', true); */ function api_statuses_f($qtype) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -3463,9 +3467,7 @@ function api_statuses_f($qtype) /** - * Returns the user's friends. - * - * @brief Returns the list of friends of the provided user + * Returns the list of friends of the provided user * * @deprecated By Twitter API in favor of friends/list * @@ -3484,9 +3486,7 @@ function api_statuses_friends($type) } /** - * Returns the user's followers. - * - * @brief Returns the list of followers of the provided user + * Returns the list of followers of the provided user * * @deprecated By Twitter API in favor of friends/list * @@ -3570,17 +3570,15 @@ api_register_func('api/friendships/incoming', 'api_friendships_incoming', true); */ function api_statusnet_config($type) { - $a = \get_app(); - - $name = Config::get('config', 'sitename'); - $server = $a->getHostName(); - $logo = System::baseUrl() . '/images/friendica-64.png'; - $email = Config::get('config', 'admin_email'); - $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false'; - $private = Config::get('system', 'block_public') ? 'true' : 'false'; - $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000)); - $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false'; - $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : ''; + $name = DI::config()->get('config', 'sitename'); + $server = DI::baseUrl()->getHostname(); + $logo = DI::baseUrl() . '/images/friendica-64.png'; + $email = DI::config()->get('config', 'admin_email'); + $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false'; + $private = DI::config()->get('system', 'block_public') ? 'true' : 'false'; + $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000)); + $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false'; + $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : ''; $config = [ 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '', @@ -3641,7 +3639,7 @@ function api_ff_ids($type, int $rel) throw new ForbiddenException(); } - $a = \get_app(); + $a = DI::app(); api_get_user($a); @@ -3728,7 +3726,7 @@ api_register_func('api/followers/ids', 'api_followers_ids', true); */ function api_direct_messages_new($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -3805,9 +3803,7 @@ function api_direct_messages_new($type) api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST); /** - * Destroys a direct message. - * - * @brief delete a direct_message from mail table through api + * delete a direct_message from mail table through api * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -3820,7 +3816,7 @@ api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, AP */ function api_direct_messages_destroy($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -3893,8 +3889,6 @@ api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', /** * Unfollow Contact * - * @brief unfollow contact - * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array * @throws BadRequestException @@ -3988,7 +3982,7 @@ api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, AP */ function api_direct_messages_box($type, $box, $verbose) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); } @@ -4190,7 +4184,7 @@ api_register_func('api/oauth/access_token', 'api_oauth_access_token', false); /** - * @brief delete a complete photoalbum with all containing photos from database through api + * delete a complete photoalbum with all containing photos from database through api * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -4245,7 +4239,7 @@ function api_fr_photoalbum_delete($type) } /** - * @brief update the name of the album for all photos of an album + * update the name of the album for all photos of an album * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -4287,7 +4281,7 @@ function api_fr_photoalbum_update($type) /** - * @brief list all photos of the authenticated user + * list all photos of the authenticated user * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -4318,7 +4312,7 @@ function api_fr_photos_list($type) $photo['album'] = $rr['album']; $photo['filename'] = $rr['filename']; $photo['type'] = $rr['type']; - $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']]; + $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']]; $photo['created'] = $rr['created']; $photo['edited'] = $rr['edited']; $photo['desc'] = $rr['desc']; @@ -4335,7 +4329,7 @@ function api_fr_photos_list($type) } /** - * @brief upload a new photo or change an existing photo + * upload a new photo or change an existing photo * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -4474,7 +4468,7 @@ function api_fr_photo_create_update($type) } /** - * @brief delete a single photo from the database through api + * delete a single photo from the database through api * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -4527,7 +4521,7 @@ function api_fr_photo_delete($type) /** - * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64 + * returns the details of a specified photo id, if scale is given, returns the photo data in base 64 * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -4556,9 +4550,7 @@ function api_fr_photo_detail($type) /** - * Updates the user’s profile image. - * - * @brief updates the profile image for the user (either a specified profile or the default profile) + * updates the profile image for the user (either a specified profile or the default profile) * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @@ -4603,7 +4595,7 @@ function api_account_update_profile_image($type) $media = $_FILES['media']; } // save new profile image - $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile); + $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile); // get filetype if (is_array($media['type'])) { @@ -4624,16 +4616,16 @@ function api_account_update_profile_image($type) $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()]; Photo::update(['profile' => false], $condition); } else { - $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext, - 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext]; + $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext, + 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext]; DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]); } Contact::updateSelfFromUserID(api_user(), true); // Update global directory in background - $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname']; - if ($url && strlen(Config::get('system', 'directory'))) { + $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname']; + if ($url && strlen(DI::config()->get('system', 'directory'))) { Worker::add(PRIORITY_LOW, "Directory", $url); } @@ -4673,7 +4665,7 @@ api_register_func('api/account/update_profile_image', 'api_account_update_profil function api_account_update_profile($type) { $local_user = api_user(); - $api_user = api_get_user(get_app()); + $api_user = api_get_user(DI::app()); if (!empty($_POST['name'])) { DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]); @@ -4690,7 +4682,7 @@ function api_account_update_profile($type) Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user); // Update global directory in background - if ($api_user['url'] && strlen(Config::get('system', 'directory'))) { + if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) { Worker::add(PRIORITY_LOW, "Directory", $api_user['url']); } @@ -4798,7 +4790,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $ throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server"); } // check against max upload size within Friendica instance - $maximagesize = Config::get('system', 'maximagesize'); + $maximagesize = DI::config()->get('system', 'maximagesize'); if ($maximagesize && ($filesize > $maximagesize)) { $formattedBytes = Strings::formatBytes($maximagesize); throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)"); @@ -4816,7 +4808,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $ @unlink($src); // check max length of images on server - $max_length = Config::get('system', 'max_image_length'); + $max_length = DI::config()->get('system', 'max_image_length'); if (!$max_length) { $max_length = MAX_IMAGE_LENGTH; } @@ -4944,8 +4936,8 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f ]; // adds link to the thumbnail scale photo - $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']' - . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]' + $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']' + . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]' . '[/url]'; // do the magic for storing the item in the database and trigger the federation to other contacts @@ -4968,7 +4960,7 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f */ function prepare_photo_data($type, $scale, $photo_id) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if ($user_info === false) { @@ -5013,14 +5005,14 @@ function prepare_photo_data($type, $scale, $photo_id) for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) { $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'], "scale" => $k, - "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]]; + "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]]; } } else { $data['photo']['link'] = []; // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0 $i = 0; for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) { - $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]; + $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]; $i++; } } @@ -5034,6 +5026,9 @@ function prepare_photo_data($type, $scale, $photo_id) // retrieve item element for getting activities (like, dislike etc.) related to photo $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo']; $item = Item::selectFirstForUser(local_user(), ['id'], $condition); + if (!DBA::isResult($item)) { + throw new NotFoundException('Photo-related item not found.'); + } $data['photo']['friendica_activities'] = api_format_items_activities($item, $type); @@ -5094,14 +5089,17 @@ function api_friendica_remoteauth() // traditional DFRN $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]); - - if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) { + if (!DBA::isResult($contact)) { throw new BadRequestException("Unknown contact"); } $cid = $contact['id']; - $dfrn_id = $contact['issued-id'] ?? $contact['dfrn-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']; @@ -5164,7 +5162,7 @@ function api_get_announce($item) } /** - * @brief Return the item shared, if the item contains only the [share] tag + * Return the item shared, if the item contains only the [share] tag * * @param array $item Sharer item * @return array|false Shared item or false if not a reshare @@ -5233,91 +5231,6 @@ function api_share_as_retweet(&$item) return $reshared_item; } -/** - * - * @param string $profile - * - * @return string|false - * @throws InternalServerErrorException - * @todo remove trailing junk from profile url - * @todo pump.io check has to check the website - */ -function api_get_nick($profile) -{ - $nick = ""; - - $r = q( - "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'", - DBA::escape(Strings::normaliseLink($profile)) - ); - - if (DBA::isResult($r)) { - $nick = $r[0]["nick"]; - } - - if (!$nick == "") { - $r = q( - "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'", - DBA::escape(Strings::normaliseLink($profile)) - ); - - if (DBA::isResult($r)) { - $nick = $r[0]["nick"]; - } - } - - if (!$nick == "") { - $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile); - if ($friendica != $profile) { - $nick = $friendica; - } - } - - if (!$nick == "") { - $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile); - if ($diaspora != $profile) { - $nick = $diaspora; - } - } - - if (!$nick == "") { - $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile); - if ($twitter != $profile) { - $nick = $twitter; - } - } - - - if (!$nick == "") { - $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile); - if ($StatusnetHost != $profile) { - $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile); - if ($StatusnetUser != $profile) { - $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser); - $user = json_decode($UserData); - if ($user) { - $nick = $user->screen_name; - } - } - } - } - - // To-Do: look at the page if its really a pumpio site - //if (!$nick == "") { - // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/"); - // if ($pumpio != $profile) - // $nick = $pumpio; - //
- - //} - - if ($nick != "") { - return $nick; - } - - return false; -} - /** * * @param array $item @@ -5349,10 +5262,6 @@ function api_in_reply_to($item) $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]); if (DBA::isResult($parent)) { - if ($parent['author-nick'] == "") { - $parent['author-nick'] = api_get_nick($parent['author-link']); - } - $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']); $in_reply_to['user_id'] = intval($parent['author-id']); $in_reply_to['user_id_str'] = (string) intval($parent['author-id']); @@ -5482,7 +5391,7 @@ function api_best_nickname(&$contacts) */ function api_friendica_group_show($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5552,7 +5461,7 @@ api_register_func('api/friendica/group_show', 'api_friendica_group_show', true); */ function api_friendica_group_delete($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5619,7 +5528,7 @@ api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', tr */ function api_lists_destroy($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5741,7 +5650,7 @@ function group_create($name, $uid, $users = []) */ function api_friendica_group_create($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5775,7 +5684,7 @@ api_register_func('api/friendica/group_create', 'api_friendica_group_create', tr */ function api_lists_create($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5814,7 +5723,7 @@ api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST) */ function api_friendica_group_update($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5893,7 +5802,7 @@ api_register_func('api/friendica/group_update', 'api_friendica_group_update', tr */ function api_lists_update($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5943,7 +5852,7 @@ api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST) */ function api_friendica_activity($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5980,7 +5889,7 @@ api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST); /** - * @brief Returns notifications + * Returns notifications * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -5990,7 +5899,7 @@ api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activit */ function api_friendica_notification($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -5998,28 +5907,31 @@ function api_friendica_notification($type) if ($a->argc!==3) { throw new BadRequestException("Invalid argument count"); } - /** @var Notify $nm */ - $nm = BaseObject::getClass(Notify::class); - $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50); + $notifications = DI::notify()->select(['uid' => api_user()], ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => 50]); if ($type == "xml") { - $xmlnotes = []; - if (!empty($notes)) { - foreach ($notes as $note) { - $xmlnotes[] = ["@attributes" => $note]; + $xmlnotes = false; + if (!empty($notifications)) { + foreach ($notifications as $notification) { + $xmlnotes[] = ["@attributes" => $notification->toArray()]; } } - $notes = $xmlnotes; + $result = $xmlnotes; + } elseif (count($notifications) > 0) { + $result = $notifications->getArrayCopy(); + } else { + $result = false; } - return api_format_data("notes", $type, ['note' => $notes]); + + return api_format_data("notes", $type, ['note' => $result]); } /** - * POST request with 'id' param as notification id + * Set notification as seen and returns associated item (if possible) * - * @brief Set notification as seen and returns associated item (if possible) + * POST request with 'id' param as notification id * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -6031,38 +5943,36 @@ function api_friendica_notification($type) */ function api_friendica_notification_seen($type) { - $a = \get_app(); + $a = DI::app(); $user_info = api_get_user($a); if (api_user() === false || $user_info === false) { throw new ForbiddenException(); } - if ($a->argc!==4) { + if ($a->argc !== 4) { throw new BadRequestException("Invalid argument count"); } $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0); - /** @var Notify $nm */ - $nm = BaseObject::getClass(Notify::class); - $note = $nm->getByID($id); - if (is_null($note)) { - throw new BadRequestException("Invalid argument"); - } - - $nm->setSeen($note); - if ($note['otype']=='item') { - // would be really better with an ItemsManager and $im->getByID() :-P - $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]); - if (DBA::isResult($item)) { - // we found the item, return it to the user - $ret = api_format_items([$item], $user_info, false, $type); - $data = ['status' => $ret]; - return api_format_data("status", $type, $data); + try { + $notification = DI::notify()->getByID($id); + $notification->setSeen(); + + if ($notification->otype === Notify::OTYPE_ITEM) { + $item = Item::selectFirstForUser(api_user(), [], ['id' => $notification->iid, 'uid' => api_user()]); + if (DBA::isResult($item)) { + // we found the item, return it to the user + $ret = api_format_items([$item], $user_info, false, $type); + $data = ['status' => $ret]; + return api_format_data("status", $type, $data); + } + // the item can't be found, but we set the notification as seen, so we count this as a success } - // the item can't be found, but we set the note as seen, so we count this as a success + return api_format_data('result', $type, ['result' => "success"]); + } catch (NotFoundException $e) { + throw new BadRequestException('Invalid argument'); } - return api_format_data('result', $type, ['result' => "success"]); } /// @TODO move to top of file or somewhere better @@ -6070,7 +5980,7 @@ api_register_func('api/friendica/notification/seen', 'api_friendica_notification api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET); /** - * @brief update a direct_message to seen state + * update a direct_message to seen state * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array (success result=ok, error result=error with error message) @@ -6082,7 +5992,7 @@ api_register_func('api/friendica/notification', 'api_friendica_notification', tr */ function api_friendica_direct_messages_setseen($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); } @@ -6121,7 +6031,7 @@ function api_friendica_direct_messages_setseen($type) api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true); /** - * @brief search for direct_messages containing a searchstring through api + * search for direct_messages containing a searchstring through api * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @param string $box @@ -6136,7 +6046,7 @@ api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct */ function api_friendica_direct_messages_search($type, $box = "") { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -6192,7 +6102,7 @@ function api_friendica_direct_messages_search($type, $box = "") api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true); /** - * @brief return data of all the profiles a user has to the client + * return data of all the profiles a user has to the client * * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' * @return string|array @@ -6204,7 +6114,7 @@ api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_ */ function api_friendica_profile_show($type) { - $a = \get_app(); + $a = DI::app(); if (api_user() === false) { throw new ForbiddenException(); @@ -6215,7 +6125,7 @@ function api_friendica_profile_show($type) // retrieve general information about profiles for user $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles'); - $directory = Config::get('system', 'directory'); + $directory = DI::config()->get('system', 'directory'); // get data of the specified profile id or all profiles of the user if not specified if ($profile_id != 0) { @@ -6298,9 +6208,9 @@ function api_saved_searches_list($type) api_register_func('api/saved_searches/list', 'api_saved_searches_list', true); /* - * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search + * Number of comments * - * @brief Number of comments + * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search * * @param object $data [Status, Status] *