Merge pull request #14559 from Art4/phpstan-level-1

Phpstan level 1
This commit is contained in:
Hypolite Petovan 2024-11-30 21:40:29 -05:00 committed by GitHub
commit e34d38182c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
88 changed files with 618 additions and 482 deletions

View file

@ -49,7 +49,7 @@ class Embed extends BaseAdmin
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($this->appHelper);
theme_admin_post();
}
}

View file

@ -31,7 +31,7 @@ class Markers extends BaseApi
}
}
if (empty($timeline) || empty($last_read_id) || empty($application['id'])) {
if ($timeline === '' || $last_read_id === '' || empty($application['id'])) {
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity());
}

View file

@ -28,12 +28,12 @@ class Show extends ContactEndpoint
$target_cid = BaseApi::getContactIDForSearchterm($this->getRequestValue($request, 'target_screen_name', ''), '', $this->getRequestValue($request, 'target_id', 0), $uid);
$source = Contact::getById($source_cid);
if (empty($source)) {
if ($source === false) {
throw new NotFoundException('Source not found');
}
$target = Contact::getById($target_cid);
if (empty($source)) {
if ($target === false) {
throw new NotFoundException('Target not found');
}

View file

@ -511,7 +511,7 @@ class BaseApi extends BaseModule
/**
* @param int $errorno
* @param Error $error
* @return void
* @return never
* @throws HTTPException\InternalServerErrorException
*/
protected function logAndJsonError(int $errorno, Error $error)

View file

@ -131,7 +131,7 @@ abstract class BaseNotifications extends BaseModule
$notif_tpl = Renderer::getMarkupTemplate('notifications/notifications.tpl');
return Renderer::replaceMacros($notif_tpl, [
'$header' => $header ?? $this->t('Notifications'),
'$header' => $header ?: $this->t('Notifications'),
'$tabs' => $tabs,
'$notifications' => $notifications,
'$noContent' => $noContent,

View file

@ -140,9 +140,9 @@ class API extends BaseModule
$share = intval($request['share'] ?? 0);
$isPreview = intval($request['preview'] ?? 0);
$start = DateTimeFormat::convert($strStartDateTime ?? DBA::NULL_DATETIME, 'UTC', $this->timezone);
$start = DateTimeFormat::convert($strStartDateTime, 'UTC', $this->timezone);
if (!$noFinish) {
$finish = DateTimeFormat::convert($strFinishDateTime ?? DBA::NULL_DATETIME, 'UTC', $this->timezone);
$finish = DateTimeFormat::convert($strFinishDateTime, 'UTC', $this->timezone);
} else {
$finish = DBA::NULL_DATETIME;
}

View file

@ -70,6 +70,8 @@ class Circle extends BaseModule
throw new \Exception(DI::l10n()->t('Permission denied.'), 403);
}
$message = '';
if (isset($this->parameters['command'])) {
$circle_id = $this->parameters['circle'];
$contact_id = $this->parameters['contact'];
@ -169,7 +171,9 @@ class Circle extends BaseModule
]);
}
$nocircle = false;
$nocircle = false;
$members = [];
$preselected = [];
// @TODO: Replace with parameter from router
if ((DI::args()->getArgc() == 2) && (DI::args()->getArgv()[1] === 'none') ||
@ -181,9 +185,6 @@ class Circle extends BaseModule
'name' => DI::l10n()->t('Contacts not in any circle'),
];
$members = [];
$preselected = [];
$context = $context + [
'$title' => $circle['name'],
'$gname' => ['circle_name', DI::l10n()->t('Circle Name: '), $circle['name'], ''],

View file

@ -7,18 +7,19 @@
namespace Friendica\Module\Contact;
use Friendica\App;
use Friendica\App\Arguments;
use Friendica\App\BaseURL;
use Friendica\App\Page;
use Friendica\BaseModule;
use Friendica\Contact\LocalRelationship\Repository\LocalRelationship;
use Friendica\Content\Conversation;
use Friendica\Content\Nav;
use Friendica\Content\Widget;
use Friendica\Content\Widget\VCard;
use Friendica\Core\ACL;
use Friendica\Core\L10n;
use Friendica\Core\Protocol;
use Friendica\Core\Session\Capability\IHandleUserSessions;
use Friendica\Core\Theme;
use Friendica\Model;
use Friendica\Model\Contact as ModelContact;
use Friendica\Module\Contact;
use Friendica\Module\Response;
@ -33,7 +34,7 @@ use Psr\Log\LoggerInterface;
class Conversations extends BaseModule
{
/**
* @var App\Page
* @var Page
*/
private $page;
/**
@ -49,7 +50,7 @@ class Conversations extends BaseModule
*/
private $userSession;
public function __construct(L10n $l10n, LocalRelationship $localRelationship, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, App\Page $page, Conversation $conversation, IHandleUserSessions $userSession, $server, array $parameters = [])
public function __construct(L10n $l10n, LocalRelationship $localRelationship, BaseURL $baseUrl, Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, Page $page, Conversation $conversation, IHandleUserSessions $userSession, $server, array $parameters = [])
{
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
@ -67,12 +68,12 @@ class Conversations extends BaseModule
// Backward compatibility: Ensure to use the public contact when the user contact is provided
// Remove by version 2022.03
$pcid = Model\Contact::getPublicContactId(intval($this->parameters['id']), $this->userSession->getLocalUserId());
$pcid = ModelContact::getPublicContactId(intval($this->parameters['id']), $this->userSession->getLocalUserId());
if (!$pcid) {
throw new NotFoundException($this->t('Contact not found.'));
}
$contact = Model\Contact::getAccountById($pcid);
$contact = ModelContact::getAccountById($pcid);
if (empty($contact)) {
throw new NotFoundException($this->t('Contact not found.'));
}
@ -83,7 +84,7 @@ class Conversations extends BaseModule
}
$localRelationship = $this->localRelationship->getForUserContact($this->userSession->getLocalUserId(), $contact['id']);
if ($localRelationship->rel === Model\Contact::SELF) {
if ($localRelationship->rel === ModelContact::SELF) {
$this->baseUrl->redirect('profile/' . $contact['nick']);
}
@ -93,10 +94,12 @@ class Conversations extends BaseModule
$this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
$this->page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
$this->page['aside'] .= Widget\VCard::getHTML($contact, true);
$this->page['aside'] .= VCard::getHTML($contact, true);
Nav::setSelected('contact');
$output = '';
if (!$contact['ap-posting-restricted']) {
$options = [
'lockstate' => ACL::getLockstateForUserId($this->userSession->getLocalUserId()) ? 'lock' : 'unlock',
@ -104,12 +107,12 @@ class Conversations extends BaseModule
'bang' => '',
'content' => ($contact['contact-type'] == ModelContact::TYPE_COMMUNITY ? '!' : '@') . ($contact['addr'] ?: $contact['url']),
];
$o = $this->conversation->statusEditor($options);
$output = $this->conversation->statusEditor($options);
}
$o .= Contact::getTabsHTML($contact, Contact::TAB_CONVERSATIONS);
$o .= Model\Contact::getThreadsFromId($contact['id'], $this->userSession->getLocalUserId(), 0, 0, $request['last_created'] ?? '');
$output .= Contact::getTabsHTML($contact, Contact::TAB_CONVERSATIONS);
$output .= ModelContact::getThreadsFromId($contact['id'], $this->userSession->getLocalUserId(), 0, 0, $request['last_created'] ?? '');
return $o;
return $output;
}
}

View file

@ -7,7 +7,8 @@
namespace Friendica\Module\Conversation;
use Friendica\App;
use Friendica\App\Arguments;
use Friendica\App\BaseURL;
use Friendica\App\Mode;
use Friendica\BaseModule;
use Friendica\Content\Conversation\Collection\Timelines;
@ -31,6 +32,8 @@ use Friendica\Model\Post;
use Friendica\Model\Post\Engagement;
use Friendica\Model\Post\SearchIndex;
use Friendica\Module\Response;
use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Network\HTTPException\ForbiddenException;
use Friendica\Protocol\Activity;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Profiler;
@ -67,7 +70,7 @@ class Timeline extends BaseModule
/** @var string */
protected $network;
/** @var App\Mode $mode */
/** @var Mode $mode */
protected $mode;
/** @var IHandleUserSessions */
protected $session;
@ -82,7 +85,7 @@ class Timeline extends BaseModule
/** @var UserDefinedChannel */
protected $channelRepository;
public function __construct(UserDefinedChannel $channel, Mode $mode, IHandleUserSessions $session, Database $database, IManagePersonalConfigValues $pConfig, IManageConfigValues $config, ICanCache $cache, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server = [], array $parameters = [])
public function __construct(UserDefinedChannel $channel, Mode $mode, IHandleUserSessions $session, Database $database, IManagePersonalConfigValues $pConfig, IManageConfigValues $config, ICanCache $cache, L10n $l10n, BaseURL $baseUrl, Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server = [], array $parameters = [])
{
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
@ -98,8 +101,8 @@ class Timeline extends BaseModule
/**
* Computes module parameters from the request and local configuration
*
* @throws HTTPException\BadRequestException
* @throws HTTPException\ForbiddenException
* @throws BadRequestException
* @throws ForbiddenException
*/
protected function parseRequest(array $request)
{
@ -308,6 +311,8 @@ class Timeline extends BaseModule
{
$table = 'post-engagement';
$condition = [];
if ($this->selectedTab == ChannelEntity::WHATSHOT) {
if (!is_null($this->accountType)) {
$condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $this->accountType];
@ -331,11 +336,11 @@ class Timeline extends BaseModule
"`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND NOT `follows`) AND
(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND NOT `follows` AND `relation-thread-score` > ?) OR
`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `cid` = ? AND `relation-thread-score` > ?) OR
((`comments` >= ? OR `activities` >= ?) AND
(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `cid` = ? AND `relation-thread-score` > ?)) OR
((`comments` >= ? OR `activities` >= ?) AND
(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `cid` = ? AND `relation-thread-score` > ?)) OR
(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?))))",
$cid, $cid, $this->getMedianRelationThreadScore($cid, 4), $cid, $this->getMedianRelationThreadScore($cid, 4),
$this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid, 0, $cid, 0
$this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid, 0, $cid, 0
];
} elseif ($this->selectedTab == ChannelEntity::FOLLOWERS) {
@ -490,7 +495,7 @@ class Timeline extends BaseModule
$placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
$condition = DBA::mergeConditions($condition, array_merge(["`uri-id` IN (SELECT `uri-id` FROM `post-tag` INNER JOIN `tag` ON `tag`.`id` = `post-tag`.`tid` WHERE `post-tag`.`type` = 1 AND `name` IN (" . $placeholders . "))"], $search));
}
if (!empty($channel->excludeTags)) {
$search = explode(',', mb_strtolower($channel->excludeTags));
$placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
@ -500,7 +505,7 @@ class Timeline extends BaseModule
if (!empty($channel->mediaType)) {
$condition = DBA::mergeConditions($condition, ["`media-type` & ?", $channel->mediaType]);
}
// For "addLanguageCondition" to work, the condition must not be empty
$condition = $this->addLanguageCondition($uid, $condition ?: ["true"], $channel->languages);
}
@ -684,6 +689,7 @@ class Timeline extends BaseModule
protected function getCommunityItems()
{
$items = $this->selectItems();
$key = '';
if ($this->selectedTab == Community::LOCAL) {
$maxpostperauthor = (int)$this->config->get('system', 'max_author_posts_community_page');
@ -692,49 +698,52 @@ class Timeline extends BaseModule
$maxpostperauthor = (int)$this->config->get('system', 'max_server_posts_community_page');
$key = 'author-gsid';
} else {
$maxpostperauthor = 0;
$this->setItemsSeenByCondition([
'unseen' => true,
'uid' => $this->session->getLocalUserId(),
'parent-uri-id' => array_column($items, 'uri-id')
]);
return $items;
}
if ($maxpostperauthor != 0) {
$count = 1;
$author_posts = [];
$selected_items = [];
while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
$maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
$minId = $items[array_key_first($items)]['received'];
$maxId = $items[array_key_last($items)]['received'];
$count = 1;
$author_posts = [];
$selected_items = [];
foreach ($items as $item) {
$author_posts[$item[$key]][$item['uri-id']] = $item['received'];
while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
$maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
$minId = $items[array_key_first($items)]['received'];
$maxId = $items[array_key_last($items)]['received'];
foreach ($items as $item) {
$author_posts[$item[$key]][$item['uri-id']] = $item['received'];
}
foreach ($author_posts as $posts) {
if (count($posts) <= $maxposts) {
continue;
}
foreach ($author_posts as $posts) {
if (count($posts) <= $maxposts) {
continue;
}
asort($posts);
while (count($posts) > $maxposts) {
$uri_id = array_key_first($posts);
unset($posts[$uri_id]);
unset($items[$uri_id]);
}
}
$selected_items = array_merge($selected_items, $items);
// If we're looking at a "previous page", the lookup continues forward in time because the list is
// sorted in chronologically decreasing order
if (!empty($this->minId)) {
$this->minId = $minId;
} else {
// In any other case, the lookup continues backwards in time
$this->maxId = $maxId;
}
if (count($selected_items) < $this->itemsPerPage) {
$items = $this->selectItems();
asort($posts);
while (count($posts) > $maxposts) {
$uri_id = array_key_first($posts);
unset($posts[$uri_id]);
unset($items[$uri_id]);
}
}
} else {
$selected_items = $items;
$selected_items = array_merge($selected_items, $items);
// If we're looking at a "previous page", the lookup continues forward in time because the list is
// sorted in chronologically decreasing order
if (!empty($this->minId)) {
$this->minId = $minId;
} else {
// In any other case, the lookup continues backwards in time
$this->maxId = $maxId;
}
if (count($selected_items) < $this->itemsPerPage) {
$items = $this->selectItems();
}
}
$condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
@ -808,7 +817,7 @@ class Timeline extends BaseModule
}
$uriids = array_keys($items);
foreach (Post\Counts::get(['parent-uri-id' => $uriids, 'verb' => Activity::POST]) as $count) {
$items[$count['parent-uri-id']]['comments'] += $count['count'];
}

View file

@ -37,26 +37,13 @@ class PageNotFound extends BaseModule
public function run(ModuleHTTPException $httpException, array $request = []): ResponseInterface
{
/* The URL provided does not resolve to a valid module.
*
* On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
* We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
* we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
* this will often succeed and eventually do the right thing.
*
* Otherwise we are going to emit a 404 not found.
*/
// The URL provided does not resolve to a valid module.
$queryString = $this->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) {
System::exit();
}
if (!empty($queryString) && ($queryString === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
$this->logger->info('index.php: dreamhost_error_hack invoked.', ['Original URI' => $this->server['REQUEST_URI']]);
$this->baseUrl->redirect($this->server['REQUEST_URI']);
}
$this->logger->debug('index.php: page not found.', [
'request_uri' => $this->server['REQUEST_URI'],
'address' => $this->remoteAddress,

View file

@ -166,12 +166,13 @@ class Display extends BaseModule
*/
protected function displaySidebar(array $item)
{
$author = [];
$shared = $this->contentItem->getSharedPost($item, ['author-link']);
if (!empty($shared) && empty($shared['comment'])) {
if (array_key_exists('comment', $shared) && strval($shared['comment']) === '') {
$author = Contact::getByURLForUser($shared['post']['author-link'], $this->session->getLocalUserId());
}
if (empty($contact)) {
if ($author === []) {
$author = Contact::getById($item['author-id']);
}

View file

@ -65,31 +65,26 @@ class Magic extends BaseModule
$this->logger->debug('Invoked', ['request' => $request]);
$addr = $request['addr'] ?? '';
$bdest = $request['bdest'] ?? '';
$dest = $request['dest'] ?? '';
$rev = intval($request['rev'] ?? 0);
$addr = (string) $request['addr'] ?? '';
$bdest = (string) $request['bdest'] ?? '';
$dest = (string) $request['dest'] ?? '';
$owa = intval($request['owa'] ?? 0);
$delegate = $request['delegate'] ?? '';
// bdest is preferred as it is hex-encoded and can survive url rewrite and argument parsing
if (!empty($bdest)) {
if ($bdest !== '') {
$dest = hex2bin($bdest);
$this->logger->debug('bdest detected', ['dest' => $dest]);
}
$target = $dest ?: $addr;
if ($addr ?: $dest) {
$contact = Contact::getByURL($addr ?: $dest);
$contact = Contact::getByURL($addr ?: $dest);
if ($contact === [] && $owa === 0) {
$this->logger->info('No contact record found, no oWA, redirecting to destination.', ['request' => $request, 'server' => $_SERVER, 'dest' => $dest]);
$this->appHelper->redirect($dest);
}
if (empty($contact)) {
if (!$owa) {
$this->logger->info('No contact record found, no oWA, redirecting to destination.', ['request' => $request, 'server' => $_SERVER, 'dest' => $dest]);
$this->appHelper->redirect($dest);
}
} else {
if ($contact !== []) {
// Redirect if the contact is already authenticated on this site.
if ($this->appHelper->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl)) !== false) {
$this->logger->info('Contact is already authenticated, redirecting to destination.', ['dest' => $dest]);
@ -99,7 +94,7 @@ class Magic extends BaseModule
$this->logger->debug('Contact found', ['url' => $contact['url']]);
}
if (!$this->userSession->getLocalUserId() || !$owa) {
if (!$this->userSession->getLocalUserId() || $owa === 0) {
$this->logger->notice('Not logged in or not OWA, redirecting to destination.', ['uid' => $this->userSession->getLocalUserId(), 'owa' => $owa, 'dest' => $dest]);
$this->appHelper->redirect($dest);
}

View file

@ -48,15 +48,18 @@ class Active extends BaseUsers
{
parent::content();
$action = $this->parameters['action'] ?? '';
$uid = $this->parameters['uid'] ?? 0;
$action = (string) $this->parameters['action'] ?? '';
$uid = (int) $this->parameters['uid'] ?? 0;
if ($uid) {
$user = User::getById($uid, ['username', 'blocked']);
if (!$user) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
if ($uid === 0) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
$user = User::getById($uid, ['username', 'blocked']);
if (!is_array($user)) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
switch ($action) {

View file

@ -48,15 +48,18 @@ class Blocked extends BaseUsers
{
parent::content();
$action = $this->parameters['action'] ?? '';
$uid = $this->parameters['uid'] ?? 0;
$action = (string) $this->parameters['action'] ?? '';
$uid = (int) $this->parameters['uid'] ?? 0;
if ($uid) {
$user = User::getById($uid, ['username', 'blocked']);
if (!$user) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
if ($uid === 0) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
$user = User::getById($uid, ['username', 'blocked']);
if (!is_array($user)) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
switch ($action) {

View file

@ -55,15 +55,18 @@ class Index extends BaseUsers
{
parent::content();
$action = $this->parameters['action'] ?? '';
$uid = $this->parameters['uid'] ?? 0;
$action = (string) $this->parameters['action'] ?? '';
$uid = (int) $this->parameters['uid'] ?? 0;
if ($uid) {
$user = User::getById($uid, ['username', 'blocked']);
if (!$user) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
if ($uid === 0) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
$user = User::getById($uid, ['username', 'blocked']);
if (!is_array($user)) {
$this->systemMessages->addNotice($this->t('User not found'));
$this->baseUrl->redirect('moderation/users');
}
switch ($action) {

View file

@ -66,32 +66,52 @@ class Token extends BaseApi
$this->logAndJsonError(401, $this->errorFactory->Unauthorized('invalid_client', $this->t('Invalid data or unknown client')));
}
if ($request['grant_type'] == 'client_credentials') {
// the "client_credentials" are used as a token for the application itself.
// see https://aaronparecki.com/oauth-2-simplified/#client-credentials
$token = OAuth::createTokenForUser($application, 0, '');
$me = null;
} elseif ($request['grant_type'] == 'authorization_code') {
// For security reasons only allow freshly created tokens
$redirect_uri = strtok($request['redirect_uri'],'?');
$condition = [
"`redirect_uri` LIKE ? AND `id` = ? AND `code` = ? AND `created_at` > ?",
$redirect_uri, $application['id'], $request['code'], DateTimeFormat::utc('now - 5 minutes')
];
$grant_type = (string) $request['grant_type'];
$token = DBA::selectFirst('application-view', ['access_token', 'created_at', 'uid'], $condition);
if (!DBA::isResult($token)) {
$this->logger->notice('Token not found or outdated', $condition);
$this->logAndJsonError(401, $this->errorFactory->Unauthorized());
}
$owner = User::getOwnerDataById($token['uid']);
$me = $owner['url'];
} else {
if (!in_array($grant_type, ['client_credentials', 'authorization_code'])) {
Logger::warning('Unsupported or missing grant type', ['request' => $_REQUEST]);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity($this->t('Unsupported or missing grant type')));
}
$object = new \Friendica\Object\Api\Mastodon\Token($token['access_token'], 'Bearer', $application['scopes'], $token['created_at'], $me);
if ($grant_type === 'client_credentials') {
// the "client_credentials" are used as a token for the application itself.
// see https://aaronparecki.com/oauth-2-simplified/#client-credentials
$token = OAuth::createTokenForUser($application, 0, '');
$object = new \Friendica\Object\Api\Mastodon\Token(
$token['access_token'],
'Bearer',
$application['scopes'],
$token['created_at'],
null
);
$this->jsonExit($object->toArray());
}
// now check for $grant_type === 'authorization_code'
// For security reasons only allow freshly created tokens
$redirect_uri = strtok($request['redirect_uri'],'?');
$condition = [
"`redirect_uri` LIKE ? AND `id` = ? AND `code` = ? AND `created_at` > ?",
$redirect_uri, $application['id'], $request['code'], DateTimeFormat::utc('now - 5 minutes')
];
$token = DBA::selectFirst('application-view', ['access_token', 'created_at', 'uid'], $condition);
if (!DBA::isResult($token)) {
$this->logger->notice('Token not found or outdated', $condition);
$this->logAndJsonError(401, $this->errorFactory->Unauthorized());
}
$owner = User::getOwnerDataById($token['uid']);
$object = new \Friendica\Object\Api\Mastodon\Token(
$token['access_token'],
'Bearer',
$application['scopes'],
$token['created_at'],
$owner['url']
);
$this->jsonExit($object->toArray());
}

View file

@ -142,7 +142,9 @@ class Photo extends BaseApi
$cacheable = ($photo['allow_cid'] . $photo['allow_gid'] . $photo['deny_cid'] . $photo['deny_gid'] === '') && (isset($photo['cacheable']) ? $photo['cacheable'] : true);
$stamp = microtime(true);
$stamp = microtime(true);
$imgdata = '';
$mimetype = false;
if (empty($request['blur']) || empty($photo['blurhash'])) {
$imgdata = MPhoto::getImageDataForPhoto($photo);
@ -150,7 +152,9 @@ class Photo extends BaseApi
}
if (empty($imgdata) && empty($photo['blurhash'])) {
throw new HTTPException\NotFoundException();
} elseif (empty($imgdata) && !empty($photo['blurhash'])) {
}
if (empty($imgdata) && !empty($photo['blurhash'])) {
$image = new Image('', image_type_to_mime_type(IMAGETYPE_WEBP));
$image->getFromBlurHash($photo['blurhash'], $photo['width'], $photo['height']);
$imgdata = $image->asString();
@ -376,6 +380,9 @@ class Photo extends BaseApi
Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
}
}
$url = '';
if (empty($mimetext) && !empty($contact['blurhash'])) {
$image = new Image('', image_type_to_mime_type(IMAGETYPE_WEBP));
$image->getFromBlurHash($contact['blurhash'], $customsize, $customsize);

View file

@ -77,10 +77,11 @@ class Remove extends \Friendica\BaseModule
$tag_text = Tag::getCSVByURIId($item['uri-id']);
$tags = explode(',', $tag_text);
if (empty($tags)) {
if ($tag_text === '') {
$this->baseUrl->redirect($returnUrl);
}
$tags = explode(',', $tag_text);
$tag_checkboxes = array_map(function ($tag_text) {
return ['tag[' . bin2hex($tag_text) . ']', BBCode::toPlaintext($tag_text)];

View file

@ -127,7 +127,11 @@ class Photos extends \Friendica\Module\BaseProfile
$visible = 0;
}
$ret = ['src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''];
$ret = ['src' => '', 'filename' => '', 'filesize' => 0, 'type' => ''];
$src = null;
$filename = '';
$filesize = 0;
$type = '';
Hook::callAll('photo_post_file', $ret);
@ -167,7 +171,11 @@ class Photos extends \Friendica\Module\BaseProfile
$this->systemMessages->addNotice($this->t('Server can\'t accept new file upload at this time, please contact your administrator'));
break;
}
@unlink($src);
if ($src !== null) {
@unlink($src);
}
$foo = 0;
Hook::callAll('photo_post_end', $foo);
return;

View file

@ -96,7 +96,7 @@ class Trust extends BaseModule
// exception wanted!
throw $e;
} catch (\Exception $e) {
$this->logger->warning('Unexpected error during authentication.', ['user' => $this->session->getLocalUserId(), 'exception' => $exception]);
$this->logger->warning('Unexpected error during authentication.', ['user' => $this->session->getLocalUserId(), 'exception' => $e]);
}
}
}

View file

@ -46,9 +46,6 @@ class Crop extends BaseSettings
$base_image = Photo::selectFirst([], ['resource-id' => $resource_id, 'uid' => DI::userSession()->getLocalUserId(), 'scale' => $scale]);
if (DBA::isResult($base_image)) {
$Image = Photo::getImageForPhoto($base_image);
if (empty($Image)) {
throw new HTTPException\InternalServerErrorException();
}
if ($Image->isValid()) {
// If setting for the default profile, unset the profile photo flag from any other photos I own
@ -185,7 +182,7 @@ class Crop extends BaseSettings
}
$Image = Photo::getImageForPhoto($photos[0]);
if (empty($Image)) {
if (!$Image->isValid()) {
throw new HTTPException\InternalServerErrorException();
}

View file

@ -92,8 +92,6 @@ class RemoveMe extends BaseSettings
$this->baseUrl->redirect();
} catch (\RuntimeException $e) {
$this->systemMessages->addNotice($e->getMessage());
} finally {
return;
}
}

View file

@ -64,6 +64,8 @@ class Xrd extends BaseModule
header('Vary: Accept', false);
$alias = '';
if ($name == User::getActorName()) {
$owner = User::getSystemAccount();
if (empty($owner)) {
@ -108,7 +110,7 @@ class Xrd extends BaseModule
$parts[] = current(explode(';', $part));
}
if (empty($parts)) {
if ($parts === []) {
return $default;
} elseif (in_array('application/jrd+json', $parts) && !in_array('application/xrd+xml', $parts)) {
return Response::TYPE_JSON;