Merge branch 'friendica:develop' into doc_faq_client-clean-up

This commit is contained in:
foss- 2021-11-21 01:09:31 +01:00 committed by GitHub
commit 3bae52074a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
290 changed files with 2713 additions and 2817 deletions

View file

@ -566,7 +566,6 @@ Here is a complete list of all hook callbacks with file locations (as of 24-Sep-
Hook::callAll($a->module.'_mod_init', $placeholder);
Hook::callAll($a->module.'_mod_init', $placeholder);
Hook::callAll($a->module.'_mod_post', $_POST);
Hook::callAll($a->module.'_mod_afterpost', $placeholder);
Hook::callAll($a->module.'_mod_content', $arr);
Hook::callAll($a->module.'_mod_aftercontent', $arr);
Hook::callAll('page_end', DI::page()['content']);

View file

@ -177,7 +177,7 @@ Friendica supports [Mastodon API](help/API-Mastodon) and [Twitter API](help/api)
* [AndStatus](http://andstatus.org) ([F-Droid](https://f-droid.org/repository/browse/?fdid=org.andstatus.app), [Google Play](https://play.google.com/store/apps/details?id=org.andstatus.app))
* [B4X for Pleroma & Mastodon](https://github.com/AnywhereSoftware/B4X-Pleroma)
* [DiCa](https://dica.mixi.cool/) (Available at Google Play)
* DiCa ([Google Play](https://play.google.com/store/apps/details?id=cool.mixi.dica), last updated 2019)
* [Fedi](https://play.google.com/store/apps/details?id=com.fediverse.app)
* [Fedilab](https://fedilab.app) ([F-Droid](https://f-droid.org/app/fr.gouv.etalab.mastodon), [Google Play](https://play.google.com/store/apps/details?id=app.fedilab.android))
* [Friendiqa](https://git.friendi.ca/lubuwest/Friendiqa) ([F-Droid](https://git.friendi.ca/lubuwest/Friendiqa#install), [Google Play](https://play.google.com/store/apps/details?id=org.qtproject.friendiqa))

View file

@ -202,7 +202,6 @@ Eine komplette Liste aller Hook-Callbacks mit den zugehörigen Dateien (am 01-Ap
Hook::callAll($a->module.'_mod_init', $placeholder);
Hook::callAll($a->module.'_mod_init', $placeholder);
Hook::callAll($a->module.'_mod_post', $_POST);
Hook::callAll($a->module.'_mod_afterpost', $placeholder);
Hook::callAll($a->module.'_mod_content', $arr);
Hook::callAll($a->module.'_mod_aftercontent', $arr);
Hook::callAll('page_end', DI::page()['content']);

View file

@ -186,7 +186,7 @@ Friendica unterstützt [Mastodon API](help/API-Mastodon) und [Twitter API](help/
* [AndStatus](http://andstatus.org) ([F-Droid](https://f-droid.org/repository/browse/?fdid=org.andstatus.app), [Google Play](https://play.google.com/store/apps/details?id=org.andstatus.app))
* [B4X for Pleroma & Mastodon](https://github.com/AnywhereSoftware/B4X-Pleroma)
* [DiCa](https://dica.mixi.cool/) (Gibt es bei Google Play)
* DiCa ([Google Play](https://play.google.com/store/apps/details?id=cool.mixi.dica), letztes Update 2019)
* [Fedi](https://play.google.com/store/apps/details?id=com.fediverse.app)
* [Fedilab](https://fedilab.app) ([F-Droid](https://f-droid.org/app/fr.gouv.etalab.mastodon), [Google Play](https://play.google.com/store/apps/details?id=app.fedilab.android))
* [Friendiqa](https://git.friendi.ca/lubuwest/Friendiqa) (Gibt es im Google Playstore oder als [binary Repository](https://freunde.ma-nic.de/display/3e98eba8185a13c5bdbf3d1539646854) für F-Droid)

View file

@ -42,7 +42,6 @@ use Friendica\Model\Post;
use Friendica\Model\Profile;
use Friendica\Model\User;
use Friendica\Model\Verb;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException;
use Friendica\Network\HTTPException\BadRequestException;
@ -55,11 +54,9 @@ use Friendica\Network\HTTPException\UnauthorizedException;
use Friendica\Object\Image;
use Friendica\Protocol\Activity;
use Friendica\Security\BasicAuth;
use Friendica\Security\OAuth;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Images;
use Friendica\Util\Network;
use Friendica\Util\Proxy;
use Friendica\Util\Strings;
require_once __DIR__ . '/../mod/item.php';
@ -73,28 +70,6 @@ define('API_METHOD_DELETE', 'POST,DELETE');
define('API_LOG_PREFIX', 'API {action} - ');
$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).
*/
function api_user()
{
$user = OAuth::getCurrentUserID();
if (!empty($user)) {
return $user;
}
if (!empty($_SESSION['allow_api'])) {
return local_user();
}
return false;
}
/**
* Get source name from API client
@ -128,19 +103,6 @@ function api_source()
return "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"
* @throws Exception
*/
function api_date($str)
{
// Wed May 23 06:01:13 +0000 2007
return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
}
/**
* Register a function to be the endpoint for defined API path.
*
@ -171,24 +133,6 @@ function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY
];
}
/**
* 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.
*
* @param string $method Required methods, uppercase, separated by comma
* @return bool
*/
function api_check_method($method)
{
if ($method == "*") {
return true;
}
return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
}
/**
* Main API entry point
*
@ -201,7 +145,7 @@ function api_check_method($method)
*/
function api_call(App $a, App\Arguments $args = null)
{
global $API, $called_api;
global $API;
if ($args == null) {
$args = DI::args();
@ -224,13 +168,7 @@ function api_call(App $a, App\Arguments $args = null)
try {
foreach ($API as $p => $info) {
if (strpos($args->getCommand(), $p) === 0) {
if (!api_check_method($info['method'])) {
throw new MethodNotAllowedException();
}
$called_api = explode("/", $p);
if (!empty($info['auth']) && api_user() === false) {
if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
BasicAuth::getCurrentUserID(true);
Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
}
@ -290,7 +228,6 @@ function api_call(App $a, App\Arguments $args = null)
/**
* Set values for RSS template
*
* @param App $a
* @param array $arr Array to be passed to template
* @param array $user_info User info
* @return array
@ -300,10 +237,15 @@ function api_call(App $a, App\Arguments $args = null)
* @throws UnauthorizedException
* @todo find proper type-hints
*/
function api_rss_extra(App $a, $arr, $user_info)
function api_rss_extra($arr, $user_info)
{
if (is_null($user_info)) {
$user_info = api_get_user();
$uid = BaseApi::getCurrentUserID();
if (empty($uid)) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
}
$arr['$user'] = $user_info;
@ -311,7 +253,7 @@ function api_rss_extra(App $a, $arr, $user_info)
'alternate' => $user_info['url'],
'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
'base' => DI::baseUrl(),
'updated' => api_date(null),
'updated' => DateTimeFormat::utc(null, DateTimeFormat::API),
'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'language' => $user_info['lang'],
'logo' => DI::baseUrl() . "/images/friendica-32.png",
@ -340,294 +282,6 @@ function api_unique_id_to_nurl($id)
}
}
/**
* Get user info array.
*
* @param App $a App
* @param int|string $contact_id Contact ID or URL
* @return array|bool
* @throws BadRequestException
* @throws ImagickException
* @throws InternalServerErrorException
* @throws UnauthorizedException
*/
function api_get_user($contact_id = null)
{
global $called_api;
$user = null;
$extra_query = "";
$url = "";
Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
// Searching for contact URL
if (!is_null($contact_id) && (intval($contact_id) == 0)) {
$user = Strings::normaliseLink($contact_id);
$url = $user;
$extra_query = "AND `contact`.`nurl` = ? ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
}
// Searching for contact id with uid = 0
if (!is_null($contact_id) && (intval($contact_id) != 0)) {
$user = api_unique_id_to_nurl(intval($contact_id));
if ($user == "") {
throw new BadRequestException("User ID ".$contact_id." not found.");
}
$url = $user;
$extra_query = "AND `contact`.`nurl` = ? ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
}
if (is_null($user) && !empty($_GET['user_id'])) {
$user = api_unique_id_to_nurl($_GET['user_id']);
if ($user == "") {
throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
}
$url = $user;
$extra_query = "AND `contact`.`nurl` = ? ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
}
if (is_null($user) && !empty($_GET['screen_name'])) {
$user = $_GET['screen_name'];
$extra_query = "AND `contact`.`nick` = ? ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=".intval(api_user());
}
}
if (is_null($user) && !empty($_GET['profileurl'])) {
$user = Strings::normaliseLink($_GET['profileurl']);
$extra_query = "AND `contact`.`nurl` = ? ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=".intval(api_user());
}
}
// $called_api is the API path exploded on / and is expected to have at least 2 elements
if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
$argid = count($called_api);
if (!empty(DI::args()->getArgv()[$argid])) {
$data = explode(".", DI::args()->getArgv()[$argid]);
if (count($data) > 1) {
[$user, $null] = $data;
}
}
if (is_numeric($user)) {
$user = api_unique_id_to_nurl(intval($user));
if ($user != "") {
$url = $user;
$extra_query = "AND `contact`.`nurl` = ? ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
}
} else {
$extra_query = "AND `contact`.`nick` = ? ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
}
}
Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
if (!$user) {
if (api_user() === false) {
BasicAuth::getCurrentUserID(true);
return false;
} else {
$user = api_user();
$extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
}
}
Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
// user info
$uinfo = DBA::toArray(DBA::p(
"SELECT *, `contact`.`id` AS `cid` FROM `contact`
WHERE 1
$extra_query",
$user
));
// Selecting the id by priority, friendica first
if (is_array($uinfo)) {
api_best_nickname($uinfo);
}
// if the contact wasn't found, fetch it from the contacts with uid = 0
if (!DBA::isResult($uinfo)) {
if ($url == "") {
throw new BadRequestException("User not found.");
}
$contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
if (DBA::isResult($contact)) {
$ret = [
'id' => $contact["id"],
'id_str' => (string) $contact["id"],
'name' => $contact["name"],
'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
'description' => BBCode::toPlaintext($contact["about"] ?? ''),
'profile_image_url' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
'profile_image_url_https' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_THUMB),
'profile_image_url_large' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_SMALL),
'url' => $contact["url"],
'protected' => false,
'followers_count' => 0,
'friends_count' => 0,
'listed_count' => 0,
'created_at' => api_date($contact["created"]),
'favourites_count' => 0,
'utc_offset' => 0,
'time_zone' => 'UTC',
'geo_enabled' => false,
'verified' => false,
'statuses_count' => 0,
'lang' => '',
'contributors_enabled' => false,
'is_translator' => false,
'is_translation_enabled' => false,
'following' => false,
'follow_request_sent' => false,
'statusnet_blocking' => false,
'notifications' => false,
'statusnet_profile_url' => $contact["url"],
'uid' => 0,
'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
'pid' => Contact::getIdForURL($contact["url"], 0, false),
'self' => 0,
'network' => $contact["network"],
];
return $ret;
} else {
throw new BadRequestException("User ".$url." not found.");
}
}
if ($uinfo[0]['self']) {
if ($uinfo[0]['network'] == "") {
$uinfo[0]['network'] = Protocol::DFRN;
}
$usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
$profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
}
$countitems = 0;
$countfriends = 0;
$countfollowers = 0;
$starred = 0;
$pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
if (!empty($profile['about'])) {
$description = $profile['about'];
} else {
$description = $uinfo[0]["about"];
}
if (!empty($usr['default-location'])) {
$location = $usr['default-location'];
} elseif (!empty($uinfo[0]["location"])) {
$location = $uinfo[0]["location"];
} else {
$location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
}
$ret = [
'id' => intval($pcontact_id),
'id_str' => (string) intval($pcontact_id),
'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
'location' => $location,
'description' => BBCode::toPlaintext($description ?? ''),
'profile_image_url' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
'profile_image_url_https' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_THUMB),
'profile_image_url_large' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_SMALL),
'url' => $uinfo[0]['url'],
'protected' => false,
'followers_count' => intval($countfollowers),
'friends_count' => intval($countfriends),
'listed_count' => 0,
'created_at' => api_date($uinfo[0]['created']),
'favourites_count' => intval($starred),
'utc_offset' => "0",
'time_zone' => 'UTC',
'geo_enabled' => false,
'verified' => true,
'statuses_count' => intval($countitems),
'lang' => '',
'contributors_enabled' => false,
'is_translator' => false,
'is_translation_enabled' => false,
'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
'follow_request_sent' => false,
'statusnet_blocking' => false,
'notifications' => false,
/// @TODO old way?
//'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
'statusnet_profile_url' => $uinfo[0]['url'],
'uid' => intval($uinfo[0]['uid']),
'cid' => intval($uinfo[0]['cid']),
'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
'self' => $uinfo[0]['self'],
'network' => $uinfo[0]['network'],
];
// If this is a local user and it uses Frio, we can get its color preferences.
if ($ret['self']) {
$theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
if ($theme_info['theme'] === 'frio') {
$schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
if ($schema && ($schema != '---')) {
if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
$schemefile = 'view/theme/frio/schema/'.$schema.'.php';
require_once $schemefile;
}
} else {
$nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
$link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
$bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
}
if (empty($nav_bg)) {
$nav_bg = "#708fa0";
}
if (empty($link_color)) {
$link_color = "#6fdbe8";
}
if (empty($bgcolor)) {
$bgcolor = "#ededed";
}
$ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
$ret['profile_link_color'] = str_replace('#', '', $link_color);
$ret['profile_background_color'] = str_replace('#', '', $bgcolor);
}
}
return $ret;
}
/**
* return api-formatted array for item's author and owner
*
@ -641,14 +295,20 @@ function api_get_user($contact_id = null)
*/
function api_item_get_user(App $a, $item)
{
$status_user = api_get_user($item['author-id'] ?? null);
if (empty($item['author-id'])) {
$item['author-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
}
$status_user = DI::twitterUser()->createFromContactId($item['author-id'], BaseApi::getCurrentUserID())->toArray();
$author_user = $status_user;
$status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
$owner_user = api_get_user($item['owner-id'] ?? null);
if (empty($item['owner-id'])) {
$item['owner-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
}
$owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], BaseApi::getCurrentUserID())->toArray();
} else {
$owner_user = $author_user;
}
@ -676,21 +336,17 @@ function api_item_get_user(App $a, $item)
*/
function api_account_verify_credentials($type)
{
$a = DI::app();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false) {
throw new ForbiddenException();
}
unset($_REQUEST['user_id']);
unset($_GET['user_id']);
unset($_REQUEST["user_id"]);
unset($_GET["user_id"]);
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
unset($_REQUEST['screen_name']);
unset($_GET['screen_name']);
$skip_status = $_REQUEST['skip_status'] ?? false;
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
// "verified" isn't used here in the standard
unset($user_info["verified"]);
@ -746,13 +402,11 @@ function api_statuses_mediap($type)
{
$a = DI::app();
if (api_user() === false) {
logger::notice('api_statuses_update: no user');
throw new ForbiddenException();
}
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$_REQUEST['profile_uid'] = api_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
$_REQUEST['api_source'] = true;
$txt = requestdata('status') ?? '';
/// @TODO old-lost code?
@ -800,12 +454,7 @@ function api_statuses_update($type)
{
$a = DI::app();
if (api_user() === false) {
logger::notice('api_statuses_update: no user');
throw new ForbiddenException();
}
api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// convert $_POST array items to the form we use for web posts.
if (requestdata('htmlstatus')) {
@ -843,7 +492,7 @@ function api_statuses_update($type)
if (requestdata('lat') && requestdata('long')) {
$_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
}
$_REQUEST['profile_uid'] = api_user();
$_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
if (!$parent) {
// Check for throttling (maximum posts per day, week and month)
@ -851,11 +500,11 @@ function api_statuses_update($type)
if ($throttle_day > 0) {
$datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
$condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
$condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
$posts_day = Post::count($condition);
if ($posts_day > $throttle_day) {
logger::info('Daily posting limit reached for user '.api_user());
logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
// die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
throw new TooManyRequestsException(DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
}
@ -865,11 +514,11 @@ function api_statuses_update($type)
if ($throttle_week > 0) {
$datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
$condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
$condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
$posts_week = Post::count($condition);
if ($posts_week > $throttle_week) {
logger::info('Weekly posting limit reached for user '.api_user());
logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
// die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
throw new TooManyRequestsException(DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
}
@ -879,11 +528,11 @@ function api_statuses_update($type)
if ($throttle_month > 0) {
$datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
$condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
$condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
$posts_month = Post::count($condition);
if ($posts_month > $throttle_month) {
logger::info('Monthly posting limit reached for user '.api_user());
logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
// die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
throw new TooManyRequestsException(DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
}
@ -908,7 +557,7 @@ function api_statuses_update($type)
$media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
(SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
if (!empty($media)) {
$ressources[] = $media[0]['resource-id'];
@ -947,7 +596,7 @@ function api_statuses_update($type)
$_REQUEST['api_source'] = true;
if (empty($_REQUEST['source'])) {
$_REQUEST["source"] = api_source();
$_REQUEST['source'] = api_source();
}
// call out normal post function
@ -956,7 +605,7 @@ function api_statuses_update($type)
if (!empty($ressources) && !empty($item_id)) {
$item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
foreach ($ressources as $ressource) {
Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
}
}
@ -983,12 +632,7 @@ function api_media_upload()
{
$a = DI::app();
if (api_user() === false) {
logger::notice('no user');
throw new ForbiddenException();
}
api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
if (empty($_FILES['media'])) {
// Output error
@ -1036,14 +680,7 @@ api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST)
*/
function api_media_metadata_create($type)
{
$a = DI::app();
if (api_user() === false) {
Logger::info('no user');
throw new ForbiddenException();
}
api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$postdata = Network::postdata();
@ -1066,7 +703,7 @@ function api_media_metadata_create($type)
Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
$condition = ['id' => $data['media_id'], 'uid' => api_user()];
$condition = ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
$photo = DBA::selectFirst('photo', ['resource-id'], $condition);
if (!DBA::isResult($photo)) {
throw new BadRequestException("Metadata not found.");
@ -1149,9 +786,9 @@ function api_get_item(array $condition)
*/
function api_users_show($type)
{
$a = Friendica\DI::app();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$item = api_get_last_status($user_info['pid'], $user_info['uid']);
if (!empty($item)) {
@ -1183,8 +820,6 @@ api_register_func('api/externalprofile/show', 'api_users_show');
*/
function api_users_search($type)
{
$a = DI::app();
$userlist = [];
if (!empty($_GET['q'])) {
@ -1202,7 +837,7 @@ function api_users_search($type)
if (DBA::isResult($contacts)) {
$k = 0;
foreach ($contacts as $contact) {
$user_info = api_get_user($contact['id']);
$user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
if ($type == 'xml') {
$userlist[$k++ . ':user'] = $user_info;
@ -1245,7 +880,10 @@ function api_users_lookup($type)
if (!empty($_REQUEST['user_id'])) {
foreach (explode(',', $_REQUEST['user_id']) as $id) {
if (!empty($id)) {
$users[] = api_get_user($id);
$cid = BaseApi::getContactIDForSearchterm($id);
if (!empty($cid)) {
$users[] = DI::twitterUser()->createFromContactId($cid, BaseApi::getCurrentUserID())->toArray();
}
}
}
}
@ -1276,12 +914,9 @@ api_register_func('api/users/lookup', 'api_users_lookup', true);
*/
function api_search($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
if (empty($_REQUEST['q'])) {
throw new BadRequestException('q parameter is required.');
@ -1308,7 +943,7 @@ function api_search($type)
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
$searchTerm = $matches[1];
$condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
$condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, BaseApi::getCurrentUserID()];
$tags = DBA::select('tag-search-view', ['uri-id'], $condition);
$uriids = [];
while ($tag = DBA::fetch($tags)) {
@ -1331,7 +966,7 @@ function api_search($type)
" . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
AND `body` LIKE CONCAT('%',?,'%')",
$since_id, api_user(), $_REQUEST['q']];
$since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
if ($max_id > 0) {
$condition[0] .= ' AND `id` <= ?';
$condition[] = $max_id;
@ -1341,7 +976,7 @@ function api_search($type)
$statuses = [];
if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
$id = Item::fetchByLink($searchTerm, api_user());
$id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
if (!$id) {
// Public post
$id = Item::fetchByLink($searchTerm);
@ -1352,7 +987,7 @@ function api_search($type)
}
}
$statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
$statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$data['status'] = api_format_items(Post::toArray($statuses), $user_info);
@ -1383,18 +1018,15 @@ api_register_func('api/search', 'api_search', true);
*/
function api_statuses_home_timeline($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
unset($_REQUEST["user_id"]);
unset($_GET["user_id"]);
unset($_REQUEST['user_id']);
unset($_GET['user_id']);
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
unset($_REQUEST['screen_name']);
unset($_GET['screen_name']);
// get last network messages
@ -1409,7 +1041,7 @@ function api_statuses_home_timeline($type)
$start = max(0, ($page - 1) * $count);
$condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
if ($max_id > 0) {
$condition[0] .= " AND `id` <= ?";
@ -1425,7 +1057,7 @@ function api_statuses_home_timeline($type)
}
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$items = Post::toArray($statuses);
@ -1451,7 +1083,7 @@ function api_statuses_home_timeline($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -1477,12 +1109,9 @@ api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline',
*/
function api_statuses_public_timeline($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
// get last network messages
@ -1506,7 +1135,7 @@ function api_statuses_public_timeline($type)
}
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$r = Post::toArray($statuses);
} else {
@ -1523,7 +1152,7 @@ function api_statuses_public_timeline($type)
}
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$r = Post::toArray($statuses);
}
@ -1537,7 +1166,7 @@ function api_statuses_public_timeline($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -1560,12 +1189,9 @@ api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline'
*/
function api_statuses_networkpublic_timeline($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$since_id = $_REQUEST['since_id'] ?? 0;
$max_id = $_REQUEST['max_id'] ?? 0;
@ -1585,7 +1211,7 @@ function api_statuses_networkpublic_timeline($type)
}
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
$statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
$ret = api_format_items($statuses, $user_info, false, $type);
@ -1596,7 +1222,7 @@ function api_statuses_networkpublic_timeline($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -1621,12 +1247,9 @@ api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpu
*/
function api_statuses_show($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
// params
$id = intval(DI::args()->getArgv()[3] ?? 0);
@ -1650,7 +1273,7 @@ function api_statuses_show($type)
throw new BadRequestException(sprintf("There is no status with the id %d", $id));
}
$item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
$item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
if (!DBA::isResult($item)) {
throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
}
@ -1665,7 +1288,7 @@ function api_statuses_show($type)
$params = [];
}
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
/// @TODO How about copying this to above methods which don't check $r ?
if (!DBA::isResult($statuses)) {
@ -1700,12 +1323,9 @@ api_register_func('api/statuses/show', 'api_statuses_show', true);
*/
function api_conversation_show($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
// params
$id = intval(DI::args()->getArgv()[3] ?? 0);
@ -1733,7 +1353,7 @@ function api_conversation_show($type)
throw new BadRequestException("There is no status with the id $id.");
}
$parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
$parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
if (!DBA::isResult($parent)) {
throw new BadRequestException("There is no status with this id.");
}
@ -1741,7 +1361,7 @@ function api_conversation_show($type)
$id = $parent['id'];
$condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
$id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
$id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
if ($max_id > 0) {
$condition[0] .= " AND `id` <= ?";
@ -1749,7 +1369,7 @@ function api_conversation_show($type)
}
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
if (!DBA::isResult($statuses)) {
throw new BadRequestException("There is no status with id $id.");
@ -1780,15 +1400,9 @@ api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
*/
function api_statuses_repeat($type)
{
global $called_api;
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$id = intval(DI::args()->getArgv()[3] ?? 0);
@ -1809,7 +1423,7 @@ function api_statuses_repeat($type)
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())) {
if (!Item::performActivity($id, 'announce', BaseApi::getCurrentUserID())) {
throw new InternalServerErrorException();
}
@ -1829,11 +1443,11 @@ function api_statuses_repeat($type)
$post .= "[/share]";
}
$_REQUEST['body'] = $post;
$_REQUEST['profile_uid'] = api_user();
$_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
$_REQUEST['api_source'] = true;
if (empty($_REQUEST['source'])) {
$_REQUEST["source"] = api_source();
$_REQUEST['source'] = api_source();
}
$item_id = item_post($a);
@ -1843,7 +1457,6 @@ function api_statuses_repeat($type)
}
// output the post that we just posted.
$called_api = [];
return api_status_show($type, $item_id);
}
@ -1865,13 +1478,7 @@ api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHO
*/
function api_statuses_destroy($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$id = intval(DI::args()->getArgv()[3] ?? 0);
@ -1889,7 +1496,7 @@ function api_statuses_destroy($type)
$ret = api_statuses_show($type);
Item::deleteForUser(['id' => $id], api_user());
Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
return $ret;
}
@ -1912,18 +1519,15 @@ api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METH
*/
function api_statuses_mentions($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
unset($_REQUEST["user_id"]);
unset($_GET["user_id"]);
unset($_REQUEST['user_id']);
unset($_GET['user_id']);
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
unset($_REQUEST['screen_name']);
unset($_GET['screen_name']);
// get last network messages
@ -1941,11 +1545,11 @@ function api_statuses_mentions($type)
$condition = [
GRAVITY_PARENT, GRAVITY_COMMENT,
api_user(),
BaseApi::getCurrentUserID(),
Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
api_user(), $since_id,
BaseApi::getCurrentUserID(), $since_id,
];
if ($max_id > 0) {
@ -1956,7 +1560,7 @@ function api_statuses_mentions($type)
array_unshift($condition, $query);
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
@ -1965,7 +1569,7 @@ function api_statuses_mentions($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -1990,14 +1594,11 @@ api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
*/
function api_statuses_user_timeline($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
$since_id = $_REQUEST['since_id'] ?? 0;
$max_id = $_REQUEST['max_id'] ?? 0;
@ -2011,7 +1612,7 @@ function api_statuses_user_timeline($type)
$start = max(0, ($page - 1) * $count);
$condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
if ($user_info['self'] == 1) {
$condition[0] .= ' AND `wall` ';
@ -2032,7 +1633,7 @@ function api_statuses_user_timeline($type)
$condition[] = $max_id;
}
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
@ -2043,7 +1644,7 @@ function api_statuses_user_timeline($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -2069,11 +1670,7 @@ api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', tr
*/
function api_favorites_create_destroy($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// for versioned api.
/// @TODO We need a better global soluton
@ -2092,7 +1689,7 @@ function api_favorites_create_destroy($type)
$itemid = intval($_REQUEST['id'] ?? 0);
}
$item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
$item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
if (!DBA::isResult($item)) {
throw new BadRequestException("Invalid item.");
@ -2115,8 +1712,7 @@ function api_favorites_create_destroy($type)
throw new InternalServerErrorException("DB error");
}
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$rets = api_format_items([$item], $user_info, false, $type);
$ret = $rets[0];
@ -2125,7 +1721,7 @@ function api_favorites_create_destroy($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -2150,16 +1746,9 @@ api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true,
*/
function api_favorites($type)
{
global $called_api;
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$a = DI::app();
$user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$called_api = [];
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
// in friendica starred item are private
// return favorites only for self
@ -2177,7 +1766,7 @@ function api_favorites($type)
$start = max(0, ($page - 1) * $count);
$condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
@ -2186,7 +1775,7 @@ function api_favorites($type)
$condition[] = $max_id;
}
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
}
@ -2198,7 +1787,7 @@ function api_favorites($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -2225,7 +1814,7 @@ function api_format_messages($item, $recipient, $sender)
'sender_id' => $sender['id'],
'text' => "",
'recipient_id' => $recipient['id'],
'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
'sender_screen_name' => $sender['screen_name'],
'recipient_screen_name' => $recipient['screen_name'],
'sender' => $sender,
@ -2624,8 +2213,6 @@ function api_contactlink_to_array($txt)
*/
function api_format_items_activities($item, $type = "json")
{
$a = DI::app();
$activities = [
'like' => [],
'dislike' => [],
@ -2643,7 +2230,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($parent_item['author-id']);
$user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
switch ($parent_item['verb']) {
case Activity::LIKE:
$activities['like'][] = $user;
@ -2702,7 +2289,7 @@ function api_format_items_activities($item, $type = "json")
*/
function api_format_items($items, $user_info, $filter_user = false, $type = "json")
{
$a = Friendica\DI::app();
$a = DI::app();
$ret = [];
@ -2740,7 +2327,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 = Friendica\DI::app();
$a = DI::app();
if (empty($status_user) || empty($author_user) || empty($owner_user)) {
[$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
@ -2761,7 +2348,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
$status = [
'text' => $converted["text"],
'truncated' => false,
'created_at'=> api_date($item['created']),
'created_at'=> DateTimeFormat::utc($item['created'], DateTimeFormat::API),
'in_reply_to_status_id' => $in_reply_to['status_id'],
'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
'source' => (($item['app']) ? $item['app'] : 'web'),
@ -2807,7 +2394,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
if (!empty($announce)) {
$retweeted_item = $item;
$item = $announce;
$status['friendica_owner'] = api_get_user($announce['author-id']);
$status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
}
}
@ -2826,7 +2413,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
$quoted_status['text'] = $conv_quoted['text'];
$quoted_status['statusnet_html'] = $conv_quoted['html'];
try {
$quoted_status["user"] = api_get_user($quoted_item["author-id"]);
$quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
} catch (BadRequestException $e) {
// user not found. should be found?
/// @todo check if the user should be always found
@ -2848,7 +2435,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
unset($retweeted_status['statusnet_conversation_id']);
$status['user'] = $status['friendica_owner'];
try {
$retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
$retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
} catch (BadRequestException $e) {
// user not found. should be found?
/// @todo check if the user should be always found
@ -2860,7 +2447,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use
$retweeted_status['text'] = $rt_converted["text"];
$retweeted_status['statusnet_html'] = $rt_converted["html"];
$retweeted_status['friendica_html'] = $rt_converted["html"];
$retweeted_status['created_at'] = api_date($retweeted_item['created']);
$retweeted_status['created_at'] = DateTimeFormat::utc($retweeted_item['created'], DateTimeFormat::API);
if (!empty($quoted_status)) {
$retweeted_status['quoted_status'] = $quoted_status;
@ -2930,14 +2517,10 @@ api_register_func('api/lists/subscriptions', 'api_lists_list', true);
*/
function api_lists_ownerships($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$uid = $user_info['uid'];
$groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
@ -2979,18 +2562,15 @@ api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
*/
function api_lists_statuses($type)
{
$a = DI::app();
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$user_info = api_get_user();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
unset($_REQUEST["user_id"]);
unset($_GET["user_id"]);
unset($_REQUEST['user_id']);
unset($_GET['user_id']);
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
unset($_REQUEST['screen_name']);
unset($_GET['screen_name']);
if (empty($_REQUEST['list_id'])) {
throw new BadRequestException('list_id not specified');
@ -3008,7 +2588,7 @@ function api_lists_statuses($type)
$groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
$gids = array_column($groups, 'contact-id');
$condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
$condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
$condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
if ($max_id > 0) {
@ -3025,7 +2605,7 @@ function api_lists_statuses($type)
}
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
$statuses = Post::selectForUser(api_user(), [], $condition, $params);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
$items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
@ -3034,7 +2614,7 @@ function api_lists_statuses($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -3060,11 +2640,7 @@ api_register_func('api/lists/statuses', 'api_lists_statuses', true);
*/
function api_statuses_f($qtype)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
// pagination
$count = $_GET['count'] ?? 20;
@ -3072,7 +2648,7 @@ function api_statuses_f($qtype)
$start = max(0, ($page - 1) * $count);
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
/* this is to stop Hotot to load friends multiple times
@ -3107,7 +2683,7 @@ function api_statuses_f($qtype)
// @todo This query most likely can be replaced with a Contact::select...
$r = DBA::toArray(DBA::p(
"SELECT `nurl`
"SELECT `id`
FROM `contact`
WHERE `uid` = ?
AND NOT `self`
@ -3115,14 +2691,14 @@ function api_statuses_f($qtype)
$sql_extra
ORDER BY `nick`
LIMIT ?, ?",
api_user(),
BaseApi::getCurrentUserID(),
$start,
$count
));
$ret = [];
foreach ($r as $cid) {
$user = api_get_user($cid['nurl']);
$user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
// "uid" and "self" are only needed for some internal stuff, so remove it from here
unset($user["uid"]);
unset($user["self"]);
@ -3246,29 +2822,30 @@ api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
*/
function api_direct_messages_new($type)
{
$a = DI::app();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
if (api_user() === false) {
throw new ForbiddenException();
}
$uid = BaseApi::getCurrentUserID();
if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
return;
}
$sender = api_get_user();
$sender = DI::twitterUser()->createFromUserId($uid)->toArray();
$recipient = null;
if (!empty($_POST['screen_name'])) {
$contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
$contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
if (DBA::isResult($contacts)) {
// Selecting the id by priority, friendica first
api_best_nickname($contacts);
$recipient = api_get_user($contacts[0]['nurl']);
$recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
}
} else {
$recipient = api_get_user($_POST['user_id']);
$cid = BaseApi::getContactIDForSearchterm($_POST['user_id']);
if (!empty($cid)) {
$recipient = DI::twitterUser()->createFromContactId($cid, $uid)->toArray();
}
}
if (empty($recipient)) {
@ -3277,7 +2854,7 @@ function api_direct_messages_new($type)
$replyto = '';
if (!empty($_REQUEST['replyto'])) {
$mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
$mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
$replyto = $mail['parent-uri'];
$sub = $mail['title'];
} else {
@ -3303,7 +2880,7 @@ function api_direct_messages_new($type)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $sender);
$data = api_rss_extra($data, $sender);
break;
}
@ -3327,14 +2904,10 @@ api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, AP
*/
function api_direct_messages_destroy($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
//required
$id = $_REQUEST['id'] ?? 0;
// optional
@ -3400,11 +2973,8 @@ api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy',
*/
function api_friendships_destroy($type)
{
$uid = api_user();
if ($uid === false) {
throw new HTTPException\ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$uid = BaseApi::getCurrentUserID();
$owner = User::getOwnerDataById($uid);
if (!$owner) {
@ -3482,10 +3052,8 @@ api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, AP
*/
function api_direct_messages_box($type, $box, $verbose)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
// params
$count = $_GET['count'] ?? 20;
$page = $_REQUEST['page'] ?? 1;
@ -3497,16 +3065,14 @@ function api_direct_messages_box($type, $box, $verbose)
$screen_name = $_REQUEST['screen_name'] ?? '';
// caller user info
unset($_REQUEST["user_id"]);
unset($_GET["user_id"]);
unset($_REQUEST['user_id']);
unset($_GET['user_id']);
unset($_REQUEST["screen_name"]);
unset($_GET["screen_name"]);
unset($_REQUEST['screen_name']);
unset($_GET['screen_name']);
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$user_info = api_get_user();
if ($user_info === false) {
throw new ForbiddenException();
}
$profile_url = $user_info["url"];
// pagination
@ -3537,7 +3103,7 @@ function api_direct_messages_box($type, $box, $verbose)
$r = DBA::toArray(DBA::p(
"SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
api_user(),
BaseApi::getCurrentUserID(),
$since_id,
$start,
$count
@ -3551,9 +3117,9 @@ function api_direct_messages_box($type, $box, $verbose)
foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url) {
$recipient = $user_info;
$sender = api_get_user(Strings::normaliseLink($item['contact-url']));
$sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
} elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
$recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
$recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
$sender = $user_info;
}
@ -3568,7 +3134,7 @@ function api_direct_messages_box($type, $box, $verbose)
case "atom":
break;
case "rss":
$data = api_rss_extra($a, $data, $user_info);
$data = api_rss_extra($data, $user_info);
break;
}
@ -3651,14 +3217,13 @@ api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
*/
function api_fr_photos_list($type)
{
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$r = DBA::toArray(DBA::p(
"SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
BaseApi::getCurrentUserID(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
));
$typetoext = [
'image/jpeg' => 'jpg',
@ -3702,9 +3267,8 @@ function api_fr_photos_list($type)
*/
function api_fr_photo_create_update($type)
{
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// input params
$photo_id = $_REQUEST['photo_id'] ?? null;
$desc = $_REQUEST['desc'] ?? null;
@ -3737,7 +3301,7 @@ function api_fr_photo_create_update($type)
$mode = "update";
// check if photo is existing in databasei
if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
throw new BadRequestException("photo not available");
}
}
@ -3799,7 +3363,7 @@ function api_fr_photo_create_update($type)
$result = false;
if (count($updated_fields) > 0) {
$nothingtodo = false;
$result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
$result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
} else {
$nothingtodo = true;
}
@ -3840,9 +3404,8 @@ function api_fr_photo_create_update($type)
*/
function api_fr_photo_detail($type)
{
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
if (empty($_REQUEST['photo_id'])) {
throw new BadRequestException("No photo id.");
}
@ -3872,9 +3435,8 @@ function api_fr_photo_detail($type)
*/
function api_account_update_profile_image($type)
{
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// input params
$profile_id = $_REQUEST['profile_id'] ?? 0;
@ -3885,7 +3447,7 @@ function api_account_update_profile_image($type)
// check if specified profile id is valid
if ($profile_id != 0) {
$profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
$profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
// error message if specified profile id is not in database
if (!DBA::isResult($profile)) {
throw new BadRequestException("profile_id not available");
@ -3921,18 +3483,18 @@ function api_account_update_profile_image($type)
// change specified profile or all profiles to the new resource-id
if ($is_default_profile) {
$condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
$condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
} else {
$fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
}
Contact::updateSelfFromUserID(api_user(), true);
Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
// Update global directory in background
Profile::publishUpdate(api_user());
Profile::publishUpdate(BaseApi::getCurrentUserID());
// output for client
if ($data) {
@ -3964,8 +3526,11 @@ api_register_func('api/account/update_profile_image', 'api_account_update_profil
*/
function api_account_update_profile($type)
{
$local_user = api_user();
$api_user = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$local_user = BaseApi::getCurrentUserID();
$api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
if (!empty($_POST['name'])) {
DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
@ -4010,7 +3575,7 @@ function check_acl_input($acl_string)
foreach ($cid_array as $cid) {
$cid = str_replace("<", "", $cid);
$cid = str_replace(">", "", $cid);
$condition = ['id' => $cid, 'uid' => api_user()];
$condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
$contact_not_found |= !DBA::exists('contact', $condition);
}
return $contact_not_found;
@ -4112,13 +3677,13 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
// upload normal image (scales 0, 1, 2)
logger::info("photo upload: starting new photo upload");
$r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: image upload with scale 0 (original size) failed");
}
if ($width > 640 || $height > 640) {
$Image->scaleDown(640);
$r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: image upload with scale 1 (640x640) failed");
}
@ -4126,7 +3691,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
if ($width > 320 || $height > 320) {
$Image->scaleDown(320);
$r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: image upload with scale 2 (320x320) failed");
}
@ -4138,7 +3703,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
if ($width > 300 || $height > 300) {
$Image->scaleDown(300);
$r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
}
@ -4146,7 +3711,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
if ($width > 80 || $height > 80) {
$Image->scaleDown(80);
$r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
}
@ -4154,7 +3719,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
if ($width > 48 || $height > 48) {
$Image->scaleDown(48);
$r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
}
@ -4189,12 +3754,12 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
{
// get data about the api authenticated user
$uri = Item::newURI(intval(api_user()));
$owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
$uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
$owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
$arr = [];
$arr['guid'] = System::createUUID();
$arr['uid'] = intval(api_user());
$arr['uid'] = intval(BaseApi::getCurrentUserID());
$arr['uri'] = $uri;
$arr['type'] = 'photo';
$arr['wall'] = 1;
@ -4245,12 +3810,9 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
*/
function prepare_photo_data($type, $scale, $photo_id)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
if ($user_info === false) {
throw new ForbiddenException();
}
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
$data_sql = ($scale === false ? "" : "data, ");
@ -4264,7 +3826,7 @@ function prepare_photo_data($type, $scale, $photo_id)
FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
`resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
`type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
local_user(),
BaseApi::getCurrentUserID(),
$photo_id
));
@ -4307,7 +3869,7 @@ function prepare_photo_data($type, $scale, $photo_id)
}
// retrieve item element for getting activities (like, dislike etc.) related to photo
$condition = ['uid' => api_user(), 'resource-id' => $photo_id];
$condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
$item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
if (!DBA::isResult($item)) {
throw new NotFoundException('Photo-related item not found.');
@ -4317,9 +3879,9 @@ function prepare_photo_data($type, $scale, $photo_id)
// retrieve comments on photo
$condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
$item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
$item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
$statuses = Post::selectForUser(api_user(), [], $condition);
$statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
// prepare output of comments
$commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
@ -4539,14 +4101,10 @@ function api_best_nickname(&$contacts)
*/
function api_friendica_group_show($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$gid = $_REQUEST['gid'] ?? 0;
$uid = $user_info['uid'];
@ -4572,13 +4130,13 @@ function api_friendica_group_show($type)
$user_element = "users";
$k = 0;
foreach ($members as $member) {
$user = api_get_user($member['nurl']);
$user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
$users[$k++.":user"] = $user;
}
} else {
$user_element = "user";
foreach ($members as $member) {
$user = api_get_user($member['nurl']);
$user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
$users[] = $user;
}
}
@ -4604,14 +4162,10 @@ api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
*/
function api_lists_destroy($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$gid = $_REQUEST['list_id'] ?? 0;
$uid = $user_info['uid'];
@ -4709,14 +4263,10 @@ function group_create($name, $uid, $users = [])
*/
function api_friendica_group_create($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$name = $_REQUEST['name'] ?? '';
$uid = $user_info['uid'];
$json = json_decode($_POST['json'], true);
@ -4744,14 +4294,10 @@ api_register_func('api/friendica/group_create', 'api_friendica_group_create', tr
*/
function api_lists_create($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$name = $_REQUEST['name'] ?? '';
$uid = $user_info['uid'];
@ -4784,14 +4330,10 @@ api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST)
*/
function api_friendica_group_update($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$uid = $user_info['uid'];
$gid = $_REQUEST['gid'] ?? 0;
$name = $_REQUEST['name'] ?? '';
@ -4858,14 +4400,10 @@ api_register_func('api/friendica/group_update', 'api_friendica_group_update', tr
*/
function api_lists_update($type)
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$gid = $_REQUEST['list_id'] ?? 0;
$name = $_REQUEST['name'] ?? '';
$uid = $user_info['uid'];
@ -4911,12 +4449,10 @@ api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST)
*/
function api_friendica_notification_seen($type)
{
$a = DI::app();
$user_info = api_get_user();
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
if (api_user() === false || $user_info === false) {
throw new ForbiddenException();
}
if (DI::args()->getArgc() !== 4) {
throw new BadRequestException('Invalid argument count');
}
@ -4925,7 +4461,7 @@ function api_friendica_notification_seen($type)
try {
$Notify = DI::notify()->selectOneById($id);
if ($Notify->uid !== api_user()) {
if ($Notify->uid !== BaseApi::getCurrentUserID()) {
throw new NotFoundException();
}
@ -4937,7 +4473,7 @@ function api_friendica_notification_seen($type)
DI::notify()->save($Notify);
if ($Notify->otype === Notification\ObjectType::ITEM) {
$item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
$item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
if (DBA::isResult($item)) {
// we found the item, return it to the user
$ret = api_format_items([$item], $user_info, false, $type);
@ -4974,14 +4510,10 @@ api_register_func('api/friendica/notification/seen', 'api_friendica_notification
*/
function api_friendica_direct_messages_search($type, $box = "")
{
$a = DI::app();
if (api_user() === false) {
throw new ForbiddenException();
}
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
// params
$user_info = api_get_user();
$user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
$searchstring = $_REQUEST['searchstring'] ?? '';
$uid = $user_info['uid'];
@ -5010,9 +4542,9 @@ function api_friendica_direct_messages_search($type, $box = "")
foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url) {
$recipient = $user_info;
$sender = api_get_user(Strings::normaliseLink($item['contact-url']));
$sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
} elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
$recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
$recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
$sender = $user_info;
}

View file

@ -41,10 +41,11 @@ $a = \Friendica\DI::app();
\Friendica\DI::mode()->setExecutor(\Friendica\App\Mode::INDEX);
$a->runFrontend(
$dice->create(\Friendica\App\Module::class),
$dice->create(\Friendica\App\ModuleController::class),
$dice->create(\Friendica\App\Router::class),
$dice->create(\Friendica\Core\PConfig\Capability\IManagePersonalConfigValues::class),
$dice->create(\Friendica\Security\Authentication::class),
$dice->create(\Friendica\App\Page::class),
$dice,
$start_time
);

View file

@ -40,7 +40,7 @@ use Friendica\Protocol\DFRN;
function display_init(App $a)
{
if (ActivityPub::isRequest()) {
Objects::rawContent(['guid' => DI::args()->getArgv()[1] ?? null]);
(new Objects(DI::l10n(), ['guid' => DI::args()->getArgv()[1] ?? null]))->rawContent();
}
if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {

View file

@ -130,6 +130,15 @@ function editpost_content(App $a)
'$cancel' => DI::l10n()->t('Cancel'),
'$rand_num' => Crypto::randomDigits(12),
// Formatting button labels
'$edbold' => DI::l10n()->t('Bold'),
'$editalic' => DI::l10n()->t('Italic'),
'$eduline' => DI::l10n()->t('Underline'),
'$edquote' => DI::l10n()->t('Quote'),
'$edcode' => DI::l10n()->t('Code'),
'$edurl' => DI::l10n()->t('Link'),
'$edattach' => DI::l10n()->t('Link or Media'),
//jot nav tab (used in some themes)
'$message' => DI::l10n()->t('Message'),
'$browser' => DI::l10n()->t('Browser'),

View file

@ -122,7 +122,7 @@ function unfollow_process(string $url)
$owner = User::getOwnerDataById($uid);
if (!$owner) {
\Friendica\Module\Security\Logout::init();
(new \Friendica\Module\Security\Logout())->init();
// NOTREACHED
}

View file

@ -32,6 +32,7 @@ use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\Photo;
use Friendica\Model\User;
use Friendica\Module\BaseApi;
use Friendica\Object\Image;
use Friendica\Util\Images;
use Friendica\Util\Strings;
@ -55,8 +56,7 @@ function wall_upload_post(App $a, $desktopmode = true)
return;
}
} else {
$user_info = api_get_user();
$user = DBA::selectFirst('owner-view', ['id', 'uid', 'nickname', 'page-flags'], ['nickname' => $user_info['screen_name'], 'blocked' => false]);
$user = DBA::selectFirst('owner-view', ['id', 'uid', 'nickname', 'page-flags'], ['uid' => BaseApi::getCurrentUserID(), 'blocked' => false]);
}
} else {
if ($r_json) {

View file

@ -21,10 +21,11 @@
namespace Friendica;
use Dice\Dice;
use Exception;
use Friendica\App\Arguments;
use Friendica\App\BaseURL;
use Friendica\App\Module;
use Friendica\App\ModuleController;
use Friendica\Core\Config\Factory\Config;
use Friendica\Module\Maintenance;
use Friendica\Security\Authentication;
@ -566,16 +567,16 @@ class App
*
* This probably should change to limit the size of this monster method.
*
* @param App\Module $module The determined module
* @param App\ModuleController $module The determined module
* @param App\Router $router
* @param IManagePersonalConfigValues $pconfig
* @param Authentication $auth The Authentication backend of the node
* @param App\Page $page The Friendica page printing container
* @param Authentication $auth The Authentication backend of the node
* @param App\Page $page The Friendica page printing container
*
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public function runFrontend(App\Module $module, App\Router $router, IManagePersonalConfigValues $pconfig, Authentication $auth, App\Page $page, float $start_time)
public function runFrontend(App\ModuleController $module, App\Router $router, IManagePersonalConfigValues $pconfig, Authentication $auth, App\Page $page, Dice $dice, float $start_time)
{
$this->profiler->set($start_time, 'start');
$this->profiler->set(microtime(true), 'classinit');
@ -702,17 +703,17 @@ class App
$page['page_title'] = $moduleName;
if (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED)) {
$module = new Module('maintenance', Maintenance::class);
$module = new ModuleController('maintenance', new Maintenance($this->l10n));
} else {
// determine the module class and save it to the module instance
// @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
$module = $module->determineClass($this->args, $router, $this->config);
$module = $module->determineClass($this->args, $router, $this->config, $dice);
}
// Let the module run it's internal process (init, get, post, ...)
$module->run($this->l10n, $this->baseURL, $this->logger, $this->profiler, $_SERVER, $_POST);
} catch (HTTPException $e) {
ModuleHTTPException::rawContent($e);
(new ModuleHTTPException())->rawContent($e);
}
$page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->profiler, $this->config, $pconfig);

View file

@ -139,14 +139,14 @@ class Mode
/**
* Checks if the site is called via a backend process
*
* @param bool $isBackend True, if the call is from a backend script (daemon, worker, ...)
* @param Module $module The pre-loaded module (just name, not class!)
* @param array $server The $_SERVER variable
* @param MobileDetect $mobileDetect The mobile detection library
* @param bool $isBackend True, if the call is from a backend script (daemon, worker, ...)
* @param ModuleController $module The pre-loaded module (just name, not class!)
* @param array $server The $_SERVER variable
* @param MobileDetect $mobileDetect The mobile detection library
*
* @return Mode returns the determined mode
*/
public function determineRunMode(bool $isBackend, Module $module, array $server, MobileDetect $mobileDetect)
public function determineRunMode(bool $isBackend, ModuleController $module, array $server, MobileDetect $mobileDetect)
{
foreach (self::BACKEND_CONTENT_TYPES as $type) {
if (strpos(strtolower($server['HTTP_ACCEPT'] ?? ''), $type) !== false) {

View file

@ -21,8 +21,9 @@
namespace Friendica\App;
use Dice\Dice;
use Friendica\App;
use Friendica\BaseModule;
use Friendica\Capabilities\ICanHandleRequests;
use Friendica\Core;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\LegacyModule;
@ -38,7 +39,7 @@ use Psr\Log\LoggerInterface;
/**
* Holds the common context of the current, loaded module
*/
class Module
class ModuleController
{
const DEFAULT = 'home';
const DEFAULT_CLASS = Home::class;
@ -77,18 +78,13 @@ class Module
/**
* @var string The module name
*/
private $moduleName;
/**
* @var ?ICanHandleRequests The module object
*/
private $module;
/**
* @var BaseModule The module class
*/
private $module_class;
/**
* @var array The module parameters
*/
private $module_parameters;
/**
* @var bool true, if the module is a backend module
*/
@ -103,40 +99,31 @@ class Module
* @return string
*/
public function getName()
{
return $this->moduleName;
}
/**
* @return ?ICanHandleRequests The base module object
*/
public function getModule(): ?ICanHandleRequests
{
return $this->module;
}
/**
* @return string The base class name
*/
public function getClassName()
{
return $this->module_class;
}
/**
* @return array The module parameters extracted from the route
*/
public function getParameters()
{
return $this->module_parameters;
}
/**
* @return bool True, if the current module is a backend module
* @see Module::BACKEND_MODULES for a list
* @see ModuleController::BACKEND_MODULES for a list
*/
public function isBackend()
{
return $this->isBackend;
}
public function __construct(string $module = self::DEFAULT, string $moduleClass = self::DEFAULT_CLASS, array $moduleParameters = [], bool $isBackend = false, bool $printNotAllowedAddon = false)
public function __construct(string $moduleName = self::DEFAULT, ?ICanHandleRequests $module = null, bool $isBackend = false, bool $printNotAllowedAddon = false)
{
$this->moduleName = $moduleName;
$this->module = $module;
$this->module_class = $moduleClass;
$this->module_parameters = $moduleParameters;
$this->isBackend = $isBackend;
$this->printNotAllowedAddon = $printNotAllowedAddon;
}
@ -146,9 +133,9 @@ class Module
*
* @param Arguments $args The Friendica arguments
*
* @return Module The module with the determined module
* @return ModuleController The module with the determined module
*/
public function determineModule(Arguments $args)
public function determineName(Arguments $args)
{
if ($args->getArgc() > 0) {
$module = str_replace('.', '_', $args->get(0));
@ -162,27 +149,28 @@ class Module
$module = "login";
}
$isBackend = in_array($module, Module::BACKEND_MODULES);;
$isBackend = in_array($module, ModuleController::BACKEND_MODULES);
return new Module($module, $this->module_class, [], $isBackend, $this->printNotAllowedAddon);
return new ModuleController($module, null, $isBackend, $this->printNotAllowedAddon);
}
/**
* Determine the class of the current module
*
* @param Arguments $args The Friendica execution arguments
* @param Router $router The Friendica routing instance
* @param Arguments $args The Friendica execution arguments
* @param Router $router The Friendica routing instance
* @param IManageConfigValues $config The Friendica Configuration
* @param Dice $dice The Dependency Injection container
*
* @return Module The determined module of this call
* @return ModuleController The determined module of this call
*
* @throws \Exception
*/
public function determineClass(Arguments $args, Router $router, IManageConfigValues $config)
public function determineClass(Arguments $args, Router $router, IManageConfigValues $config, Dice $dice)
{
$printNotAllowedAddon = false;
$module_class = null;
$module_class = null;
$module_parameters = [];
/**
* ROUTING
@ -191,22 +179,22 @@ class Module
* post() and/or content() static methods can be respectively called to produce a data change or an output.
**/
try {
$module_class = $router->getModuleClass($args->getCommand());
$module_parameters = $router->getModuleParameters();
$module_class = $router->getModuleClass($args->getCommand());
$module_parameters[] = $router->getModuleParameters();
} catch (MethodNotAllowedException $e) {
$module_class = MethodNotAllowed::class;
} catch (NotFoundException $e) {
// Then we try addon-provided modules that we wrap in the LegacyModule class
if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
if (Core\Addon::isEnabled($this->moduleName) && file_exists("addon/{$this->moduleName}/{$this->moduleName}.php")) {
//Check if module is an app and if public access to apps is allowed or not
$privateapps = $config->get('config', 'private_addons', false);
if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
if ((!local_user()) && Core\Hook::isAddonApp($this->moduleName) && $privateapps) {
$printNotAllowedAddon = true;
} else {
include_once "addon/{$this->module}/{$this->module}.php";
if (function_exists($this->module . '_module')) {
LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
$module_class = LegacyModule::class;
include_once "addon/{$this->moduleName}/{$this->moduleName}.php";
if (function_exists($this->moduleName . '_module')) {
$module_parameters[] = "addon/{$this->moduleName}/{$this->moduleName}.php";
$module_class = LegacyModule::class;
}
}
}
@ -214,15 +202,18 @@ class Module
/* Finally, we look for a 'standard' program module in the 'mod' directory
* We emulate a Module class through the LegacyModule class
*/
if (!$module_class && file_exists("mod/{$this->module}.php")) {
LegacyModule::setModuleFile("mod/{$this->module}.php");
$module_class = LegacyModule::class;
if (!$module_class && file_exists("mod/{$this->moduleName}.php")) {
$module_parameters[] = "mod/{$this->moduleName}.php";
$module_class = LegacyModule::class;
}
$module_class = $module_class ?: PageNotFound::class;
}
return new Module($this->module, $module_class, $module_parameters, $this->isBackend, $printNotAllowedAddon);
/** @var ICanHandleRequests $module */
$module = $dice->create($module_class, $module_parameters);
return new ModuleController($this->moduleName, $module, $this->isBackend, $printNotAllowedAddon);
}
/**
@ -251,7 +242,7 @@ class Module
*
* Otherwise we are going to emit a 404 not found.
*/
if ($this->module_class === PageNotFound::class) {
if ($this->module === PageNotFound::class) {
$queryString = $server['QUERY_STRING'];
// Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
if (!empty($queryString) && preg_match('/{[0-9]}/', $queryString) !== 0) {
@ -302,34 +293,29 @@ class Module
$profiler->set(microtime(true), 'ready');
$timestamp = microtime(true);
Core\Hook::callAll($this->module . '_mod_init', $placeholder);
call_user_func([$this->module_class, 'init'], $this->module_parameters);
Core\Hook::callAll($this->moduleName . '_mod_init', $placeholder);
$profiler->set(microtime(true) - $timestamp, 'init');
if ($server['REQUEST_METHOD'] === Router::DELETE) {
call_user_func([$this->module_class, 'delete'], $this->module_parameters);
$this->module->delete();
}
if ($server['REQUEST_METHOD'] === Router::PATCH) {
call_user_func([$this->module_class, 'patch'], $this->module_parameters);
$this->module->patch();
}
if ($server['REQUEST_METHOD'] === Router::POST) {
Core\Hook::callAll($this->module . '_mod_post', $post);
call_user_func([$this->module_class, 'post'], $this->module_parameters);
Core\Hook::callAll($this->moduleName . '_mod_post', $post);
$this->module->post();
}
if ($server['REQUEST_METHOD'] === Router::PUT) {
call_user_func([$this->module_class, 'put'], $this->module_parameters);
$this->module->put();
}
Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
call_user_func([$this->module_class, 'afterpost'], $this->module_parameters);
// "rawContent" is especially meant for technical endpoints.
// This endpoint doesn't need any theme initialization or other comparable stuff.
call_user_func([$this->module_class, 'rawContent'], $this->module_parameters);
$this->module->rawContent();
}
}

View file

@ -191,14 +191,14 @@ class Page implements ArrayAccess
* - head.tpl template
*
* @param App $app The Friendica App instance
* @param Module $module The loaded Friendica module
* @param ModuleController $module The loaded Friendica module
* @param L10n $l10n The l10n language instance
* @param IManageConfigValues $config The Friendica configuration
* @param IManagePersonalConfigValues $pConfig The Friendica personal configuration (for user)
*
* @throws HTTPException\InternalServerErrorException
*/
private function initHead(App $app, Module $module, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig)
private function initHead(App $app, ModuleController $module, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig)
{
$interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
@ -337,26 +337,24 @@ class Page implements ArrayAccess
* - module content
* - hooks for content
*
* @param Module $module The module
* @param Mode $mode The Friendica execution mode
* @param ModuleController $module The module
* @param Mode $mode The Friendica execution mode
*
* @throws HTTPException\InternalServerErrorException
*/
private function initContent(Module $module, Mode $mode)
private function initContent(ModuleController $module, Mode $mode)
{
$content = '';
try {
$moduleClass = $module->getClassName();
$moduleClass = $module->getModule();
$arr = ['content' => $content];
Hook::callAll($moduleClass . '_mod_content', $arr);
Hook::callAll($moduleClass->getClassName() . '_mod_content', $arr);
$content = $arr['content'];
$arr = ['content' => call_user_func([$moduleClass, 'content'], $module->getParameters())];
Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
$content .= $arr['content'];
$content .= $module->getModule()->content();
} catch (HTTPException $e) {
$content = ModuleHTTPException::content($e);
$content = (new ModuleHTTPException())->content($e);
}
// initialise content region
@ -392,14 +390,14 @@ class Page implements ArrayAccess
* @param App $app The Friendica App
* @param BaseURL $baseURL The Friendica Base URL
* @param Mode $mode The current node mode
* @param Module $module The loaded Friendica module
* @param ModuleController $module The loaded Friendica module
* @param L10n $l10n The l10n language class
* @param IManageConfigValues $config The Configuration of this node
* @param IManagePersonalConfigValues $pconfig The personal/user configuration
*
* @throws HTTPException\InternalServerErrorException
*/
public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, Profiler $profiler, IManageConfigValues $config, IManagePersonalConfigValues $pconfig)
public function run(App $app, BaseURL $baseURL, Mode $mode, ModuleController $module, L10n $l10n, Profiler $profiler, IManageConfigValues $config, IManagePersonalConfigValues $pconfig)
{
$moduleName = $module->getName();

View file

@ -21,6 +21,8 @@
namespace Friendica;
use Friendica\Capabilities\ICanHandleRequests;
use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Model\User;
@ -33,94 +35,90 @@ use Friendica\Model\User;
*
* @author Hypolite Petovan <hypolite@mrpetovan.com>
*/
abstract class BaseModule
abstract class BaseModule implements ICanHandleRequests
{
/**
* Initialization method common to both content() and post()
*
* Extend this method if you need to do any shared processing before both
* content() or post()
*/
public static function init(array $parameters = [])
/** @var array */
protected $parameters = [];
/** @var L10n */
protected $l10n;
public function __construct(L10n $l10n, array $parameters = [])
{
$this->parameters = $parameters;
$this->l10n = $l10n;
}
/**
* Module GET method to display raw content from technical endpoints
* Wraps the L10n::t() function for Modules
*
* Extend this method if the module is supposed to return communication data,
* e.g. from protocol implementations.
* @see L10n::t()
*/
public static function rawContent(array $parameters = [])
protected function t(string $s, ...$args): string
{
return $this->l10n->t($s, $args);
}
/**
* Wraps the L10n::tt() function for Modules
*
* @see L10n::tt()
*/
protected function tt(string $singular, string $plurarl, int $count): string
{
return $this->l10n->tt($singular, $plurarl, $count);
}
/**
* {@inheritDoc}
*/
public function rawContent()
{
// echo '';
// exit;
}
/**
* Module GET method to display any content
*
* Extend this method if the module is supposed to return any display
* through a GET request. It can be an HTML page through templating or a
* XML feed or a JSON output.
*
* @return string
* {@inheritDoc}
*/
public static function content(array $parameters = [])
public function content(): string
{
$o = '';
return $o;
return '';
}
/**
* Module DELETE method to process submitted data
*
* Extend this method if the module is supposed to process DELETE requests.
* Doesn't display any content
* {@inheritDoc}
*/
public static function delete(array $parameters = [])
public function delete()
{
}
/**
* Module PATCH method to process submitted data
*
* Extend this method if the module is supposed to process PATCH requests.
* Doesn't display any content
* {@inheritDoc}
*/
public static function patch(array $parameters = [])
public function patch()
{
}
/**
* Module POST method to process submitted data
*
* Extend this method if the module is supposed to process POST requests.
* Doesn't display any content
* {@inheritDoc}
*/
public static function post(array $parameters = [])
public function post()
{
// DI::baseurl()->redirect('module');
}
/**
* Called after post()
*
* Unknown purpose
* {@inheritDoc}
*/
public static function afterpost(array $parameters = [])
public function put()
{
}
/**
* Module PUT method to process submitted data
*
* Extend this method if the module is supposed to process PUT requests.
* Doesn't display any content
*/
public static function put(array $parameters = [])
/** Gets the name of the current class */
public function getClassName(): string
{
return static::class;
}
/*

View file

@ -0,0 +1,60 @@
<?php
namespace Friendica\Capabilities;
/**
* This interface provides the capability to handle requests from clients and returns the desired outcome
*/
interface ICanHandleRequests
{
/**
* Module GET method to display raw content from technical endpoints
*
* Extend this method if the module is supposed to return communication data,
* e.g. from protocol implementations.
*/
public function rawContent();
/**
* Module GET method to display any content
*
* Extend this method if the module is supposed to return any display
* through a GET request. It can be an HTML page through templating or a
* XML feed or a JSON output.
*/
public function content(): string;
/**
* Module DELETE method to process submitted data
*
* Extend this method if the module is supposed to process DELETE requests.
* Doesn't display any content
*/
public function delete();
/**
* Module PATCH method to process submitted data
*
* Extend this method if the module is supposed to process PATCH requests.
* Doesn't display any content
*/
public function patch();
/**
* Module POST method to process submitted data
*
* Extend this method if the module is supposed to process POST requests.
* Doesn't display any content
*/
public function post();
/**
* Module PUT method to process submitted data
*
* Extend this method if the module is supposed to process PUT requests.
* Doesn't display any content
*/
public function put();
public function getClassName(): string;
}

View file

@ -99,11 +99,11 @@ abstract class DI
}
/**
* @return App\Module
* @return App\ModuleController
*/
public static function module()
{
return self::$dice->create(App\Module::class);
return self::$dice->create(App\ModuleController::class);
}
/**

View file

@ -52,4 +52,9 @@ class User extends BaseFactory
return new \Friendica\Object\Api\Twitter\User($publicContact, $apcontact, $userContact, $skip_status, $include_user_entities);
}
public function createFromUserId(int $uid, $skip_status = false, $include_user_entities = true)
{
return $this->createFromContactId(Contact::getPublicIdByUserId($uid), $uid, $skip_status, $include_user_entities);
}
}

View file

@ -21,6 +21,8 @@
namespace Friendica;
use Friendica\Core\L10n;
/**
* This mock module enable class encapsulation of legacy global function modules.
* After having provided the module file name, all the methods will behave like a normal Module class.
@ -35,7 +37,16 @@ class LegacyModule extends BaseModule
*
* @var string
*/
private static $moduleName = '';
private $moduleName = '';
public function __construct(L10n $l10n, string $file_path = '', array $parameters = [])
{
parent::__construct($l10n, $parameters);
$this->setModuleFile($file_path);
$this->runModuleFunction('init');
}
/**
* The only method that needs to be called, with the module/addon file name.
@ -43,35 +54,25 @@ class LegacyModule extends BaseModule
* @param string $file_path
* @throws \Exception
*/
public static function setModuleFile($file_path)
private function setModuleFile($file_path)
{
if (!is_readable($file_path)) {
throw new \Exception(DI::l10n()->t('Legacy module file not found: %s', $file_path));
}
self::$moduleName = basename($file_path, '.php');
$this->moduleName = basename($file_path, '.php');
require_once $file_path;
}
public static function init(array $parameters = [])
public function content(): string
{
self::runModuleFunction('init', $parameters);
return $this->runModuleFunction('content');
}
public static function content(array $parameters = [])
public function post()
{
return self::runModuleFunction('content', $parameters);
}
public static function post(array $parameters = [])
{
self::runModuleFunction('post', $parameters);
}
public static function afterpost(array $parameters = [])
{
self::runModuleFunction('afterpost', $parameters);
$this->runModuleFunction('post');
}
/**
@ -81,15 +82,15 @@ class LegacyModule extends BaseModule
* @return string
* @throws \Exception
*/
private static function runModuleFunction($function_suffix, array $parameters = [])
private function runModuleFunction(string $function_suffix)
{
$function_name = static::$moduleName . '_' . $function_suffix;
$function_name = $this->moduleName . '_' . $function_suffix;
if (\function_exists($function_name)) {
$a = DI::app();
return $function_name($a);
} else {
return parent::{$function_suffix}($parameters);
}
return '';
}
}

View file

@ -30,7 +30,7 @@ use Friendica\BaseModule;
*/
class AccountManagementControlDocument extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$output = [
'version' => 1,

View file

@ -24,22 +24,25 @@ namespace Friendica\Module;
use Friendica\BaseModule;
use Friendica\Core\System;
use Friendica\Model\Contact;
use Friendica\Network\HTTPException\NotFoundException;
/**
* Redirects to another URL based on the parameter 'addr'
*/
class Acctlink extends BaseModule
{
public static function content(array $parameters = [])
public function rawContent()
{
$addr = trim($_GET['addr'] ?? '');
if ($addr) {
$url = Contact::getByURL($addr)['url'] ?? '';
if ($url) {
System::externalRedirect($url['url']);
exit();
}
if (!$addr) {
throw new NotFoundException('Parameter "addr" is missing or empty');
}
$contact = Contact::getByURL($addr, null, ['url']) ?? '';
if (!$contact) {
throw new NotFoundException('Contact not found');
}
System::externalRedirect($contact['url']);
}
}

View file

@ -31,14 +31,14 @@ use Friendica\Protocol\ActivityPub;
*/
class Followers extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (empty($parameters['nickname'])) {
if (empty($this->parameters['nickname'])) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}
// @TODO: Replace with parameter from router
$owner = User::getOwnerDataByNick($parameters['nickname']);
$owner = User::getOwnerDataByNick($this->parameters['nickname']);
if (empty($owner)) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}

View file

@ -31,13 +31,13 @@ use Friendica\Protocol\ActivityPub;
*/
class Following extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (empty($parameters['nickname'])) {
if (empty($this->parameters['nickname'])) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}
$owner = User::getOwnerDataByNick($parameters['nickname']);
$owner = User::getOwnerDataByNick($this->parameters['nickname']);
if (empty($owner)) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}

View file

@ -35,7 +35,7 @@ use Friendica\Util\Network;
*/
class Inbox extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$postdata = Network::postdata();
@ -50,12 +50,12 @@ class Inbox extends BaseModule
$filename = 'failed-activitypub';
}
$tempfile = tempnam(System::getTempPath(), $filename);
file_put_contents($tempfile, json_encode(['parameters' => $parameters, 'header' => $_SERVER, 'body' => $postdata], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
file_put_contents($tempfile, json_encode(['parameters' => $this->parameters, 'header' => $_SERVER, 'body' => $postdata], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
Logger::notice('Incoming message stored', ['file' => $tempfile]);
}
if (!empty($parameters['nickname'])) {
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $parameters['nickname']]);
if (!empty($this->parameters['nickname'])) {
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $this->parameters['nickname']]);
if (!DBA::isResult($user)) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}

View file

@ -41,9 +41,9 @@ use Friendica\Util\Strings;
*/
class Objects extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (empty($parameters['guid'])) {
if (empty($this->parameters['guid'])) {
throw new HTTPException\BadRequestException();
}
@ -51,10 +51,10 @@ class Objects extends BaseModule
DI::baseUrl()->redirect(str_replace('objects/', 'display/', DI::args()->getQueryString()));
}
$itemuri = DBA::selectFirst('item-uri', ['id'], ['guid' => $parameters['guid']]);
$itemuri = DBA::selectFirst('item-uri', ['id'], ['guid' => $this->parameters['guid']]);
if (DBA::isResult($itemuri)) {
Logger::info('Provided GUID found.', ['guid' => $parameters['guid'], 'uri-id' => $itemuri['id']]);
Logger::info('Provided GUID found.', ['guid' => $this->parameters['guid'], 'uri-id' => $itemuri['id']]);
} else {
// The item URI does not always contain the GUID. This means that we have to search the URL instead
$url = DI::baseUrl()->get() . '/' . DI::args()->getQueryString();
@ -104,11 +104,11 @@ class Objects extends BaseModule
throw new HTTPException\NotFoundException();
}
$etag = md5($parameters['guid'] . '-' . $item['changed']);
$etag = md5($this->parameters['guid'] . '-' . $item['changed']);
$last_modified = $item['changed'];
Network::checkEtagModified($etag, $last_modified);
if (empty($parameters['activity']) && ($item['gravity'] != GRAVITY_ACTIVITY)) {
if (empty($this->parameters['activity']) && ($item['gravity'] != GRAVITY_ACTIVITY)) {
$activity = ActivityPub\Transmitter::createActivityFromItem($item['id'], true);
if (empty($activity['type'])) {
throw new HTTPException\NotFoundException();
@ -123,16 +123,16 @@ class Objects extends BaseModule
$data = ['@context' => ActivityPub::CONTEXT];
$data = array_merge($data, $activity['object']);
} elseif (empty($parameters['activity']) || in_array($parameters['activity'],
} elseif (empty($this->parameters['activity']) || in_array($this->parameters['activity'],
['Create', 'Announce', 'Update', 'Like', 'Dislike', 'Accept', 'Reject',
'TentativeAccept', 'Follow', 'Add'])) {
$data = ActivityPub\Transmitter::createActivityFromItem($item['id']);
if (empty($data)) {
throw new HTTPException\NotFoundException();
}
if (!empty($parameters['activity']) && ($parameters['activity'] != 'Create')) {
$data['type'] = $parameters['activity'];
$data['id'] = str_replace('/Create', '/' . $parameters['activity'], $data['id']);
if (!empty($this->parameters['activity']) && ($this->parameters['activity'] != 'Create')) {
$data['type'] = $this->parameters['activity'];
$data['id'] = str_replace('/Create', '/' . $this->parameters['activity'], $data['id']);
}
} else {
throw new HTTPException\NotFoundException();

View file

@ -31,13 +31,13 @@ use Friendica\Util\HTTPSignature;
*/
class Outbox extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (empty($parameters['nickname'])) {
if (empty($this->parameters['nickname'])) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}
$owner = User::getOwnerDataByNick($parameters['nickname']);
$owner = User::getOwnerDataByNick($this->parameters['nickname']);
if (empty($owner)) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}

View file

@ -30,11 +30,11 @@ use Friendica\Util\Strings;
class Details extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
$addon = Strings::sanitizeFilePathItem($parameters['addon']);
$addon = Strings::sanitizeFilePathItem($this->parameters['addon']);
$redirect = 'admin/addons/' . $addon;
@ -52,15 +52,15 @@ class Details extends BaseAdmin
DI::baseUrl()->redirect($redirect);
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$a = DI::app();
$addons_admin = Addon::getAdminList();
$addon = Strings::sanitizeFilePathItem($parameters['addon']);
$addon = Strings::sanitizeFilePathItem($this->parameters['addon']);
if (!is_file("addon/$addon/$addon.php")) {
notice(DI::l10n()->t('Addon not found.'));
Addon::uninstall($addon);

View file

@ -28,9 +28,9 @@ use Friendica\Module\BaseAdmin;
class Index extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
// reload active themes
if (!empty($_GET['action'])) {

View file

@ -32,7 +32,7 @@ use Friendica\Util\Network;
class Contact extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -76,9 +76,9 @@ class Contact extends BaseAdmin
DI::baseUrl()->redirect('admin/blocklist/contact');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$condition = ['uid' => 0, 'blocked' => true];

View file

@ -32,7 +32,7 @@ use GuzzleHttp\Psr7\Uri;
class Add extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -66,9 +66,9 @@ class Add extends BaseAdmin
DI::baseUrl()->redirect('admin/blocklist/server');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$gservers = [];

View file

@ -27,7 +27,7 @@ use Friendica\Module\BaseAdmin;
class Index extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -56,9 +56,9 @@ class Index extends BaseAdmin
DI::baseUrl()->redirect('admin/blocklist/server');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$blocklist = DI::config()->get('system', 'blocklist');
$blocklistform = [];

View file

@ -30,14 +30,14 @@ use Friendica\Module\BaseAdmin;
class DBSync extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$a = DI::app();
$action = $parameters['action'] ?? '';
$update = $parameters['update'] ?? 0;
$action = $this->parameters['action'] ?? '';
$update = $this->parameters['update'] ?? 0;
switch ($action) {
case 'mark':

View file

@ -28,7 +28,7 @@ use Friendica\Module\BaseAdmin;
class Features extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -60,9 +60,9 @@ class Features extends BaseAdmin
DI::baseUrl()->redirect('admin/features');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$features = [];

View file

@ -28,9 +28,9 @@ use Friendica\Module\BaseAdmin;
class Federation extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
// get counts on active federation systems this node is knowing
// We list the more common systems by name. The rest is counted as "other"

View file

@ -29,7 +29,7 @@ use Friendica\Util\Strings;
class Delete extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -55,9 +55,9 @@ class Delete extends BaseAdmin
DI::baseUrl()->redirect('admin/item/delete');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$t = Renderer::getMarkupTemplate('admin/item/delete.tpl');

View file

@ -29,11 +29,11 @@ use Friendica\Module\BaseAdmin;
class Source extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$guid = basename($_REQUEST['guid'] ?? $parameters['guid'] ?? '');
$guid = basename($_REQUEST['guid'] ?? $this->parameters['guid'] ?? '');
$source = '';
$item_uri = '';

View file

@ -29,7 +29,7 @@ use Psr\Log\LogLevel;
class Settings extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -56,9 +56,9 @@ class Settings extends BaseAdmin
DI::baseUrl()->redirect('admin/logs');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$log_choices = [
LogLevel::ERROR => 'Error',

View file

@ -31,9 +31,9 @@ class View extends BaseAdmin
{
const LIMIT = 500;
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$t = Renderer::getMarkupTemplate('admin/logs/view.tpl');
DI::page()->registerFooterScript(Theme::getPathForFile('js/module/admin/logs/view.js'));
@ -75,7 +75,7 @@ class View extends BaseAdmin
->withLimit(self::LIMIT)
->withFilters($filters)
->withSearch($search);
} catch (Exception $e) {
} catch (\Exception $e) {
$error = DI::l10n()->t('Couldn\'t open <strong>%1$s</strong> log file.<br/>Check to see if file %1$s is readable.', $f);
}
}

View file

@ -25,7 +25,7 @@ use Friendica\Module\BaseAdmin;
class PhpInfo extends BaseAdmin
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAdminAccess();

View file

@ -38,11 +38,11 @@ use Friendica\Util\DateTimeFormat;
*/
class Queue extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$status = $parameters['status'] ?? '';
$status = $this->parameters['status'] ?? '';
// get jobs from the workerqueue table
if ($status == 'deferred') {

View file

@ -43,7 +43,7 @@ require_once __DIR__ . '/../../../boot.php';
class Site extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -384,9 +384,9 @@ class Site extends BaseAdmin
DI::baseUrl()->redirect('admin/site' . $active_panel);
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
/* Installed langs */
$lang_choices = DI::l10n()->getAvailableLanguages();

View file

@ -31,13 +31,13 @@ use Friendica\Util\Strings;
class Storage extends BaseAdmin
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
self::checkFormSecurityTokenRedirectOnError('/admin/storage', 'admin_storage');
$storagebackend = trim($parameters['name'] ?? '');
$storagebackend = trim($this->parameters['name'] ?? '');
try {
/** @var ICanConfigureStorage|false $newStorageConfig */
@ -91,9 +91,9 @@ class Storage extends BaseAdmin
DI::baseUrl()->redirect('admin/storage');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$current_storage_backend = DI::storage();
$available_storage_forms = [];

View file

@ -37,9 +37,9 @@ use Friendica\Util\DateTimeFormat;
class Summary extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$a = DI::app();

View file

@ -30,11 +30,11 @@ use Friendica\Util\Strings;
class Details extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$theme = Strings::sanitizeFilePathItem($parameters['theme']);
$theme = Strings::sanitizeFilePathItem($this->parameters['theme']);
if (!is_dir("view/theme/$theme")) {
notice(DI::l10n()->t("Item not found."));
return '';

View file

@ -21,48 +21,62 @@
namespace Friendica\Module\Admin\Themes;
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\DI;
use Friendica\Module\BaseAdmin;
use Friendica\Util\Strings;
class Embed extends BaseAdmin
{
public static function init(array $parameters = [])
/** @var App */
protected $app;
/** @var App\BaseURL */
protected $baseUrl;
/** @var App\Mode */
protected $mode;
public function __construct(App $app, App\BaseURL $baseUrl, App\Mode $mode, L10n $l10n, array $parameters = [])
{
$theme = Strings::sanitizeFilePathItem($parameters['theme']);
parent::__construct($l10n, $parameters);
$this->app = $app;
$this->baseUrl = $baseUrl;
$this->mode = $mode;
$theme = Strings::sanitizeFilePathItem($this->parameters['theme']);
if (is_file("view/theme/$theme/config.php")) {
DI::app()->setCurrentTheme($theme);
$this->app->setCurrentTheme($theme);
}
}
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
$theme = Strings::sanitizeFilePathItem($parameters['theme']);
$theme = Strings::sanitizeFilePathItem($this->parameters['theme']);
if (is_file("view/theme/$theme/config.php")) {
require_once "view/theme/$theme/config.php";
if (function_exists('theme_admin_post')) {
self::checkFormSecurityTokenRedirectOnError('/admin/themes/' . $theme . '/embed?mode=minimal', 'admin_theme_settings');
theme_admin_post(DI::app());
theme_admin_post($this->app);
}
}
if (DI::mode()->isAjax()) {
if ($this->mode->isAjax()) {
return;
}
DI::baseUrl()->redirect('admin/themes/' . $theme . '/embed?mode=minimal');
$this->baseUrl->redirect('admin/themes/' . $theme . '/embed?mode=minimal');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$theme = Strings::sanitizeFilePathItem($parameters['theme']);
$theme = Strings::sanitizeFilePathItem($this->parameters['theme']);
if (!is_dir("view/theme/$theme")) {
notice(DI::l10n()->t('Unknown theme.'));
notice($this->t('Unknown theme.'));
return '';
}
@ -71,7 +85,7 @@ class Embed extends BaseAdmin
require_once "view/theme/$theme/config.php";
if (function_exists('theme_admin')) {
$admin_form = theme_admin(DI::app());
$admin_form = theme_admin($this->app);
}
}

View file

@ -29,9 +29,9 @@ use Friendica\Util\Strings;
class Index extends BaseAdmin
{
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$allowed_themes = Theme::getAllowedList();

View file

@ -21,13 +21,31 @@
namespace Friendica\Module\Admin;
use Friendica\App\BaseURL;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\DI;
use Friendica\Module\BaseAdmin;
class Tos extends BaseAdmin
{
public static function post(array $parameters = [])
/** @var \Friendica\Module\Tos */
protected $tos;
/** @var IManageConfigValues */
protected $config;
/** @var BaseURL */
protected $baseUrl;
public function __construct(\Friendica\Module\Tos $tos, IManageConfigValues $config, BaseURL $baseUrl, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
$this->tos = $tos;
$this->config = $config;
$this->baseUrl = $baseUrl;
}
public function post()
{
self::checkAdminAccess();
@ -41,29 +59,28 @@ class Tos extends BaseAdmin
$displayprivstatement = !empty($_POST['displayprivstatement']);
$tostext = (!empty($_POST['tostext']) ? strip_tags(trim($_POST['tostext'])) : '');
DI::config()->set('system', 'tosdisplay', $displaytos);
DI::config()->set('system', 'tosprivstatement', $displayprivstatement);
DI::config()->set('system', 'tostext', $tostext);
$this->config->set('system', 'tosdisplay', $displaytos);
$this->config->set('system', 'tosprivstatement', $displayprivstatement);
$this->config->set('system', 'tostext', $tostext);
DI::baseUrl()->redirect('admin/tos');
$this->baseUrl->redirect('admin/tos');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$tos = new \Friendica\Module\Tos();
$t = Renderer::getMarkupTemplate('admin/tos.tpl');
return Renderer::replaceMacros($t, [
'$title' => DI::l10n()->t('Administration'),
'$page' => DI::l10n()->t('Terms of Service'),
'$displaytos' => ['displaytos', DI::l10n()->t('Display Terms of Service'), DI::config()->get('system', 'tosdisplay'), DI::l10n()->t('Enable the Terms of Service page. If this is enabled a link to the terms will be added to the registration form and the general information page.')],
'$displayprivstatement' => ['displayprivstatement', DI::l10n()->t('Display Privacy Statement'), DI::config()->get('system', 'tosprivstatement'), DI::l10n()->t('Show some informations regarding the needed information to operate the node according e.g. to <a href="%s" target="_blank" rel="noopener noreferrer">EU-GDPR</a>.', 'https://en.wikipedia.org/wiki/General_Data_Protection_Regulation')],
'$preview' => DI::l10n()->t('Privacy Statement Preview'),
'$privtext' => $tos->privacy_complete,
'$tostext' => ['tostext', DI::l10n()->t('The Terms of Service'), DI::config()->get('system', 'tostext'), DI::l10n()->t('Enter the Terms of Service for your node here. You can use BBCode. Headers of sections should be [h2] and below.')],
'$title' => $this->t('Administration'),
'$page' => $this->t('Terms of Service'),
'$displaytos' => ['displaytos', $this->t('Display Terms of Service'), $this->config->get('system', 'tosdisplay'), $this->t('Enable the Terms of Service page. If this is enabled a link to the terms will be added to the registration form and the general information page.')],
'$displayprivstatement' => ['displayprivstatement', $this->t('Display Privacy Statement'), $this->config->get('system', 'tosprivstatement'), $this->t('Show some informations regarding the needed information to operate the node according e.g. to <a href="%s" target="_blank" rel="noopener noreferrer">EU-GDPR</a>.', 'https://en.wikipedia.org/wiki/General_Data_Protection_Regulation')],
'$preview' => $this->t('Privacy Statement Preview'),
'$privtext' => $this->tos->privacy_complete,
'$tostext' => ['tostext', $this->t('The Terms of Service'), $this->config->get('system', 'tostext'), $this->t('Enter the Terms of Service for your node here. You can use BBCode. Headers of sections should be [h2] and below.')],
'$form_security_token' => self::getFormSecurityToken('admin_tos'),
'$submit' => DI::l10n()->t('Save Settings'),
'$submit' => $this->t('Save Settings'),
]);
}
}

View file

@ -30,7 +30,7 @@ use Friendica\Module\Admin\BaseUsers;
class Active extends BaseUsers
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -60,12 +60,12 @@ class Active extends BaseUsers
DI::baseUrl()->redirect(DI::args()->getQueryString());
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$action = $parameters['action'] ?? '';
$uid = $parameters['uid'] ?? 0;
$action = $this->parameters['action'] ?? '';
$uid = $this->parameters['uid'] ?? 0;
if ($uid) {
$user = User::getById($uid, ['username', 'blocked']);

View file

@ -31,7 +31,7 @@ use Friendica\Util\Temporal;
class Blocked extends BaseUsers
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -61,12 +61,12 @@ class Blocked extends BaseUsers
DI::baseUrl()->redirect('admin/users/blocked');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$action = $parameters['action'] ?? '';
$uid = $parameters['uid'] ?? 0;
$action = $this->parameters['action'] ?? '';
$uid = $this->parameters['uid'] ?? 0;
if ($uid) {
$user = User::getById($uid, ['username', 'blocked']);

View file

@ -28,7 +28,7 @@ use Friendica\Module\Admin\BaseUsers;
class Create extends BaseUsers
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -51,9 +51,9 @@ class Create extends BaseUsers
DI::baseUrl()->redirect('admin/users/create');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$t = Renderer::getMarkupTemplate('admin/users/create.tpl');
return self::getTabsHTML('all') . Renderer::replaceMacros($t, [

View file

@ -33,7 +33,7 @@ use Friendica\Util\Temporal;
class Deleted extends BaseUsers
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -44,9 +44,9 @@ class Deleted extends BaseUsers
DI::baseUrl()->redirect('admin/users/deleted');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 100);

View file

@ -30,7 +30,7 @@ use Friendica\Module\Admin\BaseUsers;
class Index extends BaseUsers
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -67,12 +67,12 @@ class Index extends BaseUsers
DI::baseUrl()->redirect(DI::args()->getQueryString());
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$action = $parameters['action'] ?? '';
$uid = $parameters['uid'] ?? 0;
$action = $this->parameters['action'] ?? '';
$uid = $this->parameters['uid'] ?? 0;
if ($uid) {
$user = User::getById($uid, ['username', 'blocked']);

View file

@ -33,7 +33,7 @@ use Friendica\Util\Temporal;
class Pending extends BaseUsers
{
public static function post(array $parameters = [])
public function post()
{
self::checkAdminAccess();
@ -58,12 +58,12 @@ class Pending extends BaseUsers
DI::baseUrl()->redirect('admin/users/pending');
}
public static function content(array $parameters = [])
public function content(): string
{
parent::content($parameters);
parent::content();
$action = $parameters['action'] ?? '';
$uid = $parameters['uid'] ?? 0;
$action = $this->parameters['action'] ?? '';
$uid = $this->parameters['uid'] ?? 0;
if ($uid) {
$user = User::getById($uid, ['username', 'blocked']);

View file

@ -40,7 +40,7 @@ use Friendica\Module\BaseApi;
*/
class Activity extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -49,17 +49,17 @@ class Activity extends BaseApi
'id' => 0, // Id of the post
]);
$res = Item::performActivity($request['id'], $parameters['verb'], $uid);
$res = Item::performActivity($request['id'], $this->parameters['verb'], $uid);
if ($res) {
if (!empty($parameters['extension']) && ($parameters['extension'] == 'xml')) {
if (!empty($this->parameters['extension']) && ($this->parameters['extension'] == 'xml')) {
$ok = 'true';
} else {
$ok = 'ok';
}
DI::apiResponse()->exit('ok', ['ok' => $ok], $parameters['extension'] ?? null);
DI::apiResponse()->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
} else {
DI::apiResponse()->error(500, 'Error adding activity', '', $parameters['extension'] ?? null);
DI::apiResponse()->error(500, 'Error adding activity', '', $this->parameters['extension'] ?? null);
}
}
}

View file

@ -30,7 +30,7 @@ use Friendica\Module\BaseApi;
*/
class Setseen extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -42,13 +42,13 @@ class Setseen extends BaseApi
// return error if id is zero
if (empty($request['id'])) {
$answer = ['result' => 'error', 'message' => 'message id not specified'];
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $parameters['extension'] ?? null);
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null);
}
// error message if specified id is not in database
if (!DBA::exists('mail', ['id' => $request['id'], 'uid' => $uid])) {
$answer = ['result' => 'error', 'message' => 'message id not in database'];
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $parameters['extension'] ?? null);
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null);
}
// update seen indicator
@ -58,6 +58,6 @@ class Setseen extends BaseApi
$answer = ['result' => 'error', 'message' => 'unknown error'];
}
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $parameters['extension'] ?? null);
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null);
}
}

View file

@ -33,7 +33,7 @@ use Friendica\Module\BaseApi;
*/
class Index extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
@ -70,6 +70,6 @@ class Index extends BaseApi
];
}
DI::apiResponse()->exit('events', ['events' => $items], $parameters['extension'] ?? null);
DI::apiResponse()->exit('events', ['events' => $items], $this->parameters['extension'] ?? null);
}
}

View file

@ -22,6 +22,7 @@
namespace Friendica\Module\Api\Friendica\Group;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\Group;
use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException\BadRequestException;
@ -31,7 +32,7 @@ use Friendica\Network\HTTPException\BadRequestException;
*/
class Delete extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -69,7 +70,7 @@ class Delete extends BaseApi
if ($ret) {
// return success
$success = ['success' => $ret, 'gid' => $request['gid'], 'name' => $request['name'], 'status' => 'deleted', 'wrong users' => []];
self::exit('group_delete', ['$result' => $success], $parameters['extension'] ?? null);
DI::apiResponse()->exit('group_delete', ['$result' => $success], $parameters['extension'] ?? null);
} else {
throw new BadRequestException('other API error');
}

View file

@ -31,17 +31,17 @@ use Friendica\Module\BaseApi;
*/
class Index extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
}
public static function delete(array $parameters = [])
public function delete()
{
self::checkAllowedScope(self::SCOPE_WRITE);
}
public static function rawContent(array $parameters = [])
public function rawContent()
{
echo api_call(DI::app());
exit();

View file

@ -31,7 +31,7 @@ use Friendica\Object\Api\Friendica\Notification as ApiNotification;
*/
class Notification extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
@ -43,7 +43,7 @@ class Notification extends BaseApi
$notifications[] = new ApiNotification($Notify);
}
if (!empty($parameters['extension']) && ($parameters['extension'] == 'xml')) {
if (!empty($this->parameters['extension']) && ($this->parameters['extension'] == 'xml')) {
$xmlnotes = [];
foreach ($notifications as $notification) {
$xmlnotes[] = ['@attributes' => $notification->toArray()];
@ -56,6 +56,6 @@ class Notification extends BaseApi
$result = false;
}
DI::apiResponse()->exit('notes', ['note' => $result], $parameters['extension'] ?? null);
DI::apiResponse()->exit('notes', ['note' => $result], $this->parameters['extension'] ?? null);
}
}

View file

@ -33,7 +33,7 @@ use Friendica\Network\HTTPException\InternalServerErrorException;
*/
class Delete extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -64,7 +64,7 @@ class Delete extends BaseApi
Item::deleteForUser($condition, $uid);
$result = ['result' => 'deleted', 'message' => 'photo with id `' . $request['photo_id'] . '` has been deleted from server.'];
DI::apiResponse()->exit('photo_delete', ['$result' => $result], $parameters['extension'] ?? null);
DI::apiResponse()->exit('photo_delete', ['$result' => $result], $this->parameters['extension'] ?? null);
} else {
throw new InternalServerErrorException("unknown error on deleting photo from database table");
}

View file

@ -34,7 +34,7 @@ use Friendica\Network\HTTPException\InternalServerErrorException;
*/
class Delete extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -67,7 +67,7 @@ class Delete extends BaseApi
// return success of deletion or error message
if ($result) {
$answer = ['result' => 'deleted', 'message' => 'album `' . $request['album'] . '` with all containing photos has been deleted.'];
DI::apiResponse()->exit('photoalbum_delete', ['$result' => $answer], $parameters['extension'] ?? null);
DI::apiResponse()->exit('photoalbum_delete', ['$result' => $answer], $this->parameters['extension'] ?? null);
} else {
throw new InternalServerErrorException("unknown error - deleting from database failed");
}

View file

@ -32,7 +32,7 @@ use Friendica\Network\HTTPException\InternalServerErrorException;
*/
class Update extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -59,7 +59,7 @@ class Update extends BaseApi
// return success of updating or error message
if ($result) {
$answer = ['result' => 'updated', 'message' => 'album `' . $request['album'] . '` with all containing photos has been renamed to `' . $request['album_new'] . '`.'];
DI::apiResponse()->exit('photoalbum_update', ['$result' => $answer], $parameters['extension'] ?? null);
DI::apiResponse()->exit('photoalbum_update', ['$result' => $answer], $this->parameters['extension'] ?? null);
} else {
throw new InternalServerErrorException("unknown error - updating in database failed");
}

View file

@ -24,7 +24,6 @@ namespace Friendica\Module\Api\Friendica\Profile;
use Friendica\Profile\ProfileField\Collection\ProfileFields;
use Friendica\Content\Text\BBCode;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Profile;
use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException;
@ -34,7 +33,7 @@ use Friendica\Network\HTTPException;
*/
class Show extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
@ -49,23 +48,20 @@ class Show extends BaseApi
$profile = self::formatProfile($profile, $profileFields);
$profiles = [];
if (!empty($parameters['extension']) && ($parameters['extension'] == 'xml')) {
if (!empty($this->parameters['extension']) && ($this->parameters['extension'] == 'xml')) {
$profiles['0:profile'] = $profile;
} else {
$profiles[] = $profile;
}
// return settings, authenticated user and profiles data
$self = Contact::selectFirst(['nurl'], ['uid' => $uid, 'self' => true]);
$result = [
'multi_profiles' => false,
'global_dir' => $directory,
'friendica_owner' => self::getUser($self['nurl']),
'friendica_owner' => DI::twitterUser()->createFromUserId($uid),
'profiles' => $profiles
];
DI::apiResponse()->exit('friendica_profiles', ['$result' => $result], $parameters['extension'] ?? null);
DI::apiResponse()->exit('friendica_profiles', ['$result' => $result], $this->parameters['extension'] ?? null);
}
/**

View file

@ -31,7 +31,7 @@ use Friendica\Module\Register;
*/
class Config extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$config = [
'site' => [
@ -61,6 +61,6 @@ class Config extends BaseApi
],
];
self::exit('config', ['config' => $config], $parameters['extension'] ?? null);
DI::apiResponse()->exit('config', ['config' => $config], $this->parameters['extension'] ?? null);
}
}

View file

@ -29,8 +29,8 @@ use Friendica\DI;
*/
class Version extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
DI::apiResponse()->exit('version', ['version' => '0.9.7'], $parameters['extension'] ?? null);
DI::apiResponse()->exit('version', ['version' => '0.9.7'], $this->parameters['extension'] ?? null);
}
}

View file

@ -29,14 +29,14 @@ use Friendica\DI;
*/
class Test extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (!empty($parameters['extension']) && ($parameters['extension'] == 'xml')) {
if (!empty($this->parameters['extension']) && ($this->parameters['extension'] == 'xml')) {
$ok = 'true';
} else {
$ok = 'ok';
}
DI::apiResponse()->exit('ok', ['ok' => $ok], $parameters['extension'] ?? null);
DI::apiResponse()->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
}
}

View file

@ -33,27 +33,26 @@ use Friendica\Module\BaseApi;
class Accounts extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();
if (empty($parameters['id']) && empty($parameters['name'])) {
if (empty($this->parameters['id']) && empty($this->parameters['name'])) {
DI::mstdnError()->UnprocessableEntity();
}
if (!empty($parameters['id'])) {
$id = $parameters['id'];
if (!empty($this->parameters['id'])) {
$id = $this->parameters['id'];
if (!DBA::exists('contact', ['id' => $id, 'uid' => 0])) {
DI::mstdnError()->RecordNotFound();
}
} else {
$contact = Contact::selectFirst(['id'], ['nick' => $parameters['name'], 'uid' => 0]);
$contact = Contact::selectFirst(['id'], ['nick' => $this->parameters['name'], 'uid' => 0]);
if (!empty($contact['id'])) {
$id = $contact['id'];
} elseif (!($id = Contact::getIdForURL($parameters['name'], 0, false))) {
} elseif (!($id = Contact::getIdForURL($this->parameters['name'], 0, false))) {
DI::mstdnError()->RecordNotFound();
}
}

View file

@ -32,12 +32,12 @@ use Friendica\Module\BaseApi;
*/
class Block extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_FOLLOW);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
@ -46,7 +46,7 @@ class Block extends BaseApi
DI::mstdnError()->Forbidden();
}
$cdata = Contact::getPublicAndUserContactID($parameters['id'], $uid);
$cdata = Contact::getPublicAndUserContactID($this->parameters['id'], $uid);
if (empty($cdata['user'])) {
DI::mstdnError()->RecordNotFound();
}
@ -62,6 +62,6 @@ class Block extends BaseApi
Contact::terminateFriendship($owner, $contact);
Contact::revokeFollow($contact);
System::jsonExit(DI::mstdnRelationship()->createFromContactId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnRelationship()->createFromContactId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -30,10 +30,9 @@ use Friendica\Module\BaseApi;
class FeaturedTags extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);

View file

@ -31,16 +31,16 @@ use Friendica\Module\BaseApi;
*/
class Follow extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_FOLLOW);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$cid = Contact::follow($parameters['id'], $uid);
$cid = Contact::follow($this->parameters['id'], $uid);
System::jsonExit(DI::mstdnRelationship()->createFromContactId($cid, $uid)->toArray());
}

View file

@ -32,19 +32,18 @@ use Friendica\Module\BaseApi;
class Followers extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!DBA::exists('contact', ['id' => $id, 'uid' => 0])) {
DI::mstdnError()->RecordNotFound();
}
@ -73,7 +72,7 @@ class Followers extends BaseApi
$params['order'] = ['cid'];
}
$followers = DBA::select('contact-relation', ['relation-cid'], $condition, $parameters);
$followers = DBA::select('contact-relation', ['relation-cid'], $condition, $this->parameters);
while ($follower = DBA::fetch($followers)) {
self::setBoundaries($follower['relation-cid']);
$accounts[] = DI::mstdnAccount()->createFromContactId($follower['relation-cid'], $uid);

View file

@ -32,19 +32,18 @@ use Friendica\Module\BaseApi;
class Following extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!DBA::exists('contact', ['id' => $id, 'uid' => 0])) {
DI::mstdnError()->RecordNotFound();
}
@ -73,7 +72,7 @@ class Following extends BaseApi
$params['order'] = ['cid'];
}
$followers = DBA::select('contact-relation', ['cid'], $condition, $parameters);
$followers = DBA::select('contact-relation', ['cid'], $condition, $this->parameters);
while ($follower = DBA::fetch($followers)) {
self::setBoundaries($follower['cid']);
$accounts[] = DI::mstdnAccount()->createFromContactId($follower['cid'], $uid);

View file

@ -30,10 +30,9 @@ use Friendica\Module\BaseApi;
class IdentityProofs extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);

View file

@ -33,19 +33,18 @@ use Friendica\Module\BaseApi;
class Lists extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!DBA::exists('contact', ['id' => $id, 'uid' => 0])) {
DI::mstdnError()->RecordNotFound();
}

View file

@ -31,17 +31,17 @@ use Friendica\Module\BaseApi;
*/
class Mute extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_FOLLOW);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
Contact\User::setIgnored($parameters['id'], $uid, true);
Contact\User::setIgnored($this->parameters['id'], $uid, true);
System::jsonExit(DI::mstdnRelationship()->createFromContactId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnRelationship()->createFromContactId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -32,12 +32,12 @@ use Friendica\Module\BaseApi;
*/
class Note extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
@ -45,13 +45,13 @@ class Note extends BaseApi
'comment' => '',
]);
$cdata = Contact::getPublicAndUserContactID($parameters['id'], $uid);
$cdata = Contact::getPublicAndUserContactID($this->parameters['id'], $uid);
if (empty($cdata['user'])) {
DI::mstdnError()->RecordNotFound();
}
Contact::update(['info' => $request['comment']], ['id' => $cdata['user']]);
System::jsonExit(DI::mstdnRelationship()->createFromContactId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnRelationship()->createFromContactId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -32,10 +32,9 @@ use Friendica\Module\BaseApi;
class Relationships extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -35,10 +35,9 @@ use Friendica\Object\Search\ContactResult;
class Search extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -37,18 +37,17 @@ use Friendica\Protocol\Activity;
class Statuses extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!DBA::exists('contact', ['id' => $id, 'uid' => 0])) {
DI::mstdnError()->RecordNotFound();
}

View file

@ -31,17 +31,17 @@ use Friendica\Module\BaseApi;
*/
class Unblock extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_FOLLOW);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
Contact\User::setBlocked($parameters['id'], $uid, false);
Contact\User::setBlocked($this->parameters['id'], $uid, false);
System::jsonExit(DI::mstdnRelationship()->createFromContactId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnRelationship()->createFromContactId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -31,17 +31,17 @@ use Friendica\Module\BaseApi;
*/
class Unfollow extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_FOLLOW);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
Contact::unfollow($parameters['id'], $uid);
Contact::unfollow($this->parameters['id'], $uid);
System::jsonExit(DI::mstdnRelationship()->createFromContactId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnRelationship()->createFromContactId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -31,17 +31,17 @@ use Friendica\Module\BaseApi;
*/
class Unmute extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_FOLLOW);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
Contact\User::setIgnored($parameters['id'], $uid, false);
Contact\User::setIgnored($this->parameters['id'], $uid, false);
System::jsonExit(DI::mstdnRelationship()->createFromContactId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnRelationship()->createFromContactId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -32,7 +32,7 @@ use Friendica\Util\HTTPInputData;
*/
class UpdateCredentials extends BaseApi
{
public static function patch(array $parameters = [])
public function patch()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();

View file

@ -33,10 +33,9 @@ use Friendica\Module\BaseApi;
class VerifyCredentials extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -30,10 +30,9 @@ use Friendica\Module\BaseApi;
class Announcements extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);

View file

@ -33,10 +33,9 @@ use Friendica\Util\Network;
class Apps extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function post(array $parameters = [])
public function post()
{
$request = self::getRequest([
'client_name' => '',

View file

@ -30,7 +30,7 @@ use Friendica\Module\BaseApi;
*/
class VerifyCredentials extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$application = self::getCurrentApplication();

View file

@ -32,19 +32,18 @@ use Friendica\Module\BaseApi;
class Blocks extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!DBA::exists('contact', ['id' => $id, 'uid' => 0])) {
DI::mstdnError()->RecordNotFound();
}
@ -73,7 +72,7 @@ class Blocks extends BaseApi
$params['order'] = ['cid'];
}
$followers = DBA::select('user-contact', ['cid'], $condition, $parameters);
$followers = DBA::select('user-contact', ['cid'], $condition, $this->parameters);
while ($follower = DBA::fetch($followers)) {
self::setBoundaries($follower['cid']);
$accounts[] = DI::mstdnAccount()->createFromContactId($follower['cid'], $uid);

View file

@ -34,10 +34,9 @@ use Friendica\Network\HTTPException;
class Bookmarks extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -31,26 +31,25 @@ use Friendica\Module\BaseApi;
*/
class Conversations extends BaseApi
{
public static function delete(array $parameters = [])
public function delete()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (!empty($parameters['id'])) {
if (!empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
DBA::delete('conv', ['id' => $parameters['id'], 'uid' => $uid]);
DBA::delete('mail', ['convid' => $parameters['id'], 'uid' => $uid]);
DBA::delete('conv', ['id' => $this->parameters['id'], 'uid' => $uid]);
DBA::delete('mail', ['convid' => $this->parameters['id'], 'uid' => $uid]);
System::jsonExit([]);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -31,17 +31,17 @@ use Friendica\Module\BaseApi;
*/
class Read extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (!empty($parameters['id'])) {
if (!empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
DBA::update('mail', ['seen' => true], ['convid' => $parameters['id'], 'uid' => $uid]);
DBA::update('mail', ['seen' => true], ['convid' => $this->parameters['id'], 'uid' => $uid]);
System::jsonExit(DI::mstdnConversation()->CreateFromConvId($parameters['id'])->toArray());
System::jsonExit(DI::mstdnConversation()->CreateFromConvId($this->parameters['id'])->toArray());
}
}

View file

@ -33,12 +33,11 @@ use Friendica\Network\HTTPException;
class CustomEmojis extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
* @see https://docs.joinmastodon.org/methods/accounts/follow_requests#pending-follows
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$emojis = DI::mstdnEmoji()->createCollectionFromSmilies(Smilies::getList());

View file

@ -35,12 +35,11 @@ use Friendica\Network\HTTPException;
class Directory extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
* @see https://docs.joinmastodon.org/methods/instance/directory/
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$request = self::getRequest([
'offset' => 0, // How many accounts to skip before returning results. Default 0.

View file

@ -30,10 +30,9 @@ use Friendica\Module\BaseApi;
class Endorsements extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
System::jsonExit([]);
}

View file

@ -35,10 +35,9 @@ use Friendica\Protocol\Activity;
class Favourited extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -31,7 +31,7 @@ use Friendica\Module\BaseApi;
*/
class Filters extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
@ -39,10 +39,9 @@ class Filters extends BaseApi
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);

View file

@ -33,7 +33,6 @@ use Friendica\Network\HTTPException;
class FollowRequests extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\BadRequestException
* @throws HTTPException\InternalServerErrorException
* @throws HTTPException\NotFoundException
@ -43,16 +42,16 @@ class FollowRequests extends BaseApi
* @see https://docs.joinmastodon.org/methods/accounts/follow_requests#accept-follow
* @see https://docs.joinmastodon.org/methods/accounts/follow_requests#reject-follow
*/
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_FOLLOW);
$uid = self::getCurrentUserID();
$introduction = DI::intro()->selectOneById($parameters['id'], $uid);
$introduction = DI::intro()->selectOneById($this->parameters['id'], $uid);
$contactId = $introduction->cid;
switch ($parameters['action']) {
switch ($this->parameters['action']) {
case 'authorize':
Contact\Introduction::confirm($introduction);
$relationship = DI::mstdnRelationship()->createFromContactId($contactId, $uid);
@ -79,12 +78,11 @@ class FollowRequests extends BaseApi
}
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
* @see https://docs.joinmastodon.org/methods/accounts/follow_requests/
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -31,10 +31,9 @@ use Friendica\Object\Api\Mastodon\Instance as InstanceEntity;
class Instance extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
System::jsonExit(InstanceEntity::get());
}

View file

@ -34,10 +34,9 @@ use Friendica\Util\Network;
class Peers extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$return = [];

View file

@ -34,10 +34,9 @@ use Friendica\Network\HTTPException;
class Rules extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$rules = [];
$id = 0;

View file

@ -31,27 +31,27 @@ use Friendica\Model\Group;
*/
class Lists extends BaseApi
{
public static function delete(array $parameters = [])
public function delete()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
if (!Group::exists($parameters['id'], $uid)) {
if (!Group::exists($this->parameters['id'], $uid)) {
DI::mstdnError()->RecordNotFound();
}
if (!Group::remove($parameters['id'])) {
if (!Group::remove($this->parameters['id'])) {
DI::mstdnError()->InternalError();
}
System::jsonExit([]);
}
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -74,30 +74,29 @@ class Lists extends BaseApi
System::jsonExit(DI::mstdnList()->createFromGroupId($id));
}
public static function put(array $parameters = [])
public function put()
{
$request = self::getRequest([
'title' => '', // The title of the list to be updated.
'replies_policy' => '', // One of: "followed", "list", or "none".
]);
if (empty($request['title']) || empty($parameters['id'])) {
if (empty($request['title']) || empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
Group::update($parameters['id'], $request['title']);
Group::update($this->parameters['id'], $request['title']);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
$lists = [];
$groups = Group::getByUserId($uid);
@ -106,7 +105,7 @@ class Lists extends BaseApi
$lists[] = DI::mstdnList()->createFromGroupId($group['id']);
}
} else {
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!Group::exists($id, $uid)) {
DI::mstdnError()->RecordNotFound();

View file

@ -35,30 +35,29 @@ use Friendica\Module\BaseApi;
*/
class Accounts extends BaseApi
{
public static function delete(array $parameters = [])
public function delete()
{
DI::apiResponse()->unsupported(Router::DELETE);
}
public static function post(array $parameters = [])
public function post()
{
DI::apiResponse()->unsupported(Router::POST);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!DBA::exists('group', ['id' => $id, 'uid' => $uid])) {
DI::mstdnError()->RecordNotFound();
}

View file

@ -31,7 +31,7 @@ use Friendica\Module\BaseApi;
*/
class Markers extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
@ -39,10 +39,9 @@ class Markers extends BaseApi
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);

View file

@ -32,7 +32,7 @@ use Friendica\Module\BaseApi;
*/
class Media extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -53,7 +53,7 @@ class Media extends BaseApi
System::jsonExit(DI::mstdnAttachment()->createFromPhoto($media['id']));
}
public static function put(array $parameters = [])
public function put()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -65,34 +65,33 @@ class Media extends BaseApi
'focus' => '', // Two floating points (x,y), comma-delimited ranging from -1.0 to 1.0
]);
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$photo = Photo::selectFirst(['resource-id'], ['id' => $parameters['id'], 'uid' => $uid]);
$photo = Photo::selectFirst(['resource-id'], ['id' => $this->parameters['id'], 'uid' => $uid]);
if (empty($photo['resource-id'])) {
DI::mstdnError()->RecordNotFound();
}
Photo::update(['desc' => $request['description']], ['resource-id' => $photo['resource-id']]);
System::jsonExit(DI::mstdnAttachment()->createFromPhoto($parameters['id']));
System::jsonExit(DI::mstdnAttachment()->createFromPhoto($this->parameters['id']));
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!Photo::exists(['id' => $id, 'uid' => $uid])) {
DI::mstdnError()->RecordNotFound();
}

View file

@ -32,19 +32,18 @@ use Friendica\Module\BaseApi;
class Mutes extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!DBA::exists('contact', ['id' => $id, 'uid' => 0])) {
DI::mstdnError()->RecordNotFound();
}
@ -73,7 +72,7 @@ class Mutes extends BaseApi
$params['order'] = ['cid'];
}
$followers = DBA::select('user-contact', ['cid'], $condition, $parameters);
$followers = DBA::select('user-contact', ['cid'], $condition, $this->parameters);
while ($follower = DBA::fetch($followers)) {
self::setBoundaries($follower['cid']);
$accounts[] = DI::mstdnAccount()->createFromContactId($follower['cid'], $uid);

View file

@ -38,16 +38,15 @@ use Friendica\Protocol\Activity;
class Notifications extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (!empty($parameters['id'])) {
$id = $parameters['id'];
if (!empty($this->parameters['id'])) {
$id = $this->parameters['id'];
try {
$notification = DI::notification()->selectOneForUser($uid, ['id' => $id]);
System::jsonExit(DI::mstdnNotification()->createFromNotification($notification));

View file

@ -30,7 +30,7 @@ use Friendica\Module\BaseApi;
*/
class Clear extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();

View file

@ -32,16 +32,16 @@ use Friendica\Network\HTTPException\ForbiddenException;
*/
class Dismiss extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$Notification = DI::notification()->selectOneForUser($uid, $parameters['id']);
$Notification = DI::notification()->selectOneForUser($uid, $this->parameters['id']);
$Notification->setSeen();
DI::notification()->save($Notification);

View file

@ -32,10 +32,9 @@ use Friendica\Module\BaseApi;
class Preferences extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -30,10 +30,9 @@ use Friendica\Module\BaseApi;
class Proofs extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
System::jsonError(404, ['error' => 'Record not found']);
}

View file

@ -33,7 +33,7 @@ use Friendica\Object\Api\Mastodon\Notification;
*/
class PushSubscription extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();
@ -66,7 +66,7 @@ class PushSubscription extends BaseApi
return DI::mstdnSubscription()->createForApplicationIdAndUserId($application['id'], $uid)->toArray();
}
public static function put(array $parameters = [])
public function put()
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();
@ -99,7 +99,7 @@ class PushSubscription extends BaseApi
return DI::mstdnSubscription()->createForApplicationIdAndUserId($application['id'], $uid)->toArray();
}
public static function delete(array $parameters = [])
public function delete()
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();
@ -112,7 +112,7 @@ class PushSubscription extends BaseApi
System::jsonExit([]);
}
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();

View file

@ -34,7 +34,7 @@ use Friendica\Module\BaseApi;
*/
class ScheduledStatuses extends BaseApi
{
public static function put(array $parameters = [])
public function put()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -42,35 +42,34 @@ class ScheduledStatuses extends BaseApi
DI::apiResponse()->unsupported(Router::PUT);
}
public static function delete(array $parameters = [])
public function delete()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
if (!DBA::exists('delayed-post', ['id' => $parameters['id'], 'uid' => $uid])) {
if (!DBA::exists('delayed-post', ['id' => $this->parameters['id'], 'uid' => $uid])) {
DI::mstdnError()->RecordNotFound();
}
Post\Delayed::deleteById($parameters['id']);
Post\Delayed::deleteById($this->parameters['id']);
System::jsonExit([]);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (isset($parameters['id'])) {
System::jsonExit(DI::mstdnScheduledStatus()->createFromDelayedPostId($parameters['id'], $uid)->toArray());
if (isset($this->parameters['id'])) {
System::jsonExit(DI::mstdnScheduledStatus()->createFromDelayedPostId($this->parameters['id'], $uid)->toArray());
}
$request = self::getRequest([

View file

@ -38,10 +38,9 @@ use Friendica\Object\Search\ContactResult;
class Search extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
@ -74,7 +73,7 @@ class Search extends BaseApi
$result['statuses'] = self::searchStatuses($uid, $request['q'], $request['account_id'], $request['max_id'], $request['min_id'], $limit, $request['offset']);
}
if ((empty($request['type']) || ($request['type'] == 'hashtags')) && (strpos($request['q'], '@') == false)) {
$result['hashtags'] = self::searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $parameters['version']);
$result['hashtags'] = self::searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $this->parameters['version']);
}
System::jsonExit($result);

View file

@ -41,7 +41,7 @@ use Friendica\Util\Images;
*/
class Statuses extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
@ -207,16 +207,16 @@ class Statuses extends BaseApi
DI::mstdnError()->InternalError();
}
public static function delete(array $parameters = [])
public function delete()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $parameters['id'], 'uid' => $uid]);
$item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $this->parameters['id'], 'uid' => $uid]);
if (empty($item['id'])) {
DI::mstdnError()->RecordNotFound();
}
@ -229,17 +229,16 @@ class Statuses extends BaseApi
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid));
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid));
}
}

View file

@ -33,16 +33,16 @@ use Friendica\Module\BaseApi;
*/
class Bookmark extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -53,6 +53,6 @@ class Bookmark extends BaseApi
Item::update(['starred' => true], ['id' => $item['id']]);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -33,18 +33,17 @@ use Friendica\Network\HTTPException;
class Card extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!Post::exists(['uri-id' => $id, 'uid' => [0, $uid]])) {
throw new HTTPException\NotFoundException('Item with URI ID ' . $id . ' not found' . ($uid ? ' for user ' . $uid : '.'));

View file

@ -33,14 +33,13 @@ use Friendica\Module\BaseApi;
class Context extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
@ -48,7 +47,7 @@ class Context extends BaseApi
'limit' => 40, // Maximum number of results to return. Defaults to 40.
]);
$id = $parameters['id'];
$id = $this->parameters['id'];
$parents = [];
$children = [];

View file

@ -33,22 +33,22 @@ use Friendica\Module\BaseApi;
*/
class Favourite extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
Item::performActivity($item['id'], 'like', $uid);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -33,18 +33,17 @@ use Friendica\Protocol\Activity;
class FavouritedBy extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!Post::exists(['uri-id' => $id, 'uid' => [0, $uid]])) {
DI::mstdnError()->RecordNotFound();
}

View file

@ -32,16 +32,16 @@ use Friendica\Module\BaseApi;
*/
class Mute extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -50,8 +50,8 @@ class Mute extends BaseApi
DI::mstdnError()->UnprocessableEntity(DI::l10n()->t('Only starting posts can be muted'));
}
Post\ThreadUser::setIgnored($parameters['id'], $uid, true);
Post\ThreadUser::setIgnored($this->parameters['id'], $uid, true);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -32,16 +32,16 @@ use Friendica\Module\BaseApi;
*/
class Pin extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -50,8 +50,8 @@ class Pin extends BaseApi
DI::mstdnError()->UnprocessableEntity(DI::l10n()->t('Only starting posts can be pinned'));
}
Post\ThreadUser::setPinned($parameters['id'], $uid, true);
Post\ThreadUser::setPinned($this->parameters['id'], $uid, true);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -35,16 +35,16 @@ use Friendica\Module\BaseApi;
*/
class Reblog extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'network'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'network'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -55,6 +55,6 @@ class Reblog extends BaseApi
Item::performActivity($item['id'], 'announce', $uid);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -33,18 +33,17 @@ use Friendica\Protocol\Activity;
class RebloggedBy extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$id = $parameters['id'];
$id = $this->parameters['id'];
if (!Post::exists(['uri-id' => $id, 'uid' => [0, $uid]])) {
DI::mstdnError()->RecordNotFound();
}

View file

@ -33,16 +33,16 @@ use Friendica\Module\BaseApi;
*/
class Unbookmark extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -53,6 +53,6 @@ class Unbookmark extends BaseApi
Item::update(['starred' => false], ['id' => $item['id']]);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -33,22 +33,22 @@ use Friendica\Module\BaseApi;
*/
class Unfavourite extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
Item::performActivity($item['id'], 'unlike', $uid);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -32,16 +32,16 @@ use Friendica\Module\BaseApi;
*/
class Unmute extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -50,8 +50,8 @@ class Unmute extends BaseApi
DI::mstdnError()->UnprocessableEntity(DI::l10n()->t('Only starting posts can be unmuted'));
}
Post\ThreadUser::setIgnored($parameters['id'], $uid, false);
Post\ThreadUser::setIgnored($this->parameters['id'], $uid, false);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -32,16 +32,16 @@ use Friendica\Module\BaseApi;
*/
class Unpin extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'gravity'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -50,8 +50,8 @@ class Unpin extends BaseApi
DI::mstdnError()->UnprocessableEntity(DI::l10n()->t('Only starting posts can be pinned'));
}
Post\ThreadUser::setPinned($parameters['id'], $uid, false);
Post\ThreadUser::setPinned($this->parameters['id'], $uid, false);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -35,16 +35,16 @@ use Friendica\Module\BaseApi;
*/
class Unreblog extends BaseApi
{
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
$item = Post::selectFirstForUser($uid, ['id', 'network'], ['uri-id' => $parameters['id'], 'uid' => [$uid, 0]]);
$item = Post::selectFirstForUser($uid, ['id', 'network'], ['uri-id' => $this->parameters['id'], 'uid' => [$uid, 0]]);
if (!DBA::isResult($item)) {
DI::mstdnError()->RecordNotFound();
}
@ -55,6 +55,6 @@ class Unreblog extends BaseApi
Item::performActivity($item['id'], 'unannounce', $uid);
System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], $uid)->toArray());
System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid)->toArray());
}
}

View file

@ -32,10 +32,9 @@ use Friendica\Module\BaseApi;
class Suggestions extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -33,10 +33,9 @@ use Friendica\Network\HTTPException;
class Direct extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -34,10 +34,9 @@ use Friendica\Network\HTTPException;
class Home extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();

View file

@ -34,15 +34,14 @@ use Friendica\Network\HTTPException;
class ListTimeline extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
DI::mstdnError()->UnprocessableEntity();
}
@ -61,7 +60,7 @@ class ListTimeline extends BaseApi
$params = ['order' => ['uri-id' => true], 'limit' => $request['limit']];
$condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)",
$uid, GRAVITY_PARENT, GRAVITY_COMMENT, $parameters['id']];
$uid, GRAVITY_PARENT, GRAVITY_COMMENT, $this->parameters['id']];
if (!empty($request['max_id'])) {
$condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $request['max_id']]);

View file

@ -37,10 +37,9 @@ use Friendica\Network\HTTPException;
class PublicTimeline extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$uid = self::getCurrentUserID();

View file

@ -35,15 +35,14 @@ use Friendica\Network\HTTPException;
class Tag extends BaseApi
{
/**
* @param array $parameters
* @throws HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
if (empty($parameters['hashtag'])) {
if (empty($this->parameters['hashtag'])) {
DI::mstdnError()->UnprocessableEntity();
}
@ -70,7 +69,7 @@ class Tag extends BaseApi
$condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
$parameters['hashtag'], 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
$this->parameters['hashtag'], 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
if ($request['local']) {
$condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `origin`)"]);

View file

@ -32,10 +32,9 @@ use Friendica\Module\BaseApi;
class Trends extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$request = self::getRequest([
'limit' => 20, // Maximum number of results to return. Defaults to 10.

View file

@ -31,46 +31,41 @@ use Friendica\Module\BaseApi;
class Unimplemented extends BaseApi
{
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function delete(array $parameters = [])
public function delete()
{
DI::apiResponse()->unsupported(Router::DELETE);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function patch(array $parameters = [])
public function patch()
{
DI::apiResponse()->unsupported(Router::PATCH);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function post(array $parameters = [])
public function post()
{
DI::apiResponse()->unsupported(Router::POST);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function put(array $parameters = [])
public function put()
{
DI::apiResponse()->unsupported(Router::PUT);
}
/**
* @param array $parameters
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
DI::apiResponse()->unsupported(Router::GET);
}

View file

@ -30,9 +30,9 @@ use Friendica\Util\DateTimeFormat;
*/
class RateLimitStatus extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (!empty($parameters['extension']) && ($parameters['extension'] == 'xml')) {
if (!empty($this->parameters['extension']) && ($this->parameters['extension'] == 'xml')) {
$hash = [
'remaining-hits' => '150',
'@attributes' => ["type" => "integer"],
@ -48,10 +48,10 @@ class RateLimitStatus extends BaseApi
'reset_time_in_seconds' => strtotime('now + 1 hour'),
'remaining_hits' => '150',
'hourly_limit' => '150',
'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
'reset_time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::API),
];
}
DI::apiResponse()->exit('hash', ['hash' => $hash], $parameters['extension'] ?? null);
DI::apiResponse()->exit('hash', ['hash' => $hash], $this->parameters['extension'] ?? null);
}
}

View file

@ -21,6 +21,7 @@
namespace Friendica\Module\Api\Twitter;
use Friendica\Core\L10n;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\Profile;
@ -35,9 +36,9 @@ abstract class ContactEndpoint extends BaseApi
const DEFAULT_COUNT = 20;
const MAX_COUNT = 200;
public static function init(array $parameters = [])
public function __construct(L10n $l10n, array $parameters = [])
{
parent::init($parameters);
parent::__construct($l10n, $parameters);
self::checkAllowedScope(self::SCOPE_READ);
}

View file

@ -19,17 +19,18 @@
*
*/
namespace Friendica\Module\Api\Twitter;
namespace Friendica\Module\Api\Twitter\Followers;
use Friendica\Core\System;
use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\ContactEndpoint;
/**
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
*/
class FollowersIds extends ContactEndpoint
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
// Expected value for user_id parameter: public/user contact id
$contact_id = filter_input(INPUT_GET, 'user_id' , FILTER_VALIDATE_INT);
@ -47,6 +48,8 @@ class FollowersIds extends ContactEndpoint
'default' => 1,
]]);
// @todo Use Model\Contact\Relation::listFollowers($cid, $condition, $count);
System::jsonExit(self::ids(
[Contact::FOLLOWER, Contact::FRIEND],
self::getUid($contact_id, $screen_name),

View file

@ -19,17 +19,18 @@
*
*/
namespace Friendica\Module\Api\Twitter;
namespace Friendica\Module\Api\Twitter\Followers;
use Friendica\Core\System;
use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\ContactEndpoint;
/**
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-list
*/
class FollowersList extends ContactEndpoint
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
// Expected value for user_id parameter: public/user contact id
$contact_id = filter_input(INPUT_GET, 'user_id' , FILTER_VALIDATE_INT);
@ -49,6 +50,7 @@ class FollowersList extends ContactEndpoint
'default' => 1,
]]);
// @todo Use Model\Contact\Relation::listFollowers($cid, $condition, $count);
System::jsonExit(self::list(
[Contact::FOLLOWER, Contact::FRIEND],

View file

@ -19,17 +19,18 @@
*
*/
namespace Friendica\Module\Api\Twitter;
namespace Friendica\Module\Api\Twitter\Friends;
use Friendica\Core\System;
use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\ContactEndpoint;
/**
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
*/
class FriendsIds extends ContactEndpoint
class Ids extends ContactEndpoint
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
// Expected value for user_id parameter: public/user contact id
$contact_id = filter_input(INPUT_GET, 'user_id' , FILTER_VALIDATE_INT);
@ -47,6 +48,8 @@ class FriendsIds extends ContactEndpoint
'default' => 1,
]]);
// @todo Use Model\Contact\Relation::listFollows($cid, $condition, $count);
System::jsonExit(self::ids(
[Contact::SHARING, Contact::FRIEND],
self::getUid($contact_id, $screen_name),

View file

@ -19,17 +19,18 @@
*
*/
namespace Friendica\Module\Api\Twitter;
namespace Friendica\Module\Api\Twitter\Friends;
use Friendica\Core\System;
use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\ContactEndpoint;
/**
* @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list
*/
class FriendsList extends ContactEndpoint
class Lists extends ContactEndpoint
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
// Expected value for user_id parameter: public/user contact id
$contact_id = filter_input(INPUT_GET, 'user_id' , FILTER_VALIDATE_INT);
@ -49,6 +50,8 @@ class FriendsList extends ContactEndpoint
'default' => 1,
]]);
// @todo Use Model\Contact\Relation::listFollows($cid, $condition, $count);
System::jsonExit(self::list(
[Contact::SHARING, Contact::FRIEND],
self::getUid($contact_id, $screen_name),

View file

@ -31,7 +31,7 @@ use Friendica\Module\BaseApi;
*/
class SavedSearches extends BaseApi
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
@ -45,6 +45,6 @@ class SavedSearches extends BaseApi
DBA::close($terms);
DI::apiResponse()->exit('terms', ['terms' => $result], $parameters['extension'] ?? null);
DI::apiResponse()->exit('terms', ['terms' => $result], $this->parameters['extension'] ?? null);
}
}

View file

@ -21,35 +21,39 @@
namespace Friendica\Module;
use Friendica\App\BaseURL;
use Friendica\BaseModule;
use Friendica\Content\Nav;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\DI;
/**
* Shows the App menu
*/
class Apps extends BaseModule
{
public static function init(array $parameters = [])
public function __construct(L10n $l10n, IManageConfigValues $config, BaseURL $baseUrl, array $parameters = [])
{
$privateaddons = DI::config()->get('config', 'private_addons');
parent::__construct($l10n, $parameters);
$privateaddons = $config->get('config', 'private_addons');
if ($privateaddons === "1" && !local_user()) {
DI::baseUrl()->redirect();
$baseUrl->redirect();
}
}
public static function content(array $parameters = [])
public function content(): string
{
$apps = Nav::getAppMenu();
if (count($apps) == 0) {
notice(DI::l10n()->t('No installed applications.'));
notice($this->t('No installed applications.'));
}
$tpl = Renderer::getMarkupTemplate('apps.tpl');
return Renderer::replaceMacros($tpl, [
'$title' => DI::l10n()->t('Applications'),
'$title' => $this->t('Applications'),
'$apps' => $apps,
]);
}

View file

@ -34,14 +34,14 @@ class Attach extends BaseModule
/**
* Return to user an attached file given the id
*/
public static function rawContent(array $parameters = [])
public function rawContent()
{
$a = DI::app();
if (empty($parameters['item'])) {
if (empty($this->parameters['item'])) {
throw new \Friendica\Network\HTTPException\BadRequestException();
}
$item_id = intval($parameters['item']);
$item_id = intval($this->parameters['item']);
// Check for existence
$item = MAttach::exists(['id' => $item_id]);

View file

@ -68,7 +68,7 @@ abstract class BaseAdmin extends BaseModule
}
}
public static function content(array $parameters = [])
public function content(): string
{
self::checkAdminAccess(true);

View file

@ -25,16 +25,13 @@ use Friendica\BaseModule;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Post;
use Friendica\Network\HTTPException;
use Friendica\Security\BasicAuth;
use Friendica\Security\OAuth;
use Friendica\Util\Arrays;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\HTTPInputData;
use Friendica\Util\XML;
require_once __DIR__ . '/../../include/api.php';
class BaseApi extends BaseModule
{
@ -53,7 +50,7 @@ class BaseApi extends BaseModule
*/
protected static $request = [];
public static function delete(array $parameters = [])
public function delete()
{
self::checkAllowedScope(self::SCOPE_WRITE);
@ -62,7 +59,7 @@ class BaseApi extends BaseModule
}
}
public static function patch(array $parameters = [])
public function patch()
{
self::checkAllowedScope(self::SCOPE_WRITE);
@ -71,7 +68,7 @@ class BaseApi extends BaseModule
}
}
public static function post(array $parameters = [])
public function post()
{
self::checkAllowedScope(self::SCOPE_WRITE);
@ -80,7 +77,7 @@ class BaseApi extends BaseModule
}
}
public static function put(array $parameters = [])
public function put()
{
self::checkAllowedScope(self::SCOPE_WRITE);
@ -139,7 +136,6 @@ class BaseApi extends BaseModule
* Set boundaries for the "link" header
* @param array $boundaries
* @param int $id
* @return array
*/
protected static function setBoundaries(int $id)
{
@ -296,18 +292,14 @@ class BaseApi extends BaseModule
}
}
/**
* Get user info array.
*
* @param int|string $contact_id Contact ID or URL
* @return array|bool
* @throws HTTPException\BadRequestException
* @throws HTTPException\InternalServerErrorException
* @throws HTTPException\UnauthorizedException
* @throws \ImagickException
*/
protected static function getUser($contact_id = null)
public static function getContactIDForSearchterm($searchterm)
{
return api_get_user($contact_id);
if (intval($searchterm) == 0) {
$cid = Contact::getIdForURL($searchterm, 0, false);
} else {
$cid = intval($searchterm);
}
return $cid;
}
}

View file

@ -22,11 +22,12 @@
namespace Friendica\Module;
use Exception;
use Friendica\App\Arguments;
use Friendica\BaseModule;
use Friendica\Content\Pager;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Core\System;
use Friendica\DI;
use Friendica\Navigation\Notifications\ValueObject\FormattedNotification;
use Friendica\Network\HTTPException\ForbiddenException;
@ -70,9 +71,12 @@ abstract class BaseNotifications extends BaseModule
const DEFAULT_PAGE_LIMIT = 80;
/** @var boolean True, if ALL entries should get shown */
protected static $showAll;
protected $showAll;
/** @var int The determined start item of the current page */
protected static $firstItemNum;
protected $firstItemNum;
/** @var Arguments */
protected $args;
/**
* Collects all notifications from the backend
@ -80,33 +84,37 @@ abstract class BaseNotifications extends BaseModule
* @return array The determined notification array
* ['header', 'notifications']
*/
abstract public static function getNotifications();
abstract public function getNotifications();
public static function init(array $parameters = [])
public function __construct(Arguments $args, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
if (!local_user()) {
throw new ForbiddenException(DI::l10n()->t('Permission denied.'));
throw new ForbiddenException($this->t('Permission denied.'));
}
$page = ($_REQUEST['page'] ?? 0) ?: 1;
self::$firstItemNum = ($page * self::ITEMS_PER_PAGE) - self::ITEMS_PER_PAGE;
self::$showAll = ($_REQUEST['show'] ?? '') === 'all';
$this->firstItemNum = ($page * self::ITEMS_PER_PAGE) - self::ITEMS_PER_PAGE;
$this->showAll = ($_REQUEST['show'] ?? '') === 'all';
$this->args = $args;
}
public static function rawContent(array $parameters = [])
public function rawContent()
{
// If the last argument of the query is NOT json, return
if (DI::args()->get(DI::args()->getArgc() - 1) !== 'json') {
if ($this->args->get($this->args->getArgc() - 1) !== 'json') {
return;
}
// Set the pager
$pager = new Pager(DI::l10n(), DI::args()->getQueryString(), self::ITEMS_PER_PAGE);
$pager = new Pager($this->l10n, $this->args->getQueryString(), self::ITEMS_PER_PAGE);
// Add additional informations (needed for json output)
$notifications = [
'notifications' => static::getNotifications(),
'notifications' => $this->getNotifications(),
'items_page' => $pager->getItemsPerPage(),
'page' => $pager->getPage(),
];
@ -126,17 +134,17 @@ abstract class BaseNotifications extends BaseModule
*
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
protected static function printContent(string $header, array $notifications, string $noContent, array $showLink)
protected function printContent(string $header, array $notifications, string $noContent, array $showLink)
{
// Get the nav tabs for the notification pages
$tabs = self::getTabs();
$tabs = $this->getTabs();
// Set the pager
$pager = new Pager(DI::l10n(), DI::args()->getQueryString(), self::ITEMS_PER_PAGE);
$pager = new Pager($this->l10n, $this->args->getQueryString(), self::ITEMS_PER_PAGE);
$notif_tpl = Renderer::getMarkupTemplate('notifications/notifications.tpl');
return Renderer::replaceMacros($notif_tpl, [
'$header' => $header ?? DI::l10n()->t('Notifications'),
'$header' => $header ?? $this->t('Notifications'),
'$tabs' => $tabs,
'$notifications' => $notifications,
'$noContent' => $noContent,
@ -151,15 +159,15 @@ abstract class BaseNotifications extends BaseModule
* @return array with with notifications TabBar data
* @throws Exception
*/
private static function getTabs()
private function getTabs()
{
$selected = DI::args()->get(1, '');
$selected = $this->args->get(1, '');
$tabs = [];
foreach (self::URL_TYPES as $type => $url) {
$tabs[] = [
'label' => DI::l10n()->t(self::PRINT_TYPES[$type]),
'label' => $this->t(self::PRINT_TYPES[$type]),
'url' => 'notifications/' . $url,
'sel' => (($selected == $url) ? 'active' : ''),
'id' => $type . '-tab',

View file

@ -28,7 +28,7 @@ use Friendica\DI;
class BaseSettings extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$a = DI::app();
@ -125,5 +125,7 @@ class BaseSettings extends BaseModule
'$class' => 'settings-widget',
'$items' => $tabs,
]);
return '';
}
}

View file

@ -34,7 +34,7 @@ use Friendica\Util\Strings;
*/
class Bookmarklet extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$_GET['mode'] = 'minimal';

View file

@ -96,7 +96,7 @@ class Contact extends BaseModule
DI::baseUrl()->redirect($redirectUrl);
}
public static function post(array $parameters = [])
public function post()
{
if (!local_user()) {
return;
@ -226,7 +226,7 @@ class Contact extends BaseModule
Model\Contact\User::setIgnored($contact_id, local_user(), $ignored);
}
public static function content(array $parameters = [], $update = 0)
public function content($update = 0): string
{
if (!local_user()) {
return Login::form($_SERVER['REQUEST_URI']);

View file

@ -21,37 +21,53 @@
namespace Friendica\Module\Contact;
use Friendica\App\Page;
use Friendica\BaseModule;
use Friendica\Content\Widget;
use Friendica\Core\L10n;
use Friendica\Core\Protocol;
use Friendica\Core\Renderer;
use Friendica\Core\Session;
use Friendica\DI;
use Friendica\Database\Database;
use Friendica\Model;
use Friendica\Module\Contact;
use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Network\HTTPException\ForbiddenException;
use Friendica\Util\Strings;
use Psr\Log\LoggerInterface;
/**
* GUI for advanced contact details manipulation
*/
class Advanced extends BaseModule
{
public static function init(array $parameters = [])
/** @var Database */
protected $dba;
/** @var LoggerInterface */
protected $logger;
/** @var Page */
protected $page;
public function __construct(Database $dba, LoggerInterface $logger, Page $page, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
$this->dba = $dba;
$this->logger = $logger;
$this->page = $page;
if (!Session::isAuthenticated()) {
throw new ForbiddenException(DI::l10n()->t('Permission denied.'));
throw new ForbiddenException($this->t('Permission denied.'));
}
}
public static function post(array $parameters = [])
public function post()
{
$cid = $parameters['id'];
$cid = $this->parameters['id'];
$contact = Model\Contact::selectFirst([], ['id' => $cid, 'uid' => local_user()]);
if (empty($contact)) {
throw new BadRequestException(DI::l10n()->t('Contact not found.'));
throw new BadRequestException($this->t('Contact not found.'));
}
$name = ($_POST['name'] ?? '') ?: $contact['name'];
@ -66,7 +82,7 @@ class Advanced extends BaseModule
$photo = $_POST['photo'] ?? '';
$nurl = Strings::normaliseLink($url);
$r = DI::dba()->update(
$r = $this->dba->update(
'contact',
[
'name' => $name,
@ -84,31 +100,29 @@ class Advanced extends BaseModule
);
if ($photo) {
DI::logger()->notice('Updating photo.', ['photo' => $photo]);
$this->logger->notice('Updating photo.', ['photo' => $photo]);
Model\Contact::updateAvatar($contact['id'], $photo, true);
}
if (!$r) {
notice(DI::l10n()->t('Contact update failed.'));
notice($this->t('Contact update failed.'));
}
return;
}
public static function content(array $parameters = [])
public function content(): string
{
$cid = $parameters['id'];
$cid = $this->parameters['id'];
$contact = Model\Contact::selectFirst([], ['id' => $cid, 'uid' => local_user()]);
if (empty($contact)) {
throw new BadRequestException(DI::l10n()->t('Contact not found.'));
throw new BadRequestException($this->t('Contact not found.'));
}
DI::page()['aside'] = Widget\VCard::getHTML($contact);
$this->page['aside'] = Widget\VCard::getHTML($contact);
$warning = DI::l10n()->t('<strong>WARNING: This is highly advanced</strong> and if you enter incorrect information your communications with this contact may stop working.');
$info = DI::l10n()->t('Please use your browser \'Back\' button <strong>now</strong> if you are uncertain what to do on this page.');
$warning = $this->t('<strong>WARNING: This is highly advanced</strong> and if you enter incorrect information your communications with this contact may stop working.');
$info = $this->t('Please use your browser \'Back\' button <strong>now</strong> if you are uncertain what to do on this page.');
$returnaddr = "contact/$cid";
@ -128,20 +142,20 @@ class Advanced extends BaseModule
'$warning' => $warning,
'$info' => $info,
'$returnaddr' => $returnaddr,
'$return' => DI::l10n()->t('Return to contact editor'),
'$return' => $this->t('Return to contact editor'),
'$contact_id' => $contact['id'],
'$lbl_submit' => DI::l10n()->t('Submit'),
'$lbl_submit' => $this->t('Submit'),
'$name' => ['name', DI::l10n()->t('Name'), $contact['name'], '', '', $readonly],
'$nick' => ['nick', DI::l10n()->t('Account Nickname'), $contact['nick'], '', '', $readonly],
'$attag' => ['attag', DI::l10n()->t('@Tagname - overrides Name/Nickname'), $contact['attag']],
'$url' => ['url', DI::l10n()->t('Account URL'), $contact['url'], '', '', $readonly],
'$alias' => ['alias', DI::l10n()->t('Account URL Alias'), $contact['alias'], '', '', $readonly],
'$request' => ['request', DI::l10n()->t('Friend Request URL'), $contact['request'], '', '', $readonly],
'confirm' => ['confirm', DI::l10n()->t('Friend Confirm URL'), $contact['confirm'], '', '', $readonly],
'notify' => ['notify', DI::l10n()->t('Notification Endpoint URL'), $contact['notify'], '', '', $readonly],
'poll' => ['poll', DI::l10n()->t('Poll/Feed URL'), $contact['poll'], '', '', $readonly],
'photo' => ['photo', DI::l10n()->t('New photo from this URL'), '', '', '', $readonly],
'$name' => ['name', $this->t('Name'), $contact['name'], '', '', $readonly],
'$nick' => ['nick', $this->t('Account Nickname'), $contact['nick'], '', '', $readonly],
'$attag' => ['attag', $this->t('@Tagname - overrides Name/Nickname'), $contact['attag']],
'$url' => ['url', $this->t('Account URL'), $contact['url'], '', '', $readonly],
'$alias' => ['alias', $this->t('Account URL Alias'), $contact['alias'], '', '', $readonly],
'$request' => ['request', $this->t('Friend Request URL'), $contact['request'], '', '', $readonly],
'confirm' => ['confirm', $this->t('Friend Confirm URL'), $contact['confirm'], '', '', $readonly],
'notify' => ['notify', $this->t('Notification Endpoint URL'), $contact['notify'], '', '', $readonly],
'poll' => ['poll', $this->t('Poll/Feed URL'), $contact['poll'], '', '', $readonly],
'photo' => ['photo', $this->t('New photo from this URL'), '', '', '', $readonly],
]);
}
}

View file

@ -14,7 +14,7 @@ use Friendica\Network\HTTPException;
class Contacts extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$app = DI::app();
@ -22,8 +22,8 @@ class Contacts extends BaseModule
throw new HTTPException\ForbiddenException();
}
$cid = $parameters['id'];
$type = $parameters['type'] ?? 'all';
$cid = $this->parameters['id'];
$type = $this->parameters['type'] ?? 'all';
$accounttype = $_GET['accounttype'] ?? '';
$accounttypeid = User::getAccountTypeByString($accounttype);

View file

@ -35,7 +35,7 @@ use Friendica\Util\Strings;
*/
class Hovercard extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$contact_url = $_REQUEST['url'] ?? '';

View file

@ -34,9 +34,9 @@ use Friendica\Network\HTTPException\BadRequestException;
*/
class Media extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$cid = $parameters['id'];
$cid = $this->parameters['id'];
$contact = Model\Contact::selectFirst([], ['id' => $cid]);
if (empty($contact)) {

View file

@ -18,9 +18,9 @@ use Friendica\Util\XML;
class Poke extends BaseModule
{
public static function post(array $parameters = [])
public function post()
{
if (!local_user() || empty($parameters['id'])) {
if (!local_user() || empty($this->parameters['id'])) {
return self::postReturn(false);
}
@ -39,14 +39,14 @@ class Poke extends BaseModule
$activity = Activity::POKE . '#' . urlencode($verbs[$verb][0]);
$contact_id = intval($parameters['id']);
$contact_id = intval($this->parameters['id']);
if (!$contact_id) {
return self::postReturn(false);
}
Logger::info('verb ' . $verb . ' contact ' . $contact_id);
$contact = DBA::selectFirst('contact', ['id', 'name', 'url', 'photo'], ['id' => $parameters['id'], 'uid' => local_user()]);
$contact = DBA::selectFirst('contact', ['id', 'name', 'url', 'photo'], ['id' => $this->parameters['id'], 'uid' => local_user()]);
if (!DBA::isResult($contact)) {
return self::postReturn(false);
}
@ -123,17 +123,17 @@ class Poke extends BaseModule
return $success;
}
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this module.'));
}
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
throw new HTTPException\BadRequestException();
}
$contact = DBA::selectFirst('contact', ['id', 'url', 'name'], ['id' => $parameters['id'], 'uid' => local_user()]);
$contact = DBA::selectFirst('contact', ['id', 'url', 'name'], ['id' => $this->parameters['id'], 'uid' => local_user()]);
if (!DBA::isResult($contact)) {
throw new HTTPException\NotFoundException();
}

View file

@ -21,12 +21,14 @@
namespace Friendica\Module\Contact;
use Friendica\App\Arguments;
use Friendica\App\BaseURL;
use Friendica\BaseModule;
use Friendica\Content\Nav;
use Friendica\Core\L10n;
use Friendica\Core\Protocol;
use Friendica\Core\Renderer;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Database\Database;
use Friendica\Model;
use Friendica\Module\Contact;
use Friendica\Module\Security\Login;
@ -35,55 +37,68 @@ use Friendica\Network\HTTPException;
class Revoke extends BaseModule
{
/** @var array */
private static $contact;
public static function init(array $parameters = [])
protected $contact;
/** @var Database */
protected $dba;
/** @var BaseURL */
protected $baseUrl;
/** @var Arguments */
protected $args;
public function __construct(Database $dba, BaseURL $baseUrl, Arguments $args, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
$this->dba = $dba;
$this->baseUrl = $baseUrl;
$this->args = $args;
if (!local_user()) {
return;
}
$data = Model\Contact::getPublicAndUserContactID($parameters['id'], local_user());
if (!DBA::isResult($data)) {
throw new HTTPException\NotFoundException(DI::l10n()->t('Unknown contact.'));
$data = Model\Contact::getPublicAndUserContactID($this->parameters['id'], local_user());
if (!$this->dba->isResult($data)) {
throw new HTTPException\NotFoundException($this->t('Unknown contact.'));
}
if (empty($data['user'])) {
throw new HTTPException\ForbiddenException();
}
self::$contact = Model\Contact::getById($data['user']);
$this->contact = Model\Contact::getById($data['user']);
if (self::$contact['deleted']) {
throw new HTTPException\NotFoundException(DI::l10n()->t('Contact is deleted.'));
if ($this->contact['deleted']) {
throw new HTTPException\NotFoundException($this->t('Contact is deleted.'));
}
if (!empty(self::$contact['network']) && self::$contact['network'] == Protocol::PHANTOM) {
throw new HTTPException\NotFoundException(DI::l10n()->t('Contact is being deleted.'));
if (!empty($this->contact['network']) && $this->contact['network'] == Protocol::PHANTOM) {
throw new HTTPException\NotFoundException($this->t('Contact is being deleted.'));
}
}
public static function post(array $parameters = [])
public function post()
{
if (!local_user()) {
throw new HTTPException\UnauthorizedException();
}
self::checkFormSecurityTokenRedirectOnError('contact/' . $parameters['id'], 'contact_revoke');
self::checkFormSecurityTokenRedirectOnError('contact/' . $this->parameters['id'], 'contact_revoke');
$result = Model\Contact::revokeFollow(self::$contact);
$result = Model\Contact::revokeFollow($this->contact);
if ($result === true) {
notice(DI::l10n()->t('Follow was successfully revoked.'));
notice($this->t('Follow was successfully revoked.'));
} elseif ($result === null) {
notice(DI::l10n()->t('Follow was successfully revoked, however the remote contact won\'t be aware of this revokation.'));
notice($this->t('Follow was successfully revoked, however the remote contact won\'t be aware of this revokation.'));
} else {
notice(DI::l10n()->t('Unable to revoke follow, please try again later or contact the administrator.'));
notice($this->t('Unable to revoke follow, please try again later or contact the administrator.'));
}
DI::baseUrl()->redirect('contact/' . $parameters['id']);
$this->baseUrl->redirect('contact/' . $this->parameters['id']);
}
public static function content(array $parameters = []): string
public function content(): string
{
if (!local_user()) {
return Login::form($_SERVER['REQUEST_URI']);
@ -93,14 +108,14 @@ class Revoke extends BaseModule
return Renderer::replaceMacros(Renderer::getMarkupTemplate('contact_drop_confirm.tpl'), [
'$l10n' => [
'header' => DI::l10n()->t('Revoke Follow'),
'message' => DI::l10n()->t('Do you really want to revoke this contact\'s follow? This cannot be undone and they will have to manually follow you back again.'),
'confirm' => DI::l10n()->t('Yes'),
'cancel' => DI::l10n()->t('Cancel'),
'header' => $this->t('Revoke Follow'),
'message' => $this->t('Do you really want to revoke this contact\'s follow? This cannot be undone and they will have to manually follow you back again.'),
'confirm' => $this->t('Yes'),
'cancel' => $this->t('Cancel'),
],
'$contact' => Contact::getContactTemplateVars(self::$contact),
'$contact' => Contact::getContactTemplateVars($this->contact),
'$method' => 'post',
'$confirm_url' => DI::args()->getCommand(),
'$confirm_url' => $this->args->getCommand(),
'$confirm_name' => 'form_security_token',
'$confirm_value' => BaseModule::getFormSecurityToken('contact_revoke'),
]);

View file

@ -49,9 +49,9 @@ class Community extends BaseModule
protected static $max_id;
protected static $item_id;
public static function content(array $parameters = [])
public function content(): string
{
self::parseRequest($parameters);
$this->parseRequest();
if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
$tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
@ -94,8 +94,8 @@ class Community extends BaseModule
if (local_user() && DI::config()->get('system', 'community_no_sharer')) {
$path = self::$content;
if (!empty($parameters['accounttype'])) {
$path .= '/' . $parameters['accounttype'];
if (!empty($this->parameters['accounttype'])) {
$path .= '/' . $this->parameters['accounttype'];
}
$query_parameters = [];
@ -166,11 +166,10 @@ class Community extends BaseModule
/**
* Computes module parameters from the request and local configuration
*
* @param array $parameters
* @throws HTTPException\BadRequestException
* @throws HTTPException\ForbiddenException
*/
protected static function parseRequest(array $parameters)
protected function parseRequest()
{
if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Public access denied.'));
@ -182,10 +181,10 @@ class Community extends BaseModule
throw new HTTPException\ForbiddenException(DI::l10n()->t('Access denied.'));
}
self::$accountTypeString = $_GET['accounttype'] ?? $parameters['accounttype'] ?? '';
self::$accountTypeString = $_GET['accounttype'] ?? $this->parameters['accounttype'] ?? '';
self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
self::$content = $parameters['content'] ?? '';
self::$content = $this->parameters['content'] ?? '';
if (!self::$content) {
if (!empty(DI::config()->get('system', 'singleuser'))) {
// On single user systems only the global page does make sense

View file

@ -57,13 +57,13 @@ class Network extends BaseModule
/** @var string */
protected static $order;
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
return Login::form();
}
self::parseRequest($parameters, $_GET);
$this->parseRequest($_GET);
$module = 'network';
@ -272,11 +272,11 @@ class Network extends BaseModule
return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
}
protected static function parseRequest(array $parameters, array $get)
protected function parseRequest(array $get)
{
self::$groupId = $parameters['group_id'] ?? 0;
self::$groupId = $this->parameters['group_id'] ?? 0;
self::$forumContactId = $parameters['contact_id'] ?? 0;
self::$forumContactId = $this->parameters['contact_id'] ?? 0;
self::$selectedTab = Session::get('network-tab', DI::pConfig()->get(local_user(), 'network.view', 'selected_tab', ''));
@ -317,13 +317,13 @@ class Network extends BaseModule
Session::set('network-tab', self::$selectedTab);
DI::pConfig()->set(local_user(), 'network.view', 'selected_tab', self::$selectedTab);
self::$accountTypeString = $get['accounttype'] ?? $parameters['accounttype'] ?? '';
self::$accountTypeString = $get['accounttype'] ?? $this->parameters['accounttype'] ?? '';
self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
self::$network = $get['nets'] ?? '';
self::$dateFrom = $parameters['from'] ?? '';
self::$dateTo = $parameters['to'] ?? '';
self::$dateFrom = $this->parameters['from'] ?? '';
self::$dateTo = $this->parameters['to'] ?? '';
if (DI::mode()->isMobile()) {
self::$itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',

View file

@ -32,7 +32,7 @@ use Friendica\DI;
*/
class Credits extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
/* fill the page with credits */
$credits_string = file_get_contents('CREDITS.txt');

View file

@ -38,7 +38,7 @@ use Friendica\Network\HTTPException;
*/
class Notify extends BaseModule
{
public static function post(array $parameters = [])
public function post()
{
$postdata = Network::postdata();
@ -47,8 +47,8 @@ class Notify extends BaseModule
}
$data = json_decode($postdata);
if (is_object($data) && !empty($parameters['nickname'])) {
$user = User::getByNickname($parameters['nickname']);
if (is_object($data) && !empty($this->parameters['nickname'])) {
$user = User::getByNickname($this->parameters['nickname']);
if (empty($user)) {
throw new \Friendica\Network\HTTPException\InternalServerErrorException();
}

View file

@ -29,11 +29,11 @@ use Friendica\Protocol\OStatus;
*/
class Poll extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
header("Content-type: application/atom+xml");
$last_update = $_GET['last_update'] ?? '';
echo OStatus::feed($parameters['nickname'], $last_update, 10);
echo OStatus::feed($this->parameters['nickname'], $last_update, 10);
exit();
}
}

View file

@ -34,7 +34,7 @@ use Friendica\Util\XML;
class ActivityPubConversion extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
function visible_whitespace($s)
{

View file

@ -35,7 +35,7 @@ use Friendica\Util\XML;
*/
class Babel extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
function visible_whitespace($s)
{

View file

@ -21,10 +21,12 @@
namespace Friendica\Module\Debug;
use Friendica\App\BaseURL;
use Friendica\BaseModule;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\DI;
use Friendica\Model;
use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
use Friendica\Protocol;
/**
@ -32,15 +34,22 @@ use Friendica\Protocol;
*/
class Feed extends BaseModule
{
public static function init(array $parameters = [])
/** @var ICanSendHttpRequests */
protected $httpClient;
public function __construct(BaseURL $baseUrl, ICanSendHttpRequests $httpClient, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
$this->httpClient = $httpClient;
if (!local_user()) {
notice(DI::l10n()->t('You must be logged in to use this module'));
DI::baseUrl()->redirect();
notice($this->t('You must be logged in to use this module'));
$baseUrl->redirect();
}
}
public static function content(array $parameters = [])
public function content(): string
{
$result = [];
if (!empty($_REQUEST['url'])) {
@ -48,7 +57,7 @@ class Feed extends BaseModule
$contact = Model\Contact::getByURLForUser($url, local_user(), null);
$xml = DI::httpClient()->fetch($contact['poll']);
$xml = $this->httpClient->fetch($contact['poll']);
$import_result = Protocol\Feed::import($xml);
@ -60,7 +69,7 @@ class Feed extends BaseModule
$tpl = Renderer::getMarkupTemplate('feedtest.tpl');
return Renderer::replaceMacros($tpl, [
'$url' => ['url', DI::l10n()->t('Source URL'), $_REQUEST['url'] ?? '', ''],
'$url' => ['url', $this->t('Source URL'), $_REQUEST['url'] ?? '', ''],
'$result' => $result
]);
}

View file

@ -31,17 +31,17 @@ use Friendica\Network\HTTPException;
*/
class ItemBody extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
throw new HTTPException\UnauthorizedException(DI::l10n()->t('Access denied.'));
}
if (empty($parameters['item'])) {
if (empty($this->parameters['item'])) {
throw new HTTPException\NotFoundException(DI::l10n()->t('Item not found.'));
}
$itemId = intval($parameters['item']);
$itemId = intval($this->parameters['item']);
$item = Post::selectFirst(['body'], ['uid' => [0, local_user()], 'uri-id' => $itemId]);

View file

@ -31,7 +31,7 @@ class Localtime extends BaseModule
{
static $mod_localtime = '';
public static function post(array $parameters = [])
public function post()
{
$time = ($_REQUEST['time'] ?? '') ?: 'now';
@ -42,7 +42,7 @@ class Localtime extends BaseModule
}
}
public static function content(array $parameters = [])
public function content(): string
{
$time = ($_REQUEST['time'] ?? '') ?: 'now';

View file

@ -32,7 +32,7 @@ use Friendica\Network\Probe as NetworkProbe;
*/
class Probe extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Only logged in users are permitted to perform a probing.'));

View file

@ -31,7 +31,7 @@ use Friendica\Network\Probe;
*/
class WebFinger extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
throw new \Friendica\Network\HTTPException\ForbiddenException(DI::l10n()->t('Only logged in users are permitted to perform a probing.'));

View file

@ -37,7 +37,7 @@ use Friendica\Util\Proxy;
*/
class Delegation extends BaseModule
{
public static function post(array $parameters = [])
public function post()
{
if (!local_user()) {
return;
@ -112,7 +112,7 @@ class Delegation extends BaseModule
// NOTREACHED
}
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
throw new ForbiddenException(DI::l10n()->t('Permission denied.'));

View file

@ -38,13 +38,13 @@ use Friendica\Util\Strings;
*/
class Fetch extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (empty($parameters['guid'])) {
if (empty($this->parameters['guid'])) {
throw new HTTPException\NotFoundException();
}
$guid = $parameters['guid'];
$guid = $this->parameters['guid'];
// Fetch the item
$condition = ['origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED], 'guid' => $guid,

View file

@ -22,7 +22,8 @@
namespace Friendica\Module\Diaspora;
use Friendica\BaseModule;
use Friendica\DI;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n;
use Friendica\Model\User;
use Friendica\Network\HTTPException;
use Friendica\Protocol\Diaspora;
@ -36,25 +37,30 @@ use Psr\Log\LoggerInterface;
class Receive extends BaseModule
{
/** @var LoggerInterface */
private static $logger;
protected $logger;
/** @var IManageConfigValues */
protected $config;
public static function init(array $parameters = [])
public function __construct(LoggerInterface $logger, IManageConfigValues $config, L10n $l10n, array $parameters = [])
{
self::$logger = DI::logger();
parent::__construct($l10n, $parameters);
$this->logger = $logger;
$this->config = $config;
}
public static function post(array $parameters = [])
public function post()
{
$enabled = DI::config()->get('system', 'diaspora_enabled', false);
$enabled = $this->config->get('system', 'diaspora_enabled', false);
if (!$enabled) {
self::$logger->info('Diaspora disabled.');
throw new HTTPException\ForbiddenException(DI::l10n()->t('Access denied.'));
$this->logger->info('Diaspora disabled.');
throw new HTTPException\ForbiddenException($this->t('Access denied.'));
}
if ($parameters['type'] === 'public') {
self::receivePublic();
} else if ($parameters['type'] === 'users') {
self::receiveUser($parameters['guid']);
if ($this->parameters['type'] === 'public') {
$this->receivePublic();
} else if ($this->parameters['type'] === 'users') {
$this->receiveUser();
}
}
@ -64,13 +70,13 @@ class Receive extends BaseModule
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function receivePublic()
private function receivePublic()
{
self::$logger->info('Diaspora: Receiving post.');
$this->logger->info('Diaspora: Receiving post.');
$msg = self::decodePost();
$msg = $this->decodePost();
self::$logger->info('Diaspora: Dispatching.');
$this->logger->info('Diaspora: Dispatching.');
Diaspora::dispatchPublic($msg);
}
@ -78,20 +84,18 @@ class Receive extends BaseModule
/**
* Receive a Diaspora posting for a user
*
* @param string $guid The GUID of the importer
*
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function receiveUser(string $guid)
private function receiveUser()
{
self::$logger->info('Diaspora: Receiving post.');
$this->logger->info('Diaspora: Receiving post.');
$importer = User::getByGuid($guid);
$importer = User::getByGuid($this->parameters['guid']);
$msg = self::decodePost(false, $importer['prvkey'] ?? '');
$msg = $this->decodePost(false, $importer['prvkey'] ?? '');
self::$logger->info('Diaspora: Dispatching.');
$this->logger->info('Diaspora: Dispatching.');
if (Diaspora::dispatch($importer, $msg)) {
throw new HTTPException\OKException();
@ -112,7 +116,7 @@ class Receive extends BaseModule
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function decodePost(bool $public = true, string $privKey = '')
private function decodePost(bool $public = true, string $privKey = '')
{
if (empty($_POST['xml'])) {
@ -122,24 +126,24 @@ class Receive extends BaseModule
throw new HTTPException\InternalServerErrorException('Missing postdata.');
}
self::$logger->info('Diaspora: Message is in the new format.');
$this->logger->info('Diaspora: Message is in the new format.');
$msg = Diaspora::decodeRaw($postdata, $privKey);
} else {
$xml = urldecode($_POST['xml']);
self::$logger->info('Diaspora: Decode message in the old format.');
$this->logger->info('Diaspora: Decode message in the old format.');
$msg = Diaspora::decode($xml, $privKey);
if ($public && !$msg) {
self::$logger->info('Diaspora: Decode message in the new format.');
$this->logger->info('Diaspora: Decode message in the new format.');
$msg = Diaspora::decodeRaw($xml, $privKey);
}
}
self::$logger->info('Diaspora: Post decoded.');
self::$logger->debug('Diaspora: Decoded message.', ['msg' => $msg]);
$this->logger->info('Diaspora: Post decoded.');
$this->logger->debug('Diaspora: Decoded message.', ['msg' => $msg]);
if (!is_array($msg)) {
throw new HTTPException\InternalServerErrorException('Message is not an array.');

View file

@ -38,7 +38,7 @@ use Friendica\Network\HTTPException;
*/
class Directory extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$app = DI::app();
$config = DI::config();

View file

@ -13,7 +13,7 @@ use Friendica\Util\Temporal;
class Json extends \Friendica\BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (!local_user()) {
throw new HTTPException\UnauthorizedException();

View file

@ -41,7 +41,7 @@ use Friendica\Protocol\Feed as ProtocolFeed;
*/
class Feed extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$a = DI::app();
@ -68,7 +68,7 @@ class Feed extends BaseModule
}
header("Content-type: application/atom+xml; charset=utf-8");
echo ProtocolFeed::atom($parameters['nickname'], $last_update, 10, $type, $nocache, true);
echo ProtocolFeed::atom($this->parameters['nickname'], $last_update, 10, $type, $nocache, true);
exit();
}
}

View file

@ -33,7 +33,7 @@ use Friendica\Util\XML;
*/
class RemoveTag extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
throw new HTTPException\ForbiddenException();
@ -41,7 +41,7 @@ class RemoveTag extends BaseModule
$logger = DI::logger();
$item_id = $parameters['id'] ?? 0;
$item_id = $this->parameters['id'] ?? 0;
$term = XML::unescape(trim($_GET['term'] ?? ''));
$cat = XML::unescape(trim($_GET['cat'] ?? ''));
@ -62,7 +62,7 @@ class RemoveTag extends BaseModule
if ($item_id && strlen($term)) {
$item = Post::selectFirst(['uri-id'], ['id' => $item_id]);
if (!DBA::isResult($item)) {
return;
return '';
}
if (!Post\Category::deleteFileByURIId($item['uri-id'], local_user(), $type, $term)) {
notice(DI::l10n()->t('Item was not removed'));
@ -74,5 +74,7 @@ class RemoveTag extends BaseModule
if ($type == Post\Category::FILE) {
DI::baseUrl()->redirect('filed?file=' . rawurlencode($term));
}
return '';
}
}

View file

@ -21,36 +21,43 @@
namespace Friendica\Module\Filer;
use Friendica\App\BaseURL;
use Friendica\BaseModule;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model;
use Friendica\Network\HTTPException;
use Friendica\Util\XML;
use Psr\Log\LoggerInterface;
/**
* Shows a dialog for adding tags to a file
*/
class SaveTag extends BaseModule
{
public static function init(array $parameters = [])
/** @var LoggerInterface */
protected $logger;
public function __construct(LoggerInterface $logger, BaseURL $baseUrl, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
$this->logger = $logger;
if (!local_user()) {
notice(DI::l10n()->t('You must be logged in to use this module'));
DI::baseUrl()->redirect();
notice($this->t('You must be logged in to use this module'));
$baseUrl->redirect();
}
}
public static function rawContent(array $parameters = [])
public function rawContent()
{
$logger = DI::logger();
$term = XML::unescape(trim($_GET['term'] ?? ''));
$item_id = $parameters['id'] ?? 0;
$item_id = $this->parameters['id'] ?? 0;
$logger->info('filer', ['tag' => $term, 'item' => $item_id]);
$this->logger->info('filer', ['tag' => $term, 'item' => $item_id]);
if ($item_id && strlen($term)) {
$item = Model\Post::selectFirst(['uri-id'], ['id' => $item_id]);
@ -65,8 +72,8 @@ class SaveTag extends BaseModule
$tpl = Renderer::getMarkupTemplate("filer_dialog.tpl");
echo Renderer::replaceMacros($tpl, [
'$field' => ['term', DI::l10n()->t("Save to Folder:"), '', '', $filetags, DI::l10n()->t('- select -')],
'$submit' => DI::l10n()->t('Save'),
'$field' => ['term', $this->t("Save to Folder:"), '', '', $filetags, $this->t('- select -')],
'$submit' => $this->t('Save'),
]);
exit;

View file

@ -10,7 +10,7 @@ use Friendica\Model\Contact;
*/
class FollowConfirm extends BaseModule
{
public static function post(array $parameters = [])
public function post()
{
$uid = local_user();
if (!$uid) {

View file

@ -21,15 +21,16 @@
namespace Friendica\Module;
use Friendica\App\BaseURL;
use Friendica\BaseModule;
use Friendica\Core\L10n;
use Friendica\Core\Protocol;
use Friendica\Core\Renderer;
use Friendica\Core\Worker;
use Friendica\DI;
use Friendica\Database\Database;
use Friendica\Model\Contact as ContactModel;
use Friendica\Network\HTTPException\ForbiddenException;
use Friendica\Network\HTTPException\NotFoundException;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Strings;
use Friendica\Worker\Delivery;
@ -38,20 +39,36 @@ use Friendica\Worker\Delivery;
*/
class FriendSuggest extends BaseModule
{
public static function init(array $parameters = [])
/** @var BaseURL */
protected $baseUrl;
/** @var Database */
protected $dba;
/** @var \Friendica\Contact\FriendSuggest\Repository\FriendSuggest */
protected $friendSuggestRepo;
/** @var \Friendica\Contact\FriendSuggest\Factory\FriendSuggest */
protected $friendSuggestFac;
public function __construct(BaseURL $baseUrl, Database $dba, \Friendica\Contact\FriendSuggest\Repository\FriendSuggest $friendSuggestRepo, \Friendica\Contact\FriendSuggest\Factory\FriendSuggest $friendSuggestFac, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
if (!local_user()) {
throw new ForbiddenException(DI::l10n()->t('Permission denied.'));
throw new ForbiddenException($this->t('Permission denied.'));
}
$this->baseUrl = $baseUrl;
$this->dba = $dba;
$this->friendSuggestRepo = $friendSuggestRepo;
$this->friendSuggestFac = $friendSuggestFac;
}
public static function post(array $parameters = [])
public function post()
{
$cid = intval($parameters['contact']);
$cid = intval($this->parameters['contact']);
// We do query the "uid" as well to ensure that it is our contact
if (!DI::dba()->exists('contact', ['id' => $cid, 'uid' => local_user()])) {
throw new NotFoundException(DI::l10n()->t('Contact not found.'));
if (!$this->dba->exists('contact', ['id' => $cid, 'uid' => local_user()])) {
throw new NotFoundException($this->t('Contact not found.'));
}
$suggest_contact_id = intval($_POST['suggest']);
@ -60,15 +77,15 @@ class FriendSuggest extends BaseModule
}
// We do query the "uid" as well to ensure that it is our contact
$contact = DI::dba()->selectFirst('contact', ['name', 'url', 'request', 'avatar'], ['id' => $suggest_contact_id, 'uid' => local_user()]);
$contact = $this->dba->selectFirst('contact', ['name', 'url', 'request', 'avatar'], ['id' => $suggest_contact_id, 'uid' => local_user()]);
if (empty($contact)) {
notice(DI::l10n()->t('Suggested contact not found.'));
notice($this->t('Suggested contact not found.'));
return;
}
$note = Strings::escapeHtml(trim($_POST['note'] ?? ''));
$suggest = DI::fsuggest()->save(DI::fsuggestFactory()->createNew(
$suggest = $this->friendSuggestRepo->save($this->friendSuggestFac->createNew(
local_user(),
$cid,
$contact['name'],
@ -80,17 +97,17 @@ class FriendSuggest extends BaseModule
Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::SUGGESTION, $suggest->id);
info(DI::l10n()->t('Friend suggestion sent.'));
info($this->t('Friend suggestion sent.'));
}
public static function content(array $parameters = [])
public function content(): string
{
$cid = intval($parameters['contact']);
$cid = intval($this->parameters['contact']);
$contact = DI::dba()->selectFirst('contact', [], ['id' => $cid, 'uid' => local_user()]);
$contact = $this->dba->selectFirst('contact', [], ['id' => $cid, 'uid' => local_user()]);
if (empty($contact)) {
notice(DI::l10n()->t('Contact not found.'));
DI::baseUrl()->redirect();
notice($this->t('Contact not found.'));
$this->baseUrl->redirect();
}
$suggestableContacts = ContactModel::selectToArray(['id', 'name'], [
@ -117,15 +134,15 @@ class FriendSuggest extends BaseModule
$tpl = Renderer::getMarkupTemplate('fsuggest.tpl');
return Renderer::replaceMacros($tpl, [
'$contact_id' => $cid,
'$fsuggest_title' => DI::l10n()->t('Suggest Friends'),
'$fsuggest_title' => $this->t('Suggest Friends'),
'$fsuggest_select' => [
'suggest',
DI::l10n()->t('Suggest a friend for %s', $contact['name']),
$this->t('Suggest a friend for %s', $contact['name']),
'',
'',
$formattedContacts,
],
'$submit' => DI::l10n()->t('Submit'),
'$submit' => $this->t('Submit'),
]);
}
}

View file

@ -38,7 +38,7 @@ use Friendica\Protocol\ActivityPub;
*/
class Friendica extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$config = DI::config();
@ -110,7 +110,7 @@ class Friendica extends BaseModule
]);
}
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (ActivityPub::isRequest()) {
try {

View file

@ -32,7 +32,7 @@ require_once 'boot.php';
class Group extends BaseModule
{
public static function post(array $parameters = [])
public function post()
{
$a = DI::app();
@ -138,7 +138,7 @@ class Group extends BaseModule
}
}
public static function content(array $parameters = [])
public function content(): string
{
$change = false;

View file

@ -34,14 +34,14 @@ use Friendica\Network\HTTPException;
*/
class HCard extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
if ((local_user()) && ($parameters['action'] ?? '') === 'view') {
if ((local_user()) && ($this->parameters['action'] ?? '') === 'view') {
// A logged in user views a profile of a user
$nickname = DI::app()->getLoggedInUserNickname();
} elseif (empty($parameters['action'])) {
} elseif (empty($this->parameters['action'])) {
// Show the profile hCard
$nickname = $parameters['profile'];
$nickname = $this->parameters['profile'];
} else {
throw new HTTPException\NotFoundException(DI::l10n()->t('No profile'));
}

View file

@ -27,7 +27,7 @@ use Friendica\Network\HTTPException;
class MethodNotAllowed extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
throw new HTTPException\MethodNotAllowedException(DI::l10n()->t('Method Not Allowed.'));
}

View file

@ -27,7 +27,7 @@ use Friendica\Network\HTTPException;
class PageNotFound extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
throw new HTTPException\NotFoundException(DI::l10n()->t('Page not found.'));
}

View file

@ -31,7 +31,7 @@ use Friendica\Util\Strings;
*/
class Hashtag extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$result = [];
@ -47,5 +47,7 @@ class Hashtag extends BaseModule
DBA::close($taglist);
System::jsonExit($result);
return '';
}
}

View file

@ -32,16 +32,15 @@ use Friendica\Network\HTTPException;
*/
class Help extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
Nav::setSelected('help');
$text = '';
$filename = '';
$a = DI::app();
$config = DI::config();
$lang = $config->get('system', 'language');
$lang = DI::session()->get('language', $config->get('system', 'language'));
// @TODO: Replace with parameter from router
if (DI::args()->getArgc() > 1) {

View file

@ -32,7 +32,7 @@ use Friendica\Module\Security\Login;
*/
class Home extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$app = DI::app();
$config = DI::config();

View file

@ -25,6 +25,7 @@ use Friendica\App;
use Friendica\BaseModule;
use Friendica\Core;
use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Core\Theme;
use Friendica\DI;
@ -58,110 +59,119 @@ class Install extends BaseModule
/**
* @var int The current step of the wizard
*/
private static $currentWizardStep;
private $currentWizardStep;
/**
* @var Core\Installer The installer
*/
private static $installer;
private $installer;
public static function init(array $parameters = [])
/** @var App */
protected $app;
/** @var App\Mode */
protected $mode;
/** @var App\BaseURL */
protected $baseUrl;
public function __construct(App $app, App\Mode $mode, App\BaseURL $baseUrl, App\Arguments $args, Core\Installer $installer, L10n $l10n, array $parameters = [])
{
$a = DI::app();
parent::__construct($l10n, $parameters);
if (!DI::mode()->isInstall()) {
$this->app = $app;
$this->mode = $mode;
$this->baseUrl = $baseUrl;
$this->installer = $installer;
if (!$this->mode->isInstall()) {
throw new HTTPException\ForbiddenException();
}
// route: install/testrwrite
// $baseurl/install/testrwrite to test if rewrite in .htaccess is working
if (DI::args()->get(1, '') == 'testrewrite') {
if ($args->get(1, '') == 'testrewrite') {
// Status Code 204 means that it worked without content
throw new HTTPException\NoContentException();
}
self::$installer = new Core\Installer();
// get basic installation information and save them to the config cache
$configCache = $a->getConfigCache();
$basePath = new BasePath($a->getBasePath());
self::$installer->setUpCache($configCache, $basePath->getPath());
$configCache = $this->app->getConfigCache();
$basePath = new BasePath($this->app->getBasePath());
$this->installer->setUpCache($configCache, $basePath->getPath());
// We overwrite current theme css, because during install we may not have a working mod_rewrite
// so we may not have a css at all. Here we set a static css file for the install procedure pages
Renderer::$theme['stylesheet'] = DI::baseUrl()->get() . '/view/install/style.css';
Renderer::$theme['stylesheet'] = $this->baseUrl->get() . '/view/install/style.css';
self::$currentWizardStep = ($_POST['pass'] ?? '') ?: self::SYSTEM_CHECK;
$this->currentWizardStep = ($_POST['pass'] ?? '') ?: self::SYSTEM_CHECK;
}
public static function post(array $parameters = [])
public function post()
{
$a = DI::app();
$configCache = $a->getConfigCache();
$configCache = $this->app->getConfigCache();
switch (self::$currentWizardStep) {
switch ($this->currentWizardStep) {
case self::SYSTEM_CHECK:
case self::BASE_CONFIG:
self::checkSetting($configCache, $_POST, 'config', 'php_path');
$this->checkSetting($configCache, $_POST, 'config', 'php_path');
break;
case self::DATABASE_CONFIG:
self::checkSetting($configCache, $_POST, 'config', 'php_path');
$this->checkSetting($configCache, $_POST, 'config', 'php_path');
self::checkSetting($configCache, $_POST, 'config', 'hostname');
self::checkSetting($configCache, $_POST, 'system', 'ssl_policy');
self::checkSetting($configCache, $_POST, 'system', 'basepath');
self::checkSetting($configCache, $_POST, 'system', 'urlpath');
$this->checkSetting($configCache, $_POST, 'config', 'hostname');
$this->checkSetting($configCache, $_POST, 'system', 'ssl_policy');
$this->checkSetting($configCache, $_POST, 'system', 'basepath');
$this->checkSetting($configCache, $_POST, 'system', 'urlpath');
break;
case self::SITE_SETTINGS:
self::checkSetting($configCache, $_POST, 'config', 'php_path');
$this->checkSetting($configCache, $_POST, 'config', 'php_path');
self::checkSetting($configCache, $_POST, 'config', 'hostname');
self::checkSetting($configCache, $_POST, 'system', 'ssl_policy');
self::checkSetting($configCache, $_POST, 'system', 'basepath');
self::checkSetting($configCache, $_POST, 'system', 'urlpath');
$this->checkSetting($configCache, $_POST, 'config', 'hostname');
$this->checkSetting($configCache, $_POST, 'system', 'ssl_policy');
$this->checkSetting($configCache, $_POST, 'system', 'basepath');
$this->checkSetting($configCache, $_POST, 'system', 'urlpath');
self::checkSetting($configCache, $_POST, 'database', 'hostname', Core\Installer::DEFAULT_HOST);
self::checkSetting($configCache, $_POST, 'database', 'username', '');
self::checkSetting($configCache, $_POST, 'database', 'password', '');
self::checkSetting($configCache, $_POST, 'database', 'database', '');
$this->checkSetting($configCache, $_POST, 'database', 'hostname', Core\Installer::DEFAULT_HOST);
$this->checkSetting($configCache, $_POST, 'database', 'username', '');
$this->checkSetting($configCache, $_POST, 'database', 'password', '');
$this->checkSetting($configCache, $_POST, 'database', 'database', '');
// If we cannot connect to the database, return to the previous step
if (!self::$installer->checkDB(DI::dba())) {
self::$currentWizardStep = self::DATABASE_CONFIG;
if (!$this->installer->checkDB(DI::dba())) {
$this->currentWizardStep = self::DATABASE_CONFIG;
}
break;
case self::FINISHED:
self::checkSetting($configCache, $_POST, 'config', 'php_path');
$this->checkSetting($configCache, $_POST, 'config', 'php_path');
self::checkSetting($configCache, $_POST, 'config', 'hostname');
self::checkSetting($configCache, $_POST, 'system', 'ssl_policy');
self::checkSetting($configCache, $_POST, 'system', 'basepath');
self::checkSetting($configCache, $_POST, 'system', 'urlpath');
$this->checkSetting($configCache, $_POST, 'config', 'hostname');
$this->checkSetting($configCache, $_POST, 'system', 'ssl_policy');
$this->checkSetting($configCache, $_POST, 'system', 'basepath');
$this->checkSetting($configCache, $_POST, 'system', 'urlpath');
self::checkSetting($configCache, $_POST, 'database', 'hostname', Core\Installer::DEFAULT_HOST);
self::checkSetting($configCache, $_POST, 'database', 'username', '');
self::checkSetting($configCache, $_POST, 'database', 'password', '');
self::checkSetting($configCache, $_POST, 'database', 'database', '');
$this->checkSetting($configCache, $_POST, 'database', 'hostname', Core\Installer::DEFAULT_HOST);
$this->checkSetting($configCache, $_POST, 'database', 'username', '');
$this->checkSetting($configCache, $_POST, 'database', 'password', '');
$this->checkSetting($configCache, $_POST, 'database', 'database', '');
self::checkSetting($configCache, $_POST, 'system', 'default_timezone', Core\Installer::DEFAULT_TZ);
self::checkSetting($configCache, $_POST, 'system', 'language', Core\Installer::DEFAULT_LANG);
self::checkSetting($configCache, $_POST, 'config', 'admin_email', '');
$this->checkSetting($configCache, $_POST, 'system', 'default_timezone', Core\Installer::DEFAULT_TZ);
$this->checkSetting($configCache, $_POST, 'system', 'language', Core\Installer::DEFAULT_LANG);
$this->checkSetting($configCache, $_POST, 'config', 'admin_email', '');
// If we cannot connect to the database, return to the Database config wizard
if (!self::$installer->checkDB(DI::dba())) {
self::$currentWizardStep = self::DATABASE_CONFIG;
if (!$this->installer->checkDB(DI::dba())) {
$this->currentWizardStep = self::DATABASE_CONFIG;
return;
}
if (!self::$installer->createConfig($configCache)) {
if (!$this->installer->createConfig($configCache)) {
return;
}
self::$installer->installDatabase($configCache->get('system', 'basepath'));
$this->installer->installDatabase($configCache->get('system', 'basepath'));
// install allowed themes to register theme hooks
// this is same as "Reload active theme" in /admin/themes
@ -177,71 +187,70 @@ class Install extends BaseModule
}
}
public static function content(array $parameters = [])
public function content(): string
{
$a = DI::app();
$configCache = $a->getConfigCache();
$configCache = $this->app->getConfigCache();
$output = '';
$install_title = DI::l10n()->t('Friendica Communications Server - Setup');
$install_title = $this->t('Friendica Communications Server - Setup');
switch (self::$currentWizardStep) {
switch ($this->currentWizardStep) {
case self::SYSTEM_CHECK:
$php_path = $configCache->get('config', 'php_path');
$status = self::$installer->checkEnvironment(DI::baseUrl()->get(), $php_path);
$status = $this->installer->checkEnvironment($this->baseUrl->get(), $php_path);
$tpl = Renderer::getMarkupTemplate('install_checks.tpl');
$output .= Renderer::replaceMacros($tpl, [
'$title' => $install_title,
'$pass' => DI::l10n()->t('System check'),
'$required' => DI::l10n()->t('Required'),
'$requirement_not_satisfied' => DI::l10n()->t('Requirement not satisfied'),
'$optional_requirement_not_satisfied' => DI::l10n()->t('Optional requirement not satisfied'),
'$ok' => DI::l10n()->t('OK'),
'$checks' => self::$installer->getChecks(),
'$pass' => $this->t('System check'),
'$required' => $this->t('Required'),
'$requirement_not_satisfied' => $this->t('Requirement not satisfied'),
'$optional_requirement_not_satisfied' => $this->t('Optional requirement not satisfied'),
'$ok' => $this->t('OK'),
'$checks' => $this->installer->getChecks(),
'$passed' => $status,
'$see_install' => DI::l10n()->t('Please see the file "doc/INSTALL.md".'),
'$next' => DI::l10n()->t('Next'),
'$reload' => DI::l10n()->t('Check again'),
'$see_install' => $this->t('Please see the file "doc/INSTALL.md".'),
'$next' => $this->t('Next'),
'$reload' => $this->t('Check again'),
'$php_path' => $php_path,
]);
break;
case self::BASE_CONFIG:
$ssl_choices = [
App\BaseURL::SSL_POLICY_NONE => DI::l10n()->t("No SSL policy, links will track page SSL state"),
App\BaseURL::SSL_POLICY_FULL => DI::l10n()->t("Force all links to use SSL"),
App\BaseURL::SSL_POLICY_SELFSIGN => DI::l10n()->t("Self-signed certificate, use SSL for local links only \x28discouraged\x29")
App\BaseURL::SSL_POLICY_NONE => $this->t("No SSL policy, links will track page SSL state"),
App\BaseURL::SSL_POLICY_FULL => $this->t("Force all links to use SSL"),
App\BaseURL::SSL_POLICY_SELFSIGN => $this->t("Self-signed certificate, use SSL for local links only \x28discouraged\x29")
];
$tpl = Renderer::getMarkupTemplate('install_base.tpl');
$output .= Renderer::replaceMacros($tpl, [
'$title' => $install_title,
'$pass' => DI::l10n()->t('Base settings'),
'$pass' => $this->t('Base settings'),
'$ssl_policy' => ['system-ssl_policy',
DI::l10n()->t("SSL link policy"),
$this->t("SSL link policy"),
$configCache->get('system', 'ssl_policy'),
DI::l10n()->t("Determines whether generated links should be forced to use SSL"),
$this->t("Determines whether generated links should be forced to use SSL"),
$ssl_choices],
'$hostname' => ['config-hostname',
DI::l10n()->t('Host name'),
$this->t('Host name'),
$configCache->get('config', 'hostname'),
DI::l10n()->t('Overwrite this field in case the determinated hostname isn\'t right, otherweise leave it as is.'),
DI::l10n()->t('Required')],
$this->t('Overwrite this field in case the determinated hostname isn\'t right, otherweise leave it as is.'),
$this->t('Required')],
'$basepath' => ['system-basepath',
DI::l10n()->t("Base path to installation"),
$this->t("Base path to installation"),
$configCache->get('system', 'basepath'),
DI::l10n()->t("If the system cannot detect the correct path to your installation, enter the correct path here. This setting should only be set if you are using a restricted system and symbolic links to your webroot."),
DI::l10n()->t('Required')],
$this->t("If the system cannot detect the correct path to your installation, enter the correct path here. This setting should only be set if you are using a restricted system and symbolic links to your webroot."),
$this->t('Required')],
'$urlpath' => ['system-urlpath',
DI::l10n()->t('Sub path of the URL'),
$this->t('Sub path of the URL'),
$configCache->get('system', 'urlpath'),
DI::l10n()->t('Overwrite this field in case the sub path determination isn\'t right, otherwise leave it as is. Leaving this field blank means the installation is at the base URL without sub path.'),
$this->t('Overwrite this field in case the sub path determination isn\'t right, otherwise leave it as is. Leaving this field blank means the installation is at the base URL without sub path.'),
''],
'$php_path' => $configCache->get('config', 'php_path'),
'$submit' => DI::l10n()->t('Submit'),
'$submit' => $this->t('Submit'),
]);
break;
@ -249,54 +258,54 @@ class Install extends BaseModule
$tpl = Renderer::getMarkupTemplate('install_db.tpl');
$output .= Renderer::replaceMacros($tpl, [
'$title' => $install_title,
'$pass' => DI::l10n()->t('Database connection'),
'$info_01' => DI::l10n()->t('In order to install Friendica we need to know how to connect to your database.'),
'$info_02' => DI::l10n()->t('Please contact your hosting provider or site administrator if you have questions about these settings.'),
'$info_03' => DI::l10n()->t('The database you specify below should already exist. If it does not, please create it before continuing.'),
'$required' => DI::l10n()->t('Required'),
'$requirement_not_satisfied' => DI::l10n()->t('Requirement not satisfied'),
'$checks' => self::$installer->getChecks(),
'$pass' => $this->t('Database connection'),
'$info_01' => $this->t('In order to install Friendica we need to know how to connect to your database.'),
'$info_02' => $this->t('Please contact your hosting provider or site administrator if you have questions about these settings.'),
'$info_03' => $this->t('The database you specify below should already exist. If it does not, please create it before continuing.'),
'$required' => $this->t('Required'),
'$requirement_not_satisfied' => $this->t('Requirement not satisfied'),
'$checks' => $this->installer->getChecks(),
'$hostname' => $configCache->get('config', 'hostname'),
'$ssl_policy' => $configCache->get('system', 'ssl_policy'),
'$basepath' => $configCache->get('system', 'basepath'),
'$urlpath' => $configCache->get('system', 'urlpath'),
'$dbhost' => ['database-hostname',
DI::l10n()->t('Database Server Name'),
$this->t('Database Server Name'),
$configCache->get('database', 'hostname'),
'',
DI::l10n()->t('Required')],
$this->t('Required')],
'$dbuser' => ['database-username',
DI::l10n()->t('Database Login Name'),
$this->t('Database Login Name'),
$configCache->get('database', 'username'),
'',
DI::l10n()->t('Required'),
$this->t('Required'),
'autofocus'],
'$dbpass' => ['database-password',
DI::l10n()->t('Database Login Password'),
$this->t('Database Login Password'),
$configCache->get('database', 'password'),
DI::l10n()->t("For security reasons the password must not be empty"),
DI::l10n()->t('Required')],
$this->t("For security reasons the password must not be empty"),
$this->t('Required')],
'$dbdata' => ['database-database',
DI::l10n()->t('Database Name'),
$this->t('Database Name'),
$configCache->get('database', 'database'),
'',
DI::l10n()->t('Required')],
'$lbl_10' => DI::l10n()->t('Please select a default timezone for your website'),
$this->t('Required')],
'$lbl_10' => $this->t('Please select a default timezone for your website'),
'$php_path' => $configCache->get('config', 'php_path'),
'$submit' => DI::l10n()->t('Submit')
'$submit' => $this->t('Submit')
]);
break;
case self::SITE_SETTINGS:
/* Installed langs */
$lang_choices = DI::l10n()->getAvailableLanguages();
$lang_choices = $this->l10n->getAvailableLanguages();
$tpl = Renderer::getMarkupTemplate('install_settings.tpl');
$output .= Renderer::replaceMacros($tpl, [
'$title' => $install_title,
'$required' => DI::l10n()->t('Required'),
'$checks' => self::$installer->getChecks(),
'$pass' => DI::l10n()->t('Site settings'),
'$required' => $this->t('Required'),
'$checks' => $this->installer->getChecks(),
'$pass' => $this->t('Site settings'),
'$hostname' => $configCache->get('config', 'hostname'),
'$ssl_policy' => $configCache->get('system', 'ssl_policy'),
'$basepath' => $configCache->get('system', 'basepath'),
@ -306,41 +315,41 @@ class Install extends BaseModule
'$dbpass' => $configCache->get('database', 'password'),
'$dbdata' => $configCache->get('database', 'database'),
'$adminmail' => ['config-admin_email',
DI::l10n()->t('Site administrator email address'),
$this->t('Site administrator email address'),
$configCache->get('config', 'admin_email'),
DI::l10n()->t('Your account email address must match this in order to use the web admin panel.'),
DI::l10n()->t('Required'), 'autofocus', 'email'],
$this->t('Your account email address must match this in order to use the web admin panel.'),
$this->t('Required'), 'autofocus', 'email'],
'$timezone' => Temporal::getTimezoneField('system-default_timezone',
DI::l10n()->t('Please select a default timezone for your website'),
$this->t('Please select a default timezone for your website'),
$configCache->get('system', 'default_timezone'),
''),
'$language' => ['system-language',
DI::l10n()->t('System Language:'),
$this->t('System Language:'),
$configCache->get('system', 'language'),
DI::l10n()->t('Set the default language for your Friendica installation interface and to send emails.'),
$this->t('Set the default language for your Friendica installation interface and to send emails.'),
$lang_choices],
'$php_path' => $configCache->get('config', 'php_path'),
'$submit' => DI::l10n()->t('Submit')
'$submit' => $this->t('Submit')
]);
break;
case self::FINISHED:
$db_return_text = "";
if (count(self::$installer->getChecks()) == 0) {
if (count($this->installer->getChecks()) == 0) {
$txt = '<p style="font-size: 130%;">';
$txt .= DI::l10n()->t('Your Friendica site database has been installed.') . EOL;
$txt .= $this->t('Your Friendica site database has been installed.') . EOL;
$db_return_text .= $txt;
}
$tpl = Renderer::getMarkupTemplate('install_finished.tpl');
$output .= Renderer::replaceMacros($tpl, [
'$title' => $install_title,
'$required' => DI::l10n()->t('Required'),
'$requirement_not_satisfied' => DI::l10n()->t('Requirement not satisfied'),
'$checks' => self::$installer->getChecks(),
'$pass' => DI::l10n()->t('Installation finished'),
'$text' => $db_return_text . self::whatNext(),
'$required' => $this->t('Required'),
'$requirement_not_satisfied' => $this->t('Requirement not satisfied'),
'$checks' => $this->installer->getChecks(),
'$pass' => $this->t('Installation finished'),
'$text' => $db_return_text . $this->whatNext(),
]);
break;
@ -355,15 +364,15 @@ class Install extends BaseModule
* @return string The text for the next steps
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function whatNext()
private function whatNext()
{
$baseurl = DI::baseUrl()->get();
$baseurl = $this->baseUrl->get();
return
DI::l10n()->t('<h1>What next</h1>')
. "<p>" . DI::l10n()->t('IMPORTANT: You will need to [manually] setup a scheduled task for the worker.')
. DI::l10n()->t('Please see the file "doc/INSTALL.md".')
$this->t('<h1>What next</h1>')
. "<p>" . $this->t('IMPORTANT: You will need to [manually] setup a scheduled task for the worker.')
. $this->t('Please see the file "doc/INSTALL.md".')
. "</p><p>"
. DI::l10n()->t('Go to your new Friendica node <a href="%s/register">registration page</a> and register as new user. Remember to use the same email you have entered as administrator email. This will allow you to enter the site admin panel.', $baseurl)
. $this->t('Go to your new Friendica node <a href="%s/register">registration page</a> and register as new user. Remember to use the same email you have entered as administrator email. This will allow you to enter the site admin panel.', $baseurl)
. "</p>";
}
@ -376,12 +385,21 @@ class Install extends BaseModule
* @param string $key The key of the setting
* @param null|string $default The default value
*/
private static function checkSetting(Cache $configCache, array $post, $cat, $key, $default = null)
private function checkSetting(Cache $configCache, array $post, string $cat, string $key, ?string $default = null)
{
$configCache->set($cat, $key,
trim(($post[sprintf('%s-%s', $cat, $key)] ?? '') ?:
($default ?? $configCache->get($cat, $key))
)
);
$value = null;
if (isset($post[sprintf('%s-%s', $cat, $key)])) {
$value = trim($post[sprintf('%s-%s', $cat, $key)]);
}
if (isset($value)) {
$configCache->set($cat, $key, $value, Cache::SOURCE_ENV);
return;
}
if (isset($default)) {
$configCache->set($cat, $key, $default, Cache::SOURCE_ENV);
}
}
}

View file

@ -35,7 +35,7 @@ use Friendica\Util\Strings;
*/
class Invite extends BaseModule
{
public static function post(array $parameters = [])
public function post()
{
if (!local_user()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
@ -124,7 +124,7 @@ class Invite extends BaseModule
info(DI::l10n()->tt('%d message sent.', '%d messages sent.', $total));
}
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));

View file

@ -38,18 +38,18 @@ use Friendica\Network\HTTPException;
*/
class Activity extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
if (!Session::isAuthenticated()) {
throw new HTTPException\ForbiddenException();
}
if (empty($parameters['id']) || empty($parameters['verb'])) {
if (empty($this->parameters['id']) || empty($this->parameters['verb'])) {
throw new HTTPException\BadRequestException();
}
$verb = $parameters['verb'];
$itemId = $parameters['id'];
$verb = $this->parameters['verb'];
$itemId = $this->parameters['id'];
if (in_array($verb, ['announce', 'unannounce'])) {
$item = Post::selectFirst(['network'], ['id' => $itemId]);

View file

@ -40,7 +40,7 @@ use Friendica\Util\Temporal;
class Compose extends BaseModule
{
public static function post(array $parameters = [])
public function post()
{
if (!empty($_REQUEST['body'])) {
$_REQUEST['return'] = 'network';
@ -51,7 +51,7 @@ class Compose extends BaseModule
}
}
public static function content(array $parameters = [])
public function content(): string
{
if (!local_user()) {
return Login::form('compose', false);
@ -64,7 +64,7 @@ class Compose extends BaseModule
}
/// @TODO Retrieve parameter from router
$posttype = $parameters['type'] ?? Item::PT_ARTICLE;
$posttype = $this->parameters['type'] ?? Item::PT_ARTICLE;
if (!in_array($posttype, [Item::PT_ARTICLE, Item::PT_PERSONAL_NOTE])) {
switch ($posttype) {
case 'note':

View file

@ -34,7 +34,7 @@ use Friendica\Network\HTTPException;
*/
class Follow extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$l10n = DI::l10n();
@ -42,11 +42,11 @@ class Follow extends BaseModule
throw new HttpException\ForbiddenException($l10n->t('Access denied.'));
}
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
throw new HTTPException\BadRequestException();
}
$itemId = intval($parameters['id']);
$itemId = intval($this->parameters['id']);
if (!Item::performActivity($itemId, 'follow', local_user())) {
throw new HTTPException\BadRequestException($l10n->t('Unable to follow this item.'));

View file

@ -33,7 +33,7 @@ use Friendica\Network\HTTPException;
*/
class Ignore extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$l10n = DI::l10n();
@ -41,11 +41,11 @@ class Ignore extends BaseModule
throw new HttpException\ForbiddenException($l10n->t('Access denied.'));
}
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
throw new HTTPException\BadRequestException();
}
$itemId = intval($parameters['id']);
$itemId = intval($this->parameters['id']);
$dba = DI::dba();

View file

@ -34,7 +34,7 @@ use Friendica\Network\HTTPException;
*/
class Pin extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$l10n = DI::l10n();
@ -42,11 +42,11 @@ class Pin extends BaseModule
throw new HttpException\ForbiddenException($l10n->t('Access denied.'));
}
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
throw new HTTPException\BadRequestException();
}
$itemId = intval($parameters['id']);
$itemId = intval($this->parameters['id']);
$item = Post::selectFirst(['uri-id', 'uid'], ['id' => $itemId]);
if (!DBA::isResult($item)) {

View file

@ -35,7 +35,7 @@ use Friendica\Network\HTTPException;
*/
class Star extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$l10n = DI::l10n();
@ -43,11 +43,11 @@ class Star extends BaseModule
throw new HttpException\ForbiddenException($l10n->t('Access denied.'));
}
if (empty($parameters['id'])) {
if (empty($this->parameters['id'])) {
throw new HTTPException\BadRequestException();
}
$itemId = intval($parameters['id']);
$itemId = intval($this->parameters['id']);
$item = Post::selectFirstForUser(local_user(), ['uid', 'uri-id', 'starred'], ['uid' => [0, local_user()], 'id' => $itemId]);

View file

@ -21,16 +21,18 @@
namespace Friendica\Module;
use Friendica\App;
use Friendica\BaseModule;
use Friendica\Core\Logger;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Database\Database;
use Friendica\Model\Contact;
use Friendica\Model\User;
use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Util\HTTPSignature;
use Friendica\Util\Strings;
use Psr\Log\LoggerInterface;
/**
* Magic Auth (remote authentication) module.
@ -39,17 +41,35 @@ use Friendica\Util\Strings;
*/
class Magic extends BaseModule
{
public static function init(array $parameters = [])
{
$a = DI::app();
$ret = ['success' => false, 'url' => '', 'message' => ''];
Logger::info('magic mdule: invoked');
/** @var App */
protected $app;
/** @var LoggerInterface */
protected $logger;
/** @var Database */
protected $dba;
/** @var ICanSendHttpRequests */
protected $httpClient;
protected $baseUrl;
Logger::debug('args', ['request' => $_REQUEST]);
public function __construct(App $app, App\BaseURL $baseUrl, LoggerInterface $logger, Database $dba, ICanSendHttpRequests $httpClient, L10n $l10n, array $parameters = [])
{
parent::__construct($l10n, $parameters);
$this->app = $app;
$this->logger = $logger;
$this->dba = $dba;
$this->httpClient = $httpClient;
$this->baseUrl = $baseUrl;
}
public function rawContent()
{
$this->logger->info('magic module: invoked');
$this->logger->debug('args', ['request' => $_REQUEST]);
$addr = $_REQUEST['addr'] ?? '';
$dest = $_REQUEST['dest'] ?? '';
$test = (!empty($_REQUEST['test']) ? intval($_REQUEST['test']) : 0);
$owa = (!empty($_REQUEST['owa']) ? intval($_REQUEST['owa']) : 0);
$cid = 0;
@ -60,21 +80,15 @@ class Magic extends BaseModule
}
if (!$cid) {
Logger::info('No contact record found', $_REQUEST);
$this->logger->info('No contact record found', $_REQUEST);
// @TODO Finding a more elegant possibility to redirect to either internal or external URL
$a->redirect($dest);
$this->app->redirect($dest);
}
$contact = DBA::selectFirst('contact', ['id', 'nurl', 'url'], ['id' => $cid]);
$contact = $this->dba->selectFirst('contact', ['id', 'nurl', 'url'], ['id' => $cid]);
// Redirect if the contact is already authenticated on this site.
if ($a->getContactId() && strpos($contact['nurl'], Strings::normaliseLink(DI::baseUrl()->get())) !== false) {
if ($test) {
$ret['success'] = true;
$ret['message'] .= 'Local site - you are already authenticated.' . EOL;
return $ret;
}
Logger::info('Contact is already authenticated');
if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl->get())) !== false) {
$this->logger->info('Contact is already authenticated');
System::externalRedirect($dest);
}
@ -98,11 +112,11 @@ class Magic extends BaseModule
$header = HTTPSignature::createSig(
$header,
$user['prvkey'],
'acct:' . $user['nickname'] . '@' . DI::baseUrl()->getHostname() . (DI::baseUrl()->getUrlPath() ? '/' . DI::baseUrl()->getUrlPath() : '')
'acct:' . $user['nickname'] . '@' . $this->baseUrl->getHostname() . ($this->baseUrl->getUrlPath() ? '/' . $this->baseUrl->getUrlPath() : '')
);
// Try to get an authentication token from the other instance.
$curlResult = DI::httpClient()->get($basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
$curlResult = $this->httpClient->get($basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
if ($curlResult->isSuccess()) {
$j = json_decode($curlResult->getBody(), true);
@ -118,19 +132,14 @@ class Magic extends BaseModule
}
$args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
Logger::info('Redirecting', ['path' => $dest . $args]);
$this->logger->info('Redirecting', ['path' => $dest . $args]);
System::externalRedirect($dest . $args);
}
}
System::externalRedirect($dest);
}
if ($test) {
$ret['message'] = 'Not authenticated or invalid arguments' . EOL;
return $ret;
}
// @TODO Finding a more elegant possibility to redirect to either internal or external URL
$a->redirect($dest);
$this->app->redirect($dest);
}
}

View file

@ -34,7 +34,7 @@ use Friendica\Util\Strings;
*/
class Maintenance extends BaseModule
{
public static function content(array $parameters = [])
public function content(): string
{
$reason = DI::config()->get('system', 'maintenance_reason');

View file

@ -27,7 +27,7 @@ use Friendica\DI;
class Manifest extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$config = DI::config();

View file

@ -35,14 +35,14 @@ use Friendica\Model\User;
*/
class NoScrape extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$a = DI::app();
if (isset($parameters['nick'])) {
if (isset($this->parameters['nick'])) {
// Get infos about a specific nick (public)
$which = $parameters['nick'];
} elseif (local_user() && isset($parameters['profile']) && DI::args()->get(2) == 'view') {
$which = $this->parameters['nick'];
} elseif (local_user() && isset($this->parameters['profile']) && DI::args()->get(2) == 'view') {
// view infos about a known profile (needs a login)
$which = $a->getLoggedInUserNickname();
} else {

View file

@ -33,7 +33,7 @@ use Friendica\Model\Nodeinfo;
*/
class NodeInfo110 extends BaseModule
{
public static function rawContent(array $parameters = [])
public function rawContent()
{
$config = DI::config();

Some files were not shown because too many files have changed in this diff Show more