Skip to content

Commit

Permalink
Merge branch 'master' into artist-video
Browse files Browse the repository at this point in the history
  • Loading branch information
notbakaneko authored Nov 30, 2023
2 parents 84ba154 + 1c8aeed commit 7ea09d7
Show file tree
Hide file tree
Showing 110 changed files with 653 additions and 484 deletions.
19 changes: 17 additions & 2 deletions app/Enums/Ruleset.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,31 @@ enum Ruleset: int
case catch = 2;
case mania = 3;

public static function fromName(string $ruleset): self
// for usage with tryFrom when the parameter may be null.
public const NULL = -1;

public static function tryFromName(?string $ruleset): ?self
{
if ($ruleset === null) {
return null;
}

static $lookupMap;
if ($lookupMap === null) {
$lookupMap = [];
foreach (self::cases() as $r) {
$lookupMap[$r->name] = $r;
}
$lookupMap['fruits'] = self::catch;
}

return $lookupMap[$ruleset];
return $lookupMap[$ruleset] ?? null;
}

public function legacyName()
{
return $this === self::catch
? 'fruits'
: $this->name;
}
}
5 changes: 3 additions & 2 deletions app/Http/Controllers/AccountController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

use App\Exceptions\ImageProcessorException;
use App\Exceptions\ModelNotSavedException;
use App\Libraries\User\AvatarHelper;
use App\Libraries\User\CountryChange;
use App\Libraries\User\CountryChangeTarget;
use App\Libraries\UserVerification;
Expand Down Expand Up @@ -73,7 +74,7 @@ public function avatar()
$user = auth()->user();

try {
$user->setAvatar(Request::file('avatar_file'));
AvatarHelper::set($user, Request::file('avatar_file'));
} catch (ImageProcessorException $e) {
return error_popup($e->getMessage());
}
Expand Down Expand Up @@ -308,7 +309,7 @@ public function verify()

public function verifyLink()
{
$state = UserVerificationState::fromVerifyLink(request('key'));
$state = UserVerificationState::fromVerifyLink(get_string(request('key')) ?? '');

if ($state === null) {
UserVerification::logAttempt('link', 'fail', 'incorrect_key');
Expand Down
19 changes: 12 additions & 7 deletions app/Http/Controllers/BeatmapsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace App\Http\Controllers;

use App\Enums\Ruleset;
use App\Exceptions\InvariantException;
use App\Jobs\Notifications\BeatmapOwnerChange;
use App\Libraries\BeatmapDifficultyAttributes;
Expand Down Expand Up @@ -256,20 +257,24 @@ public function show($id)
abort(404);
}

if ($beatmap->mode === 'osu') {
$beatmapRuleset = $beatmap->mode;
if ($beatmapRuleset === 'osu') {
$params = get_params(request()->all(), null, [
'm:int', // legacy parameter
'mode:string',
'mode', // legacy parameter
'ruleset',
], ['null_missing' => true]);

$mode = Beatmap::isModeValid($params['mode'])
? $params['mode']
: Beatmap::modeStr($params['m']);
$ruleset = (
Ruleset::tryFromName($params['ruleset'])
?? Ruleset::tryFromName($params['mode'])
?? Ruleset::tryFrom($params['m'] ?? Ruleset::NULL)
)?->legacyName();
}

$mode ??= $beatmap->mode;
$ruleset ??= $beatmapRuleset;

return ujs_redirect(route('beatmapsets.show', ['beatmapset' => $beatmapset->getKey()]).'#'.$mode.'/'.$beatmap->getKey());
return ujs_redirect(route('beatmapsets.show', ['beatmapset' => $beatmapset->getKey()]).'#'.$ruleset.'/'.$beatmap->getKey());
}

/**
Expand Down
1 change: 1 addition & 0 deletions app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Kernel extends HttpKernel
Middleware\AuthApi::class,
Middleware\SetLocaleApi::class,
Middleware\CheckUserBanStatus::class,
Middleware\UpdateUserLastvisit::class,
],
'web' => [
Middleware\StripCookies::class,
Expand Down
1 change: 1 addition & 0 deletions app/Http/Middleware/AuthApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ private function validTokenFromRequest($psr)
throw new AuthenticationException('invalid token');
}

$token->setRelation('client', $client);
$token->validate();

$user = $token->getResourceOwner();
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Middleware/DatadogMetrics.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ protected static function logDuration(Request $request, Response $response, $sta
$duration = microtime(true) - $startTime;
$tags = [
'action' => 'error_page',
'api' => $request->is('api/*') ? 'true' : 'false',
'api' => is_api_request() ? 'true' : 'false',
'controller' => 'error',
'namespace' => 'error',
'pod_name' => $hostname,
Expand Down
8 changes: 1 addition & 7 deletions app/Http/Middleware/StripCookies.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,7 @@ public function handle($request, Closure $next)

if ($request->attributes->get('strip_cookies')) {
// strip all cookies from response
foreach ($result->headers->getCookies() as $cookie) {
$result->headers->removeCookie(
$cookie->getName(),
$cookie->getPath(),
$cookie->getDomain()
);
}
$result->headers->remove('set-cookie');
}

return $result;
Expand Down
32 changes: 19 additions & 13 deletions app/Http/Middleware/UpdateUserLastvisit.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,30 @@ public function handle($request, Closure $next)
$user = $this->auth->user();

if ($user !== null) {
$isInactive = $user->isInactive();
$token = $user->token();
$shouldUpdate = $token === null || $token->client->password_client;

if ($isInactive) {
$isVerified = $user->isSessionVerified();
}
if ($shouldUpdate) {
$isInactive = $user->isInactive();
if ($isInactive) {
$isVerified = $user->isSessionVerified();
}

if (!$isInactive || $isVerified) {
$recordedLastVisit = $user->getRawAttribute('user_lastvisit');
$currentLastVisit = time();
if (!$isInactive || $isVerified) {
$recordedLastVisit = $user->getRawAttribute('user_lastvisit');
$currentLastVisit = time();

if ($currentLastVisit - $recordedLastVisit > 300) {
$user->update([
'user_lastvisit' => $currentLastVisit,
], ['skipValidations' => true]);
if ($currentLastVisit - $recordedLastVisit > 300) {
$user->update([
'user_lastvisit' => $currentLastVisit,
], ['skipValidations' => true]);
}
}
}

$this->recordSession($request);
if ($token === null) {
$this->recordSession($request);
}
}
}

return $next($request);
Expand Down
16 changes: 3 additions & 13 deletions app/Libraries/BBCodeForDB.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

namespace App\Libraries;

use App\Models\Smiley;
use App\Models\User;

class BBCodeForDB
Expand Down Expand Up @@ -325,22 +324,13 @@ public function parseSize($text)
);
}

// copied from www/forum/includes/message_parser.php#L1196

public function parseSmiley($text)
{
$smilies = Smiley::getAll();

$match = [];
$replace = [];
$replacer = app('smilies')->replacer();

foreach ($smilies as $smiley) {
$match[] = '(?<=^|[\n .])'.preg_quote($smiley['code'], '#').'(?![^<>]*>)';
$replace[] = '<!-- s'.$smiley['code'].' --><img src="{SMILIES_PATH}/'.$smiley['smiley_url'].'" alt="'.$smiley['code'].'" title="'.$smiley['emotion'].'" /><!-- s'.$smiley['code'].' -->';
}
if (count($match)) {
if (count($replacer['patterns']) > 0) {
// Make sure the delimiter # is added in front and at the end of every element within $match
$text = trim(preg_replace(explode(chr(0), '#'.implode('#'.chr(0).'#', $match).'#'), $replace, $text));
$text = trim(preg_replace($replacer['patterns'], $replacer['replacements'], $text));
}

return $text;
Expand Down
23 changes: 23 additions & 0 deletions app/Libraries/Base64Url.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

declare(strict_types=1);

namespace App\Libraries;

class Base64Url
{
public static function decode(string $value): ?string
{
return null_if_false(base64_decode(strtr($value, '-_', '+/'), true));
}

public static function encode(string $value): string
{
// url safe base64
// reference: https://datatracker.ietf.org/doc/html/rfc4648#section-5
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
}
}
39 changes: 39 additions & 0 deletions app/Libraries/SignedRandomString.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

declare(strict_types=1);

namespace App\Libraries;

class SignedRandomString
{
public static function create(int $randomSize): string
{
$key = random_bytes($randomSize);
$hmac = static::hmac($key);

return Base64Url::encode($hmac.$key);
}

public static function isValid(string $input): bool
{
$bin = Base64Url::decode($input);
if ($bin === null) {
return false;
}

// hmac size for sha1 is 20
$hmac = substr($bin, 0, 20);
$key = substr($bin, 20);
$expectedHmac = static::hmac($key);

return hash_equals($expectedHmac, $hmac);
}

private static function hmac(string $key): string
{
return hash_hmac('sha1', $key, \Crypt::getKey(), true);
}
}
43 changes: 43 additions & 0 deletions app/Libraries/Smilies.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

declare(strict_types=1);

namespace App\Libraries;

use App\Models\Smiley;
use App\Traits\Memoizes;

class Smilies
{
use Memoizes;

public function all(): array
{
return $this->memoize(__FUNCTION__, fn () => $this->fetch());
}

public function replacer(): array
{
return $this->memoize(__FUNCTION__, function () {
$smilies = $this->all();

$patterns = [];
$replacements = [];

foreach ($smilies as $smiley) {
$patterns[] = '#(?<=^|[\n .])'.preg_quote($smiley['code'], '#').'(?![^<>]*>)#';
$replacements[] = '<!-- s'.$smiley['code'].' --><img src="{SMILIES_PATH}/'.$smiley['smiley_url'].'" alt="'.$smiley['code'].'" title="'.$smiley['emotion'].'" /><!-- s'.$smiley['code'].' -->';
}

return compact('patterns', 'replacements');
});
}

private function fetch(): array
{
return Smiley::orderBy(\DB::raw('LENGTH(code)'), 'desc')->get()->toArray();
}
}
Loading

0 comments on commit 7ea09d7

Please sign in to comment.