Merge branch 'master' into Refactor-PHP-Announnce

This commit is contained in:
HDVinnie
2020-08-17 14:41:42 -04:00
806 changed files with 19157 additions and 9789 deletions

View File

@@ -17,13 +17,14 @@ CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_CONNECTION=session
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=true
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=stealth.tg
MAIL_PORT=587
MAIL_USERNAME=example@stealth.tg

View File

@@ -18,13 +18,14 @@ BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=true
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null

1
.gitignore vendored
View File

@@ -12,6 +12,7 @@
/public/css
/public/js
/public/mix-manifest.json
/public/mix-sri.json
/public/tmp
/public/fonts/bootstrap
/public/fonts/font-awesome

0
.phpstorm.meta.php Executable file → Normal file
View File

View File

@@ -1,8 +1,49 @@
<!-- changelog-linker -->
<!-- dumped content start -->
## [v2.7.0]
## Unreleased
- [#1410] [ImgBot] Optimize images, Thanks to [@imgbot][bot]
- [#1414] (Update) Log Viewer, Thanks to [@HDVinnie]
- [#1412] (Refactor) Code Quality and Style, Thanks to [@HDVinnie]
- [#1409] Apply fixes from StyleCI, Thanks to [@HDVinnie]
<!-- dumped content end -->
<!-- dumped content start -->
## [v2.6.0]
- [#1394] Adds num_file to torrent API response., Thanks to [@PyR8zdl]
- [#1385] fix: Add unique index for group slug, Thanks to [@leighmacdonald]
- [#1403] build(deps-dev): bump lodash from 4.17.15 to 4.17.19, Thanks to [@dependabot][bot]
- [#1392] (Update) index.blade.php, Thanks to [@innocente205]
- [#1387] (Update) Italian Translations, Thanks to [@Gideon75]
- [#1334] Laravel 7.x Shift, Thanks to [@HDVinnie]
- [#1408] Apply fixes from StyleCI, Thanks to [@HDVinnie]
- [#1388] Fix a single translation (pt-br), Thanks to [@StealthC]
- [#1386] Fix 'Expired' lang, Thanks to [@PyR8zdl]
<!-- dumped content end -->
<!-- dumped content start -->
## [v2.5.0]
- [#1365] (Update) Add set freeleech to torrent upload page, Thanks to [@innocente205]
- [#1360] (Refactor) Types System, Thanks to [@HDVinnie]
- [#1354] (Update) Announce Controller, Thanks to [@PyR8zdl]
- [#1356] PHPUnit 9 Shift, Thanks to [@HDVinnie]
- [#1357] (Update) upload.blade.php, Thanks to [@innocente205]
- [#1358] (Update) add_request.blade.php, Thanks to [@innocente205]
- [#1359] (Update) Composer v2 Compatibility, Thanks to [@HDVinnie]
- [#1379] (Feature) Resolutions System, Thanks to [@HDVinnie]
- [#1368] (Enhancement) Upload Parser, Thanks to [@HDVinnie]
- [#1371] (Refactor) Code Quality Changes, Thanks to [@HDVinnie]
- [#1374] (Update) Model Doc Blocks, Thanks to [@HDVinnie]
- [#1376] (Refactor) Count and Sum Queries, Thanks to [@HDVinnie]
- [#1378] Apply fixes from StyleCI, Thanks to [@HDVinnie]
- [#1372] Apply fixes from StyleCI, Thanks to [@HDVinnie]
- [#1375] Apply fixes from StyleCI, Thanks to [@HDVinnie]
<!-- dumped content end -->
@@ -1467,3 +1508,44 @@
[#1350]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1350
[#1346]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1346
[#1345]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1345
[#1379]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1379
[#1378]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1378
[#1376]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1376
[#1375]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1375
[#1374]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1374
[#1372]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1372
[#1371]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1371
[#1368]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1368
[#1365]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1365
[#1360]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1360
[#1359]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1359
[#1358]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1358
[#1357]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1357
[#1356]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1356
[#1354]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1354
[v2.4.0]: https://github.com/HDInnovations/UNIT3D-Community-Edition/compare/v2.3.0...v2.4.0
[v2.5.0]: https://github.com/HDInnovations/UNIT3D-Community-Edition/compare/v2.4.0...v2.5.0
[v2.6.0]: https://github.com/HDInnovations/UNIT3D-Community-Edition/compare/v2.5.0...v2.6.0
[v2.7.0]: https://github.com/HDInnovations/UNIT3D-Community-Edition/compare/v2.6.0...v2.7.0
[#1408]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1408
[#1407]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1407
[#1404]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1404
[#1403]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1403
[#1397]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1397
[#1396]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1396
[#1394]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1394
[#1393]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1393
[#1392]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1392
[#1389]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1389
[#1388]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1388
[#1387]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1387
[#1386]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1386
[#1385]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1385
[#1334]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1334
[@leighmacdonald]: https://github.com/leighmacdonald
[@StealthC]: https://github.com/StealthC
[@Gideon75]: https://github.com/Gideon75
[#1414]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1414
[#1412]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1412
[#1410]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1410
[#1409]: https://github.com/HDInnovations/UNIT3D-Community-Edition/pull/1409

View File

@@ -7,7 +7,7 @@
<hr>
<p align="center">
<a href="http://laravel.com"><img src="https://img.shields.io/badge/Laravel-6-f4645f.svg?style=flat-square" /></a>
<a href="http://laravel.com"><img src="https://img.shields.io/badge/Laravel-7-f4645f.svg?style=flat-square" /></a>
<a href="https://github.com/HDInnovations/UNIT3D/blob/master/LICENSE"><img src="https://img.shields.io/badge/License-AGPL%20v3.0-yellow.svg?style=flat-square" /></a>
<a href="https://travis-ci.org/HDInnovations/UNIT3D-Community-Edition?utm_medium=notification&utm_source=github_status"><img src="https://travis-ci.org/HDInnovations/UNIT3D-Community-Edition.svg?branch=master" /></a>
<a href="https://github.styleci.io/repos/113471037"><img src="https://github.styleci.io/repos/113471037/shield?branch=master" alt="StyleCI"></a>
@@ -96,7 +96,7 @@ Traffic: Unlimited
```
NOTE: If you are running UNIT3D on a non HTTPS instance you MUST change the following configs.
config/session.php <-- HTTPS Only Cookies must be set to false
.env <-- SESSION_SECURE_COOKIE must be set to false
config/secure-headers.php <-- HTTP Strict Transport Security must be set to false
config/secure-headers.php <-- Content Security Policy must be disabled
```
@@ -140,8 +140,11 @@ Here are some packages that are built for UNIT3D.
## <a name="versions"></a> 🚨 Version Support Information
Version | Status | PHP Version Required
:------------|:-------------------------|:------------
2.4.x | Active Support :rocket: | >= 7.4
2.3.x | Active Support :rocket: | >= 7.4
2.7.x | Active Support :rocket: | >= 7.4
2.6.x | Active Support :rocket: | >= 7.4
2.5.x | End Of Life :skull: | >= 7.4
2.4.x | End Of Life :skull: | >= 7.4
2.3.x | End Of Life :skull: | >= 7.4
2.0.0 to 2.2.7| End Of Life :skull: | >= 7.3
1.0 to 1.9.4| End Of Life :skull: | >= 7.1.3
@@ -292,8 +295,10 @@ Thanks goes to these wonderful people who have contributed alot of code:
## <a name="thanks"></a> 🎉 Special Thanks
<a href="https://www.jetbrains.com/store/?fromMenu#edition=personal"><img src="https://i.imgur.com/KgDXZV8.png" width="50px;"></a>
<a href="https://www.themoviedb.org/"><img src="https://www.themoviedb.org/assets/2/v4/logos/208x226-stacked-green-9484383bd9853615c113f020def5cbe27f6d08a84ff834f41371f223ebad4a3c.png" width="50px;"></a>
<a href="https://github.com"><img src="https://i.imgur.com/NVWhzrU.png" width="50px;"></a>
<a href="https://laravel.com"><img src="https://i.postimg.cc/cCDBswfK/1200px-Laravel-svg.png" width="50px;"></a>
<a href="https://www.jetbrains.com/store/?fromMenu#edition=personal"><img src="https://i.imgur.com/KgDXZV8.png" height="50px;"></a>
<a href="https://www.themoviedb.org/"><img src="https://www.themoviedb.org/assets/2/v4/logos/v2/blue_square_2-d537fb228cf3ded904ef09b136fe3fec72548ebc1fea3fbbd1ad9e36364db38b.svg" height="50px;"></a>
<a href="https://github.com"><img src="https://i.imgur.com/NVWhzrU.png" height="50px;"></a>
<a href="https://laravel.com"><img src="https://i.postimg.cc/cCDBswfK/1200px-Laravel-svg.png" height="50px;"></a>
<a href="https://laravel-livewire.com"><img src="https://i.postimg.cc/jjsNyBbh/Livewire.png" height="50px;"></a>
<a href="https://styleci.io"><img src="https://i.postimg.cc/0y4XN4yW/og.png" height="50px;"></a>
<a href="https://travis-ci.org"><img src="https://i.postimg.cc/Wz96HDDW/travis-ci-logo-png-transparent.png" height="50px;"></a>

View File

@@ -47,12 +47,12 @@ class CasinoBot
/**
* NerdBot Constructor.
*
* @param ChatRepository $chat
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
$bot = Bot::where('id', '=', '3')->firstOrFail();
$this->chat = $chat;
$this->chat = $chatRepository;
$this->bot = $bot;
$this->expiresAt = Carbon::now()->addMinutes(60);
$this->current = Carbon::now();
@@ -67,15 +67,15 @@ class CasinoBot
*/
public function replaceVars($output)
{
$output = str_replace('{me}', $this->bot->name, $output);
$output = str_replace('{command}', $this->bot->command, $output);
if (strstr($output, '{bots}')) {
$output = \str_replace('{me}', $this->bot->name, $output);
$output = \str_replace('{command}', $this->bot->command, $output);
if (\strstr($output, '{bots}')) {
$bot_help = '';
$bots = Bot::where('active', '=', 1)->where('id', '!=', $this->bot->id)->orderBy('position', 'asc')->get();
foreach ($bots as $bot) {
$bot_help .= '( ! | / | @)'.$bot->command.' help triggers help file for '.$bot->name."\n";
}
$output = str_replace('{bots}', $bot_help, $output);
$output = \str_replace('{bots}', $bot_help, $output);
}
return $output;
@@ -93,10 +93,10 @@ class CasinoBot
*/
public function putDonate($amount = 0, $note = '')
{
$output = implode(' ', $note);
$v = validator(['bot_id' => $this->bot->id, 'amount'=> $amount, 'note'=> $output], [
$output = \implode(' ', $note);
$v = \validator(['bot_id' => $this->bot->id, 'amount'=> $amount, 'note'=> $output], [
'bot_id' => 'required|exists:bots,id|max:999',
'amount' => sprintf('required|numeric|min:1|max:%s', $this->target->seedbonus),
'amount' => \sprintf('required|numeric|min:1|max:%s', $this->target->seedbonus),
'note' => 'required|string',
]);
if ($v->passes()) {
@@ -107,17 +107,17 @@ class CasinoBot
$this->target->seedbonus -= $value;
$this->target->save();
$transaction = new BotTransaction();
$transaction->type = 'bon';
$transaction->cost = $value;
$transaction->user_id = $this->target->id;
$transaction->bot_id = $this->bot->id;
$transaction->to_bot = 1;
$transaction->comment = $output;
$transaction->save();
$botTransaction = new BotTransaction();
$botTransaction->type = 'bon';
$botTransaction->cost = $value;
$botTransaction->user_id = $this->target->id;
$botTransaction->bot_id = $this->bot->id;
$botTransaction->to_bot = 1;
$botTransaction->comment = $output;
$botTransaction->save();
$donations = BotTransaction::with('user', 'bot')->where('bot_id', '=', $this->bot->id)->where('to_bot', '=', 1)->latest()->limit(10)->get();
cache()->put('casinobot-donations', $donations, $this->expiresAt);
\cache()->put('casinobot-donations', $donations, $this->expiresAt);
return 'Your donation to '.$this->bot->name.' for '.$amount.' BON has been sent!';
}
@@ -136,10 +136,10 @@ class CasinoBot
*/
public function getDonations($duration = 'default')
{
$donations = cache()->get('casinobot-donations');
$donations = \cache()->get('casinobot-donations');
if (! $donations || $donations == null) {
$donations = BotTransaction::with('user', 'bot')->where('bot_id', '=', $this->bot->id)->where('to_bot', '=', 1)->latest()->limit(10)->get();
cache()->put('casinobot-donations', $donations, $this->expiresAt);
\cache()->put('casinobot-donations', $donations, $this->expiresAt);
}
$donation_dump = '';
$i = 1;
@@ -148,7 +148,7 @@ class CasinoBot
$i++;
}
return "The Most Recent Donations To Me Are As Follows:\n\n".trim($donation_dump);
return "The Most Recent Donations To Me Are As Follows:\n\n".\trim($donation_dump);
}
/**
@@ -162,16 +162,18 @@ class CasinoBot
/**
* Process Message.
*
* @param $type
* @param User $target
* @param string $message
* @param int $targeted
* @param $type
* @param \App\Models\User $user
* @param string $message
* @param int $targeted
*
* @throws \Exception
*
* @return bool
*/
public function process($type, User $target, $message = '', $targeted = 0)
public function process($type, User $user, $message = '', $targeted = 0)
{
$this->target = $target;
$this->target = $user;
if ($type == 'message') {
$x = 0;
$y = 1;
@@ -187,23 +189,23 @@ class CasinoBot
} else {
$log = 'All '.$this->bot->name.' commands must be a private message or begin with /'.$this->bot->command.' or !'.$this->bot->command.'. Need help? Type /'.$this->bot->command.' help and you shall be helped.';
}
$command = @explode(' ', $message);
$command = @\explode(' ', $message);
$wildcard = null;
$params = null;
if (array_key_exists($y, $command)) {
if (\array_key_exists($y, $command)) {
$params = $command[$y];
}
if ($params != null) {
$clone = $command;
array_shift($clone);
array_shift($clone);
array_shift($clone);
\array_shift($clone);
\array_shift($clone);
\array_shift($clone);
$wildcard = $clone;
}
if (array_key_exists($x, $command)) {
if (\array_key_exists($x, $command)) {
if ($command[$x] === 'donations') {
$log = $this->getDonations($params);
}
@@ -235,8 +237,8 @@ class CasinoBot
}
if ($type == 'message' || $type == 'private') {
$receiver_dirty = 0;
$receiver_echoes = cache()->get('user-echoes'.$target->id);
if (! $receiver_echoes || ! is_array($receiver_echoes) || count($receiver_echoes) < 1) {
$receiver_echoes = \cache()->get('user-echoes'.$target->id);
if (! $receiver_echoes || ! \is_array($receiver_echoes) || \count($receiver_echoes) < 1) {
$receiver_echoes = UserEcho::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$target->id])->get();
}
$receiver_listening = false;
@@ -255,12 +257,12 @@ class CasinoBot
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$target->id, $receiver_echoes, $expiresAt);
event(new Chatter('echo', $target->id, UserEchoResource::collection($receiver_echoes)));
\cache()->put('user-echoes'.$target->id, $receiver_echoes, $expiresAt);
\event(new Chatter('echo', $target->id, UserEchoResource::collection($receiver_echoes)));
}
$receiver_dirty = 0;
$receiver_audibles = cache()->get('user-audibles'.$target->id);
if (! $receiver_audibles || ! is_array($receiver_audibles) || count($receiver_audibles) < 1) {
$receiver_audibles = \cache()->get('user-audibles'.$target->id);
if (! $receiver_audibles || ! \is_array($receiver_audibles) || \count($receiver_audibles) < 1) {
$receiver_audibles = UserAudible::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$target->id])->get();
}
$receiver_listening = false;
@@ -279,8 +281,8 @@ class CasinoBot
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$target->id, $receiver_audibles, $expiresAt);
event(new Chatter('audible', $target->id, UserAudibleResource::collection($receiver_audibles)));
\cache()->put('user-audibles'.$target->id, $receiver_audibles, $expiresAt);
\event(new Chatter('audible', $target->id, UserAudibleResource::collection($receiver_audibles)));
}
if ($txt != '') {
$room_id = 0;
@@ -288,23 +290,24 @@ class CasinoBot
$message = $this->chat->privateMessage(1, $room_id, $txt, $target->id, $this->bot->id);
}
return response('success');
return \response('success');
}
if ($type == 'echo') {
if ($txt != '') {
$room_id = 0;
$message = $this->chat->botMessage($this->bot->id, $room_id, $txt, $target->id);
}
return response('success');
} elseif ($type == 'public') {
return \response('success');
}
if ($type == 'public') {
if ($txt != '') {
$dumproom = $this->chat->message($target->id, $target->chatroom->id, $message, null, null);
$dumproom = $this->chat->message(1, $target->chatroom->id, $txt, null, $this->bot->id);
}
return response('success');
return \response('success');
}
return true;

View File

@@ -45,17 +45,17 @@ class IRCAnnounceBot
public function __construct()
{
$this->username = config('irc-bot.username');
$this->channels = config('irc-bot.channels');
$this->server = config('irc-bot.server');
$this->port = config('irc-bot.port');
$this->hostname = config('irc-bot.hostname');
$this->nickservpass = config('irc-bot.nickservpass');
$this->joinchannels = config('irc-bot.joinchannels');
$this->socket = fsockopen($this->server, $this->port);
$this->username = \config('irc-bot.username');
$this->channels = \config('irc-bot.channels');
$this->server = \config('irc-bot.server');
$this->port = \config('irc-bot.port');
$this->hostname = \config('irc-bot.hostname');
$this->nickservpass = \config('irc-bot.nickservpass');
$this->joinchannels = \config('irc-bot.joinchannels');
$this->socket = \fsockopen($this->server, $this->port);
$this->send_data(sprintf('NICK %s', $this->username));
$this->send_data(sprintf('USER %s %s %s %s', $this->username, $this->hostname, $this->server, $this->username));
$this->send_data(\sprintf('NICK %s', $this->username));
$this->send_data(\sprintf('USER %s %s %s %s', $this->username, $this->hostname, $this->server, $this->username));
$this->connect();
}
@@ -63,20 +63,20 @@ class IRCAnnounceBot
public function __destruct()
{
if ($this->socket) {
fclose($this->socket);
\fclose($this->socket);
}
}
private function connect()
{
while ($data = fgets($this->socket)) {
flush();
$ex = explode(' ', $data);
while ($data = \fgets($this->socket)) {
\flush();
$ex = \explode(' ', $data);
if ($ex[0] === 'PING') {
$this->send_data('PONG '.$ex[1]);
if ($this->nickservpass) {
$this->send_data(sprintf('NICKSERV IDENTIFY %s', $this->nickservpass));
$this->send_data(\sprintf('NICKSERV IDENTIFY %s', $this->nickservpass));
}
return;
@@ -86,24 +86,24 @@ class IRCAnnounceBot
private function send_data($data)
{
fwrite($this->socket, sprintf('%s
\fwrite($this->socket, \sprintf('%s
', $data));
}
private function say($channel, $string)
{
$this->send_data(sprintf('PRIVMSG %s %s', $channel, $string));
$this->send_data(\sprintf('PRIVMSG %s %s', $channel, $string));
}
private function join($channel)
{
$this->send_data(sprintf('JOIN %s', $channel));
$this->send_data(\sprintf('JOIN %s', $channel));
}
public function message($channel, $message)
{
// Messages an specific IRC Channel
if ($this->joinchannels && preg_match('##(\w*[a-zA-Z_0-9]+\w*)#', $channel)) {
if ($this->joinchannels && \preg_match('##(\w*[a-zA-Z_0-9]+\w*)#', $channel)) {
$this->join($channel);
}
@@ -113,7 +113,7 @@ class IRCAnnounceBot
public function broadcast($message, $channels = null)
{
// Broadcast to all IRC Channels in config
$channels = (is_null($channels)) ? $this->channels : $channels;
$channels = (\is_null($channels)) ? $this->channels : $channels;
foreach ($channels as $channel) {
$this->message($channel, $message);
}

View File

@@ -51,12 +51,12 @@ class NerdBot
/**
* NerdBot Constructor.
*
* @param ChatRepository $chat
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
$bot = Bot::where('id', '=', '2')->firstOrFail();
$this->chat = $chat;
$this->chat = $chatRepository;
$this->bot = $bot;
$this->expiresAt = Carbon::now()->addMinutes(60);
$this->current = Carbon::now();
@@ -71,15 +71,15 @@ class NerdBot
*/
public function replaceVars($output)
{
$output = str_replace('{me}', $this->bot->name, $output);
$output = str_replace('{command}', $this->bot->command, $output);
if (strstr($output, '{bots}')) {
$output = \str_replace('{me}', $this->bot->name, $output);
$output = \str_replace('{command}', $this->bot->command, $output);
if (\strstr($output, '{bots}')) {
$bot_help = '';
$bots = Bot::where('active', '=', 1)->where('id', '!=', $this->bot->id)->orderBy('position', 'asc')->get();
foreach ($bots as $bot) {
$bot_help .= '( ! | / | @)'.$bot->command.' help triggers help file for '.$bot->name."\n";
}
$output = str_replace('{bots}', $bot_help, $output);
$output = \str_replace('{bots}', $bot_help, $output);
}
return $output;
@@ -96,13 +96,13 @@ class NerdBot
*/
public function getBanker($duration = 'default')
{
$banker = cache()->get('nerdbot-banker');
$banker = \cache()->get('nerdbot-banker');
if (! $banker || $banker == null) {
$banker = User::latest('seedbonus')->first();
cache()->put('nerdbot-banker', $banker, $this->expiresAt);
\cache()->put('nerdbot-banker', $banker, $this->expiresAt);
}
return sprintf('Currently [url=/users/%s]%s[/url] Is The Top BON Holder On ', $banker->username, $banker->username).config('other.title').'!';
return \sprintf('Currently [url=/users/%s]%s[/url] Is The Top BON Holder On ', $banker->username, $banker->username).\config('other.title').'!';
}
/**
@@ -116,13 +116,13 @@ class NerdBot
*/
public function getSnatched($duration = 'default')
{
$snatched = cache()->get('nerdbot-snatched');
$snatched = \cache()->get('nerdbot-snatched');
if (! $snatched || $snatched == null) {
$snatched = Torrent::latest('times_completed')->first();
cache()->put('nerdbot-snatched', $snatched, $this->expiresAt);
\cache()->put('nerdbot-snatched', $snatched, $this->expiresAt);
}
return sprintf('Currently [url=/torrents/%s]%s[/url] Is The Most Snatched Torrent On ', $snatched->id, $snatched->name).config('other.title').'!';
return \sprintf('Currently [url=/torrents/%s]%s[/url] Is The Most Snatched Torrent On ', $snatched->id, $snatched->name).\config('other.title').'!';
}
/**
@@ -136,13 +136,13 @@ class NerdBot
*/
public function getLeeched($duration = 'default')
{
$leeched = cache()->get('nerdbot-leeched');
$leeched = \cache()->get('nerdbot-leeched');
if (! $leeched || $leeched == null) {
$leeched = Torrent::latest('leechers')->first();
cache()->put('nerdbot-leeched', $leeched, $this->expiresAt);
\cache()->put('nerdbot-leeched', $leeched, $this->expiresAt);
}
return sprintf('Currently [url=/torrents/%s]%s[/url] Is The Most Leeched Torrent On ', $leeched->id, $leeched->name).config('other.title').'!';
return \sprintf('Currently [url=/torrents/%s]%s[/url] Is The Most Leeched Torrent On ', $leeched->id, $leeched->name).\config('other.title').'!';
}
/**
@@ -156,13 +156,13 @@ class NerdBot
*/
public function getSeeded($duration = 'default')
{
$seeded = cache()->get('nerdbot-seeded');
$seeded = \cache()->get('nerdbot-seeded');
if (! $seeded || $seeded == null) {
$seeded = Torrent::latest('seeders')->first();
cache()->put('nerdbot-seeded', $seeded, $this->expiresAt);
\cache()->put('nerdbot-seeded', $seeded, $this->expiresAt);
}
return sprintf('Currently [url=/torrents/%s]%s[/url] Is The Most Seeded Torrent On ', $seeded->id, $seeded->name).config('other.title').'!';
return \sprintf('Currently [url=/torrents/%s]%s[/url] Is The Most Seeded Torrent On ', $seeded->id, $seeded->name).\config('other.title').'!';
}
/**
@@ -176,13 +176,13 @@ class NerdBot
*/
public function getFreeleech($duration = 'default')
{
$fl = cache()->get('nerdbot-fl');
$fl = \cache()->get('nerdbot-fl');
if (! $fl || $fl == null) {
$fl = Torrent::where('free', '=', 1)->count();
cache()->put('nerdbot-fl', $fl, $this->expiresAt);
\cache()->put('nerdbot-fl', $fl, $this->expiresAt);
}
return sprintf('There Are Currently %s Freeleech Torrents On ', $fl).config('other.title').'!';
return \sprintf('There Are Currently %s Freeleech Torrents On ', $fl).\config('other.title').'!';
}
/**
@@ -196,13 +196,13 @@ class NerdBot
*/
public function getDoubleUpload($duration = 'default')
{
$du = cache()->get('nerdbot-doubleup');
$du = \cache()->get('nerdbot-doubleup');
if (! $du || $du == null) {
$du = Torrent::where('doubleup', '=', 1)->count();
cache()->put('nerdbot-doubleup', $du, $this->expiresAt);
\cache()->put('nerdbot-doubleup', $du, $this->expiresAt);
}
return sprintf('There Are Currently %s Double Upload Torrents On ', $du).config('other.title').'!';
return \sprintf('There Are Currently %s Double Upload Torrents On ', $du).\config('other.title').'!';
}
/**
@@ -216,13 +216,13 @@ class NerdBot
*/
public function getPeers($duration = 'default')
{
$peers = cache()->get('nerdbot-peers');
$peers = \cache()->get('nerdbot-peers');
if (! $peers || $peers == null) {
$peers = Peer::count();
cache()->put('nerdbot-peers', $peers, $this->expiresAt);
\cache()->put('nerdbot-peers', $peers, $this->expiresAt);
}
return sprintf('Currently There Are %s Peers On ', $peers).config('other.title').'!';
return \sprintf('Currently There Are %s Peers On ', $peers).\config('other.title').'!';
}
/**
@@ -236,13 +236,13 @@ class NerdBot
*/
public function getBans($duration = 'default')
{
$bans = cache()->get('nerdbot-bans');
$bans = \cache()->get('nerdbot-bans');
if (! $bans || $bans == null) {
$bans = Ban::whereNull('unban_reason')->whereNull('removed_at')->where('created_at', '>', $this->current->subDay())->count();
cache()->put('nerdbot-bans', $bans, $this->expiresAt);
\cache()->put('nerdbot-bans', $bans, $this->expiresAt);
}
return sprintf('In The Last 24 Hours %s Users Have Been Banned From ', $bans).config('other.title').'!';
return \sprintf('In The Last 24 Hours %s Users Have Been Banned From ', $bans).\config('other.title').'!';
}
/**
@@ -256,13 +256,13 @@ class NerdBot
*/
public function getWarnings($duration = 'default')
{
$warnings = cache()->get('nerdbot-warnings');
$warnings = \cache()->get('nerdbot-warnings');
if (! $warnings || $warnings == null) {
$warnings = Warning::where('created_at', '>', $this->current->subDay())->count();
cache()->put('nerdbot-warnings', $warnings, $this->expiresAt);
\cache()->put('nerdbot-warnings', $warnings, $this->expiresAt);
}
return sprintf('In The Last 24 Hours %s Hit and Run Warnings Have Been Issued On ', $warnings).config('other.title').'!';
return \sprintf('In The Last 24 Hours %s Hit and Run Warnings Have Been Issued On ', $warnings).\config('other.title').'!';
}
/**
@@ -276,13 +276,13 @@ class NerdBot
*/
public function getUploads($duration = 'default')
{
$uploads = cache()->get('nerdbot-uploads');
$uploads = \cache()->get('nerdbot-uploads');
if (! $uploads || $uploads == null) {
$uploads = Torrent::where('created_at', '>', $this->current->subDay())->count();
cache()->put('nerdbot-uploads', $uploads, $this->expiresAt);
\cache()->put('nerdbot-uploads', $uploads, $this->expiresAt);
}
return sprintf('In The Last 24 Hours %s Torrents Have Been Uploaded To ', $uploads).config('other.title').'!';
return \sprintf('In The Last 24 Hours %s Torrents Have Been Uploaded To ', $uploads).\config('other.title').'!';
}
/**
@@ -296,13 +296,13 @@ class NerdBot
*/
public function getLogins($duration = 'default')
{
$logins = cache()->get('nerdbot-logins');
$logins = \cache()->get('nerdbot-logins');
if (! $logins || $logins == null) {
$logins = User::whereNotNull('last_login')->where('last_login', '>', $this->current->subDay())->count();
cache()->put('nerdbot-logins', $logins, $this->expiresAt);
\cache()->put('nerdbot-logins', $logins, $this->expiresAt);
}
return sprintf('In The Last 24 Hours %s Unique Users Have Logged Into ', $logins).config('other.title').'!';
return \sprintf('In The Last 24 Hours %s Unique Users Have Logged Into ', $logins).\config('other.title').'!';
}
/**
@@ -316,13 +316,13 @@ class NerdBot
*/
public function getRegistrations($duration = 'default')
{
$registrations = cache()->get('nerdbot-users');
$registrations = \cache()->get('nerdbot-users');
if (! $registrations || $registrations == null) {
$registrations = User::where('created_at', '>', $this->current->subDay())->count();
cache()->put('nerdbot-users', $registrations, $this->expiresAt);
\cache()->put('nerdbot-users', $registrations, $this->expiresAt);
}
return sprintf('In The Last 24 Hours %s Users Have Registered To ', $registrations).config('other.title').'!';
return \sprintf('In The Last 24 Hours %s Users Have Registered To ', $registrations).\config('other.title').'!';
}
/**
@@ -336,10 +336,10 @@ class NerdBot
*/
public function getDonations($duration = 'default')
{
$donations = cache()->get('nerdbot-donations');
$donations = \cache()->get('nerdbot-donations');
if (! $donations || $donations == null) {
$donations = BotTransaction::with('user', 'bot')->where('to_bot', '=', 1)->latest()->limit(10)->get();
cache()->put('nerdbot-donations', $donations, $this->expiresAt);
\cache()->put('nerdbot-donations', $donations, $this->expiresAt);
}
$donation_dump = '';
$i = 1;
@@ -348,7 +348,7 @@ class NerdBot
$i++;
}
return "The Most Recent Donations To All Bots Are As Follows:\n\n".trim($donation_dump);
return "The Most Recent Donations To All Bots Are As Follows:\n\n".\trim($donation_dump);
}
/**
@@ -364,7 +364,7 @@ class NerdBot
*/
public function getKing()
{
return config('other.title').' Is King!';
return \config('other.title').' Is King!';
}
/**
@@ -379,10 +379,10 @@ class NerdBot
*/
public function putDonate($amount = 0, $note = '')
{
$output = implode(' ', $note);
$v = validator(['bot_id' => $this->bot->id, 'amount'=> $amount, 'note'=> $output], [
$output = \implode(' ', $note);
$v = \validator(['bot_id' => $this->bot->id, 'amount'=> $amount, 'note'=> $output], [
'bot_id' => 'required|exists:bots,id|max:999',
'amount' => sprintf('required|numeric|min:1|max:%s', $this->target->seedbonus),
'amount' => \sprintf('required|numeric|min:1|max:%s', $this->target->seedbonus),
'note' => 'required|string',
]);
if ($v->passes()) {
@@ -393,17 +393,17 @@ class NerdBot
$this->target->seedbonus -= $value;
$this->target->save();
$transaction = new BotTransaction();
$transaction->type = 'bon';
$transaction->cost = $value;
$transaction->user_id = $this->target->id;
$transaction->bot_id = $this->bot->id;
$transaction->to_bot = 1;
$transaction->comment = $output;
$transaction->save();
$botTransaction = new BotTransaction();
$botTransaction->type = 'bon';
$botTransaction->cost = $value;
$botTransaction->user_id = $this->target->id;
$botTransaction->bot_id = $this->bot->id;
$botTransaction->to_bot = 1;
$botTransaction->comment = $output;
$botTransaction->save();
$donations = BotTransaction::with('user', 'bot')->where('bot_id', '=', $this->bot->id)->where('to_bot', '=', 1)->latest()->limit(10)->get();
cache()->put('casinobot-donations', $donations, $this->expiresAt);
\cache()->put('casinobot-donations', $donations, $this->expiresAt);
return 'Your donation to '.$this->bot->name.' for '.$amount.' BON has been sent!';
}
@@ -414,16 +414,18 @@ class NerdBot
/**
* Process Message.
*
* @param $type
* @param User $target
* @param string $message
* @param int $targeted
* @param $type
* @param \App\Models\User $user
* @param string $message
* @param int $targeted
*
* @throws \Exception
*
* @return bool
*/
public function process($type, User $target, $message = '', $targeted = 0)
public function process($type, User $user, $message = '', $targeted = 0)
{
$this->target = $target;
$this->target = $user;
if ($type == 'message') {
$x = 0;
$y = 1;
@@ -439,23 +441,23 @@ class NerdBot
} else {
$log = 'All '.$this->bot->name.' commands must be a private message or begin with /'.$this->bot->command.' or !'.$this->bot->command.'. Need help? Type /'.$this->bot->command.' help and you shall be helped.';
}
$command = @explode(' ', $message);
$command = @\explode(' ', $message);
$wildcard = null;
$params = null;
if (array_key_exists($y, $command)) {
if (\array_key_exists($y, $command)) {
$params = $command[$y];
}
if ($params != null) {
$clone = $command;
array_shift($clone);
array_shift($clone);
array_shift($clone);
\array_shift($clone);
\array_shift($clone);
\array_shift($clone);
$wildcard = $clone;
}
if (array_key_exists($x, $command)) {
if (\array_key_exists($x, $command)) {
if ($command[$x] === 'banker') {
$log = $this->getBanker($params);
}
@@ -529,8 +531,8 @@ class NerdBot
}
if ($type == 'message' || $type == 'private') {
$receiver_dirty = 0;
$receiver_echoes = cache()->get('user-echoes'.$target->id);
if (! $receiver_echoes || ! is_array($receiver_echoes) || count($receiver_echoes) < 1) {
$receiver_echoes = \cache()->get('user-echoes'.$target->id);
if (! $receiver_echoes || ! \is_array($receiver_echoes) || \count($receiver_echoes) < 1) {
$receiver_echoes = UserEcho::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$target->id])->get();
}
$receiver_listening = false;
@@ -549,12 +551,12 @@ class NerdBot
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$target->id, $receiver_echoes, $expiresAt);
event(new Chatter('echo', $target->id, UserEchoResource::collection($receiver_echoes)));
\cache()->put('user-echoes'.$target->id, $receiver_echoes, $expiresAt);
\event(new Chatter('echo', $target->id, UserEchoResource::collection($receiver_echoes)));
}
$receiver_dirty = 0;
$receiver_audibles = cache()->get('user-audibles'.$target->id);
if (! $receiver_audibles || ! is_array($receiver_audibles) || count($receiver_audibles) < 1) {
$receiver_audibles = \cache()->get('user-audibles'.$target->id);
if (! $receiver_audibles || ! \is_array($receiver_audibles) || \count($receiver_audibles) < 1) {
$receiver_audibles = UserAudible::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$target->id])->get();
}
$receiver_listening = false;
@@ -573,8 +575,8 @@ class NerdBot
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$target->id, $receiver_audibles, $expiresAt);
event(new Chatter('audible', $target->id, UserAudibleResource::collection($receiver_audibles)));
\cache()->put('user-audibles'.$target->id, $receiver_audibles, $expiresAt);
\event(new Chatter('audible', $target->id, UserAudibleResource::collection($receiver_audibles)));
}
if ($txt != '') {
$room_id = 0;
@@ -582,23 +584,24 @@ class NerdBot
$message = $this->chat->privateMessage(1, $room_id, $txt, $target->id, $this->bot->id);
}
return response('success');
return \response('success');
}
if ($type == 'echo') {
if ($txt != '') {
$room_id = 0;
$message = $this->chat->botMessage($this->bot->id, $room_id, $txt, $target->id);
}
return response('success');
} elseif ($type == 'public') {
return \response('success');
}
if ($type == 'public') {
if ($txt != '') {
$dumproom = $this->chat->message($target->id, $target->chatroom->id, $message, null, null);
$dumproom = $this->chat->message(1, $target->chatroom->id, $txt, null, $this->bot->id);
}
return response('success');
return \response('success');
}
return true;

View File

@@ -44,12 +44,12 @@ class SystemBot
/**
* SystemBot Constructor.
*
* @param ChatRepository $chat
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
$bot = Bot::where('slug', '=', 'systembot')->firstOrFail();
$this->chat = $chat;
$this->chat = $chatRepository;
$this->bot = $bot;
}
@@ -62,15 +62,15 @@ class SystemBot
*/
public function replaceVars($output)
{
$output = str_replace('{me}', $this->bot->name, $output);
$output = str_replace('{command}', $this->bot->command, $output);
if (strstr($output, '{bots}')) {
$output = \str_replace('{me}', $this->bot->name, $output);
$output = \str_replace('{command}', $this->bot->command, $output);
if (\strstr($output, '{bots}')) {
$bot_help = '';
$bots = Bot::where('active', '=', 1)->where('id', '!=', $this->bot->id)->orderBy('position', 'asc')->get();
foreach ($bots as $bot) {
$bot_help .= '( ! | / | @)'.$bot->command.' help triggers help file for '.$bot->name."\n";
}
$output = str_replace('{bots}', $bot_help, $output);
$output = \str_replace('{bots}', $bot_help, $output);
}
return $output;
@@ -95,10 +95,10 @@ class SystemBot
*/
public function putGift($receiver = '', $amount = 0, $note = '')
{
$output = implode(' ', $note);
$v = validator(['receiver' => $receiver, 'amount'=> $amount, 'note'=> $output], [
$output = \implode(' ', $note);
$v = \validator(['receiver' => $receiver, 'amount'=> $amount, 'note'=> $output], [
'receiver' => 'required|string|exists:users,username',
'amount' => sprintf('required|numeric|min:1|max:%s', $this->target->seedbonus),
'amount' => \sprintf('required|numeric|min:1|max:%s', $this->target->seedbonus),
'note' => 'required|string',
]);
if ($v->passes()) {
@@ -115,25 +115,25 @@ class SystemBot
$this->target->seedbonus -= $value;
$this->target->save();
$transaction = new BonTransactions();
$transaction->itemID = 0;
$transaction->name = 'gift';
$transaction->cost = $value;
$transaction->sender = $this->target->id;
$transaction->receiver = $recipient->id;
$transaction->comment = $output;
$transaction->torrent_id = null;
$transaction->save();
$bonTransactions = new BonTransactions();
$bonTransactions->itemID = 0;
$bonTransactions->name = 'gift';
$bonTransactions->cost = $value;
$bonTransactions->sender = $this->target->id;
$bonTransactions->receiver = $recipient->id;
$bonTransactions->comment = $output;
$bonTransactions->torrent_id = null;
$bonTransactions->save();
if ($this->target->id != $recipient->id && $recipient->acceptsNotification($this->target, $recipient, 'bon', 'show_bon_gift')) {
$recipient->notify(new NewBon('gift', $this->target->username, $transaction));
$recipient->notify(new NewBon('gift', $this->target->username, $bonTransactions));
}
$profile_url = href_profile($this->target);
$recipient_url = href_profile($recipient);
$profile_url = \href_profile($this->target);
$recipient_url = \href_profile($recipient);
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has gifted %s BON to [url=%s]%s[/url]', $profile_url, $this->target->username, $value, $recipient_url, $recipient->username)
\sprintf('[url=%s]%s[/url] has gifted %s BON to [url=%s]%s[/url]', $profile_url, $this->target->username, $value, $recipient_url, $recipient->username)
);
return 'Your gift to '.$recipient->username.' for '.$amount.' BON has been sent!';
@@ -145,16 +145,16 @@ class SystemBot
/**
* Process Message.
*
* @param $type
* @param User $target
* @param string $message
* @param int $targeted
* @param $type
* @param \App\Models\User $user
* @param string $message
* @param int $targeted
*
* @return bool
*/
public function process($type, User $target, $message = '', $targeted = 0)
public function process($type, User $user, $message = '', $targeted = 0)
{
$this->target = $target;
$this->target = $user;
$x = $type == 'message' ? 0 : 1;
$y = $x + 1;
@@ -165,14 +165,14 @@ class SystemBot
} else {
$log = 'All '.$this->bot->name.' commands must be a private message or begin with /'.$this->bot->command.' or !'.$this->bot->command.'. Need help? Type /'.$this->bot->command.' help and you shall be helped.';
}
$command = @explode(' ', $message);
if (array_key_exists($x, $command)) {
if ($command[$x] === 'gift' && array_key_exists($y, $command) && array_key_exists($z, $command) && array_key_exists($z + 1, $command)) {
$command = @\explode(' ', $message);
if (\array_key_exists($x, $command)) {
if ($command[$x] === 'gift' && \array_key_exists($y, $command) && \array_key_exists($z, $command) && \array_key_exists($z + 1, $command)) {
$clone = $command;
array_shift($clone);
array_shift($clone);
array_shift($clone);
array_shift($clone);
\array_shift($clone);
\array_shift($clone);
\array_shift($clone);
\array_shift($clone);
$log = $this->putGift($command[$y], $command[$z], $clone);
}
if ($command[$x] === 'help') {
@@ -203,8 +203,8 @@ class SystemBot
}
if ($type == 'message' || $type == 'private') {
$receiver_dirty = 0;
$receiver_echoes = cache()->get('user-echoes'.$target->id);
if (! $receiver_echoes || ! is_array($receiver_echoes) || count($receiver_echoes) < 1) {
$receiver_echoes = \cache()->get('user-echoes'.$target->id);
if (! $receiver_echoes || ! \is_array($receiver_echoes) || \count($receiver_echoes) < 1) {
$receiver_echoes = UserEcho::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$target->id])->get();
}
$receiver_listening = false;
@@ -223,12 +223,12 @@ class SystemBot
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$target->id, $receiver_echoes, $expiresAt);
event(new Chatter('echo', $target->id, UserEchoResource::collection($receiver_echoes)));
\cache()->put('user-echoes'.$target->id, $receiver_echoes, $expiresAt);
\event(new Chatter('echo', $target->id, UserEchoResource::collection($receiver_echoes)));
}
$receiver_dirty = 0;
$receiver_audibles = cache()->get('user-audibles'.$target->id);
if (! $receiver_audibles || ! is_array($receiver_audibles) || count($receiver_audibles) < 1) {
$receiver_audibles = \cache()->get('user-audibles'.$target->id);
if (! $receiver_audibles || ! \is_array($receiver_audibles) || \count($receiver_audibles) < 1) {
$receiver_audibles = UserAudible::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$target->id])->get();
}
$receiver_listening = false;
@@ -247,8 +247,8 @@ class SystemBot
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$target->id, $receiver_audibles, $expiresAt);
event(new Chatter('audible', $target->id, UserAudibleResource::collection($receiver_audibles)));
\cache()->put('user-audibles'.$target->id, $receiver_audibles, $expiresAt);
\event(new Chatter('audible', $target->id, UserAudibleResource::collection($receiver_audibles)));
}
if ($txt != '') {
$room_id = 0;
@@ -256,23 +256,24 @@ class SystemBot
$message = $this->chat->privateMessage(1, $room_id, $txt, $target->id, $this->bot->id);
}
return response('success');
return \response('success');
}
if ($type == 'echo') {
if ($txt != '') {
$room_id = 0;
$message = $this->chat->botMessage($this->bot->id, $room_id, $txt, $target->id);
}
return response('success');
} elseif ($type == 'public') {
return \response('success');
}
if ($type == 'public') {
if ($txt != '') {
$dumproom = $this->chat->message($target->id, $target->chatroom->id, $message, null, null);
$dumproom = $this->chat->message(1, $target->chatroom->id, $txt, null, $this->bot->id);
}
return response('success');
return \response('success');
}
return true;

View File

@@ -21,6 +21,9 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* @see \Tests\Unit\Console\Commands\AutoBanTest
*/
class AutoBan extends Command
{
/**
@@ -46,9 +49,9 @@ class AutoBan extends Command
*/
public function handle()
{
$banned_group = cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$banned_group = \cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$bans = Warning::with('warneduser')->select(DB::raw('user_id, count(*) as value'))->where('active', '=', 1)->groupBy('user_id')->having('value', '>=', config('hitrun.max_warnings'))->get();
$bans = Warning::with('warneduser')->select(DB::raw('user_id, count(*) as value'))->where('active', '=', 1)->groupBy('user_id')->having('value', '>=', \config('hitrun.max_warnings'))->get();
foreach ($bans as $ban) {
if ($ban->warneduser->group_id != $banned_group[0] && ! $ban->warneduser->group->is_immune) {

View File

@@ -21,6 +21,9 @@ use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
/**
* @see \Tests\Todo\Unit\Console\Commands\AutoBanDisposableUsersTest
*/
class AutoBanDisposableUsers extends Command
{
/**
@@ -46,11 +49,11 @@ class AutoBanDisposableUsers extends Command
*/
public function handle()
{
$banned_group = cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$banned_group = \cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
User::where('group_id', '!=', $banned_group[0])->chunkById(100, function ($users) use ($banned_group) {
foreach ($users as $user) {
$v = validator([
$v = \validator([
'email' => $user->email,
], [
'email' => 'required|string|email|max:70|blacklist',
@@ -68,7 +71,7 @@ class AutoBanDisposableUsers extends Command
$user->save();
// Log The Ban To Ban Log
$domain = substr(strrchr($user->email, '@'), 1);
$domain = \substr(\strrchr($user->email, '@'), 1);
$logban = new Ban();
$logban->owned_by = $user->id;
$logban->created_by = 1;

View File

@@ -18,6 +18,9 @@ use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* @see \Tests\Unit\Console\Commands\AutoBonAllocationTest
*/
class AutoBonAllocation extends Command
{
/**
@@ -37,6 +40,8 @@ class AutoBonAllocation extends Command
/**
* Execute the console command.
*
* @param \App\Helpers\ByteUnits $byteUnits
*
* @return mixed
*/
public function handle(ByteUnits $byteUnits)
@@ -159,7 +164,7 @@ class AutoBonAllocation extends Command
$array = [];
foreach ($dying_torrent as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 2;
} else {
$array[$value->user_id] = $value->value * 2;
@@ -167,7 +172,7 @@ class AutoBonAllocation extends Command
}
foreach ($legendary_torrent as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 1.5;
} else {
$array[$value->user_id] = $value->value * 1.5;
@@ -175,7 +180,7 @@ class AutoBonAllocation extends Command
}
foreach ($old_torrent as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 1;
} else {
$array[$value->user_id] = $value->value * 1;
@@ -183,7 +188,7 @@ class AutoBonAllocation extends Command
}
foreach ($huge_torrent as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 0.75;
} else {
$array[$value->user_id] = $value->value * 0.75;
@@ -191,7 +196,7 @@ class AutoBonAllocation extends Command
}
foreach ($large_torrent as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 0.50;
} else {
$array[$value->user_id] = $value->value * 0.50;
@@ -199,7 +204,7 @@ class AutoBonAllocation extends Command
}
foreach ($regular_torrent as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 0.25;
} else {
$array[$value->user_id] = $value->value * 0.25;
@@ -207,7 +212,7 @@ class AutoBonAllocation extends Command
}
foreach ($participaint_seeder as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 0.25;
} else {
$array[$value->user_id] = $value->value * 0.25;
@@ -215,7 +220,7 @@ class AutoBonAllocation extends Command
}
foreach ($teamplayer_seeder as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 0.50;
} else {
$array[$value->user_id] = $value->value * 0.50;
@@ -223,7 +228,7 @@ class AutoBonAllocation extends Command
}
foreach ($commited_seeder as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 0.75;
} else {
$array[$value->user_id] = $value->value * 0.75;
@@ -231,7 +236,7 @@ class AutoBonAllocation extends Command
}
foreach ($mvp_seeder as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 1;
} else {
$array[$value->user_id] = $value->value * 1;
@@ -239,7 +244,7 @@ class AutoBonAllocation extends Command
}
foreach ($legendary_seeder as $key => $value) {
if (array_key_exists($value->user_id, $array)) {
if (\array_key_exists($value->user_id, $array)) {
$array[$value->user_id] += $value->value * 2;
} else {
$array[$value->user_id] = $value->value * 2;

View File

@@ -17,6 +17,9 @@ use App\Models\History;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoCorrectHistoryTest
*/
class AutoCorrectHistory extends Command
{
/**
@@ -52,12 +55,11 @@ class AutoCorrectHistory extends Command
*/
public function handle()
{
$current = new Carbon();
$history = History::select(['id', 'active', 'updated_at'])->where('active', '=', 1)->where('updated_at', '<', $current->copy()->subHours(2)->toDateTimeString())->get();
$carbon = new Carbon();
$history = History::select(['id', 'active', 'updated_at'])->where('active', '=', 1)->where('updated_at', '<', $carbon->copy()->subHours(2)->toDateTimeString())->get();
foreach ($history as $h) {
$h->active = false;
$h->seeder = false;
$h->save();
}
$this->comment('Automated History Record Correction Command Complete');

View File

@@ -18,6 +18,9 @@ use App\Models\Warning;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoDeactivateWarningTest
*/
class AutoDeactivateWarning extends Command
{
/**

View File

@@ -19,6 +19,9 @@ use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoDisableInactiveUsersTest
*/
class AutoDisableInactiveUsers extends Command
{
/**
@@ -44,16 +47,16 @@ class AutoDisableInactiveUsers extends Command
*/
public function handle()
{
if (config('pruning.user_pruning') == true) {
$disabled_group = cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
if (\config('pruning.user_pruning') == true) {
$disabled_group = \cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
$current = Carbon::now();
$matches = User::whereIn('group_id', [config('pruning.group_ids')])->get();
$matches = User::whereIn('group_id', [\config('pruning.group_ids')])->get();
$users = $matches->where('created_at', '<', $current->copy()->subDays(config('pruning.account_age'))->toDateTimeString())
->where('last_login', '<', $current->copy()->subDays(config('pruning.last_login'))->toDateTimeString())
->all();
$users = $matches->where('created_at', '<', $current->copy()->subDays(\config('pruning.account_age'))->toDateTimeString())
->where('last_login', '<', $current->copy()->subDays(\config('pruning.last_login'))->toDateTimeString())
->get();
foreach ($users as $user) {
if ($user->getSeeding() === 0) {
@@ -68,7 +71,7 @@ class AutoDisableInactiveUsers extends Command
$user->save();
// Send Email
dispatch(new SendDisableUserMail($user));
\dispatch(new SendDisableUserMail($user));
}
}
}

View File

@@ -18,6 +18,9 @@ use App\Models\Peer;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoFlushPeersTest
*/
class AutoFlushPeers extends Command
{
/**
@@ -53,8 +56,8 @@ class AutoFlushPeers extends Command
*/
public function handle()
{
$current = new Carbon();
$peers = Peer::select(['id', 'info_hash', 'user_id', 'updated_at'])->where('updated_at', '<', $current->copy()->subHours(2)->toDateTimeString())->get();
$carbon = new Carbon();
$peers = Peer::select(['id', 'info_hash', 'user_id', 'updated_at'])->where('updated_at', '<', $carbon->copy()->subHours(2)->toDateTimeString())->get();
foreach ($peers as $peer) {
$history = History::where('info_hash', '=', $peer->info_hash)->where('user_id', '=', $peer->user_id)->first();

View File

@@ -22,18 +22,21 @@ use App\Models\User;
use App\Repositories\ChatRepository;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoGraveyardTest
*/
class AutoGraveyard extends Command
{
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
parent::__construct();
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
@@ -75,14 +78,14 @@ class AutoGraveyard extends Command
$reward->rewarded = 1;
$reward->save();
$user->fl_tokens += config('graveyard.reward');
$user->fl_tokens += \config('graveyard.reward');
$user->save();
// Auto Shout
$appurl = config('app.url');
$appurl = \config('app.url');
$this->chat->systemMessage(
sprintf('Ladies and Gents, [url=%s/users/%s]%s[/url] has successfully resurrected [url=%s/torrents/%s]%s[/url]. :zombie:', $appurl, $user->username, $user->username, $appurl, $torrent->id, $torrent->name)
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/users/%s]%s[/url] has successfully resurrected [url=%s/torrents/%s]%s[/url]. :zombie:', $appurl, $user->username, $user->username, $appurl, $torrent->id, $torrent->name)
);
// Send Private Message
@@ -90,7 +93,7 @@ class AutoGraveyard extends Command
$pm->sender_id = 1;
$pm->receiver_id = $user->id;
$pm->subject = 'Successful Graveyard Resurrection';
$pm->message = sprintf('You have successfully resurrected [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] :zombie: ! Thank you for bringing a torrent back from the dead! Enjoy the freeleech tokens!
$pm->message = \sprintf('You have successfully resurrected [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] :zombie: ! Thank you for bringing a torrent back from the dead! Enjoy the freeleech tokens!
[color=red][b]THIS IS AN AUTOMATED SYSTEM MESSAGE, PLEASE DO NOT REPLY![/b][/color]';
$pm->save();
}

View File

@@ -20,6 +20,9 @@ use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoGroupTest
*/
class AutoGroup extends Command
{
/**
@@ -56,7 +59,7 @@ class AutoGroup extends Command
// Temp Hard Coding of Group Requirements (Config Files To Come) (Upload in Bytes!) (Seedtime in Seconds!)
// Leech ratio dropped below sites minimum
if ($user->getRatio() < config('other.ratio') && $user->group_id != 15) {
if ($user->getRatio() < \config('other.ratio') && $user->group_id != 15) {
$user->group_id = 15;
$user->can_request = 0;
$user->can_invite = 0;
@@ -64,7 +67,7 @@ class AutoGroup extends Command
$user->save();
}
// User >= 0 and ratio above sites minimum
if ($user->uploaded >= 0 && $user->getRatio() >= config('other.ratio') && $user->group_id != 3) {
if ($user->uploaded >= 0 && $user->getRatio() >= \config('other.ratio') && $user->group_id != 3) {
$user->group_id = 3;
$user->can_request = 1;
$user->can_invite = 1;
@@ -73,37 +76,37 @@ class AutoGroup extends Command
}
// PowerUser >= 1TiB and account 1 month old
if ($user->uploaded >= $byteUnits->bytesFromUnit('1TiB') && $user->getRatio() >= config('other.ratio') && $user->created_at < $current->copy()->subDays(30)->toDateTimeString() && $user->group_id != 11) {
if ($user->uploaded >= $byteUnits->bytesFromUnit('1TiB') && $user->getRatio() >= \config('other.ratio') && $user->created_at < $current->copy()->subDays(30)->toDateTimeString() && $user->group_id != 11) {
$user->group_id = 11;
$user->save();
}
// SuperUser >= 5TiB and account 2 month old
if ($user->uploaded >= $byteUnits->bytesFromUnit('5TiB') && $user->getRatio() >= config('other.ratio') && $user->created_at < $current->copy()->subDays(60)->toDateTimeString() && $user->group_id != 12) {
if ($user->uploaded >= $byteUnits->bytesFromUnit('5TiB') && $user->getRatio() >= \config('other.ratio') && $user->created_at < $current->copy()->subDays(60)->toDateTimeString() && $user->group_id != 12) {
$user->group_id = 12;
$user->save();
}
// ExtremeUser >= 20TiB and account 3 month old
if ($user->uploaded >= $byteUnits->bytesFromUnit('20TiB') && $user->getRatio() >= config('other.ratio') && $user->created_at < $current->copy()->subDays(90)->toDateTimeString() && $user->group_id != 13) {
if ($user->uploaded >= $byteUnits->bytesFromUnit('20TiB') && $user->getRatio() >= \config('other.ratio') && $user->created_at < $current->copy()->subDays(90)->toDateTimeString() && $user->group_id != 13) {
$user->group_id = 13;
$user->save();
}
// InsaneUser >= 50TiB and account 6 month old
if ($user->uploaded >= $byteUnits->bytesFromUnit('50TiB') && $user->getRatio() >= config('other.ratio') && $user->created_at < $current->copy()->subDays(180)->toDateTimeString() && $user->group_id != 14) {
if ($user->uploaded >= $byteUnits->bytesFromUnit('50TiB') && $user->getRatio() >= \config('other.ratio') && $user->created_at < $current->copy()->subDays(180)->toDateTimeString() && $user->group_id != 14) {
$user->group_id = 14;
$user->save();
}
// Seeder Seedsize >= 5TiB and account 1 month old and seedtime average 30 days or better
if ($user->getTotalSeedSize() >= $byteUnits->bytesFromUnit('5TiB') && $user->getRatio() >= config('other.ratio') && round($user->getTotalSeedTime() / max(1, $hiscount)) > 2_592_000 && $user->created_at < $current->copy()->subDays(30)->toDateTimeString() && $user->group_id != 17) {
if ($user->getTotalSeedSize() >= $byteUnits->bytesFromUnit('5TiB') && $user->getRatio() >= \config('other.ratio') && \round($user->getTotalSeedTime() / \max(1, $hiscount)) > 2_592_000 && $user->created_at < $current->copy()->subDays(30)->toDateTimeString() && $user->group_id != 17) {
$user->group_id = 17;
$user->save();
}
// Veteran >= 100TiB and account 1 year old
if ($user->uploaded >= $byteUnits->bytesFromUnit('100TiB') && $user->getRatio() >= config('other.ratio') && $user->created_at < $current->copy()->subDays(365)->toDateTimeString() && $user->group_id != 16) {
if ($user->uploaded >= $byteUnits->bytesFromUnit('100TiB') && $user->getRatio() >= \config('other.ratio') && $user->created_at < $current->copy()->subDays(365)->toDateTimeString() && $user->group_id != 16) {
$user->group_id = 16;
$user->save();
}
// Archivist Seedsize >= 10TiB and account 3 month old and seedtime average 60 days or better
if ($user->getTotalSeedSize() >= $byteUnits->bytesFromUnit('10TiB') && $user->getRatio() >= config('other.ratio') && round($user->getTotalSeedTime() / max(1, $hiscount)) > 2_592_000 * 2 && $user->created_at < $current->copy()->subDays(90)->toDateTimeString() && $user->group_id != 18) {
if ($user->getTotalSeedSize() >= $byteUnits->bytesFromUnit('10TiB') && $user->getRatio() >= \config('other.ratio') && \round($user->getTotalSeedTime() / \max(1, $hiscount)) > 2_592_000 * 2 && $user->created_at < $current->copy()->subDays(90)->toDateTimeString() && $user->group_id != 18) {
$user->group_id = 18;
$user->save();
}

View File

@@ -19,6 +19,9 @@ use App\Models\Torrent;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* @see \Tests\Unit\Console\Commands\AutoHighspeedTagTest
*/
class AutoHighspeedTag extends Command
{
/**
@@ -46,7 +49,7 @@ class AutoHighspeedTag extends Command
$seedbox_users = Seedbox::select(['user_id'])->get()->toArray();
if (is_array($seedbox_users) && count($seedbox_users) > 0) {
if (\is_array($seedbox_users) && \count($seedbox_users) > 0) {
$torid = Peer::select(['torrent_id'])->whereIn('user_id', $seedbox_users)->where('seeder', '=', 1)->get()->toArray();
foreach ($torid as $id) {

View File

@@ -22,18 +22,21 @@ use App\Repositories\ChatRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Todo\Unit\Console\Commands\AutoNerdStatTest
*/
class AutoNerdStat extends Command
{
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
parent::__construct();
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
@@ -59,7 +62,7 @@ class AutoNerdStat extends Command
*/
public function handle()
{
if (config('chat.nerd_bot') == true) {
if (\config('chat.nerd_bot') == true) {
// Current Timestamp
$current = Carbon::now();
@@ -67,83 +70,83 @@ class AutoNerdStat extends Command
$expiresAt = $current->addMinutes(60);
// Site Birthday
$bday = config('other.birthdate');
$bday = \config('other.birthdate');
// Logins Count Last 24hours
$logins = User::whereNotNull('last_login')->where('last_login', '>', $current->subDay())->count();
cache()->put('nerdbot-logins', $logins, $expiresAt);
\cache()->put('nerdbot-logins', $logins, $expiresAt);
// Torrents Uploaded Count Last 24hours
$uploads = Torrent::where('created_at', '>', $current->subDay())->count();
cache()->put('nerdbot-uploads', $uploads, $expiresAt);
\cache()->put('nerdbot-uploads', $uploads, $expiresAt);
// New Users Count Last 24hours
$users = User::where('created_at', '>', $current->subDay())->count();
cache()->put('nerdbot-users', $users, $expiresAt);
\cache()->put('nerdbot-users', $users, $expiresAt);
// Top Banker
$banker = User::latest('seedbonus')->first();
cache()->put('nerdbot-banker', $banker, $expiresAt);
\cache()->put('nerdbot-banker', $banker, $expiresAt);
// Most Snatched Torrent
$snatched = Torrent::latest('times_completed')->first();
cache()->put('nerdbot-snatched', $snatched, $expiresAt);
\cache()->put('nerdbot-snatched', $snatched, $expiresAt);
// Most Seeded Torrent
$seeded = Torrent::latest('seeders')->first();
cache()->put('nerdbot-seeded', $seeded, $expiresAt);
\cache()->put('nerdbot-seeded', $seeded, $expiresAt);
// Most Leeched Torrent
$leeched = Torrent::latest('leechers')->first();
cache()->put('nerdbot-leeched', $leeched, $expiresAt);
\cache()->put('nerdbot-leeched', $leeched, $expiresAt);
// FL Torrents
$fl = Torrent::where('free', '=', 1)->count();
cache()->put('nerdbot-fl', $fl, $expiresAt);
\cache()->put('nerdbot-fl', $fl, $expiresAt);
// DU Torrents
$du = Torrent::where('doubleup', '=', 1)->count();
cache()->put('nerdbot-doubleup', $du, $expiresAt);
\cache()->put('nerdbot-doubleup', $du, $expiresAt);
// Peers Count
$peers = Peer::count();
cache()->put('nerdbot-peers', $peers, $expiresAt);
\cache()->put('nerdbot-peers', $peers, $expiresAt);
// New User Bans Count Last 24hours
$bans = Ban::whereNull('unban_reason')->whereNull('removed_at')->where('created_at', '>', $current->subDay())->count();
cache()->put('nerdbot-bans', $bans, $expiresAt);
\cache()->put('nerdbot-bans', $bans, $expiresAt);
// Hit and Run Warning Issued In Last 24hours
$warnings = Warning::where('created_at', '>', $current->subDay())->count();
cache()->put('nerdbot-warnings', $warnings, $expiresAt);
\cache()->put('nerdbot-warnings', $warnings, $expiresAt);
// URL Helpers
$banker_url = href_profile($banker);
$seeded_url = href_torrent($seeded);
$leeched_url = href_torrent($leeched);
$snatched_url = href_torrent($snatched);
$banker_url = \href_profile($banker);
$seeded_url = \href_torrent($seeded);
$leeched_url = \href_torrent($leeched);
$snatched_url = \href_torrent($snatched);
// Select A Random Nerd Stat
$statArray = [
sprintf('In The Last 24 Hours [color=#93c47d][b]%s[/b][/color] Unique Users Have Logged Into ', $logins).config('other.title').'!',
sprintf('In The Last 24 Hours [color=#93c47d][b]%s[/b][/color] Torrents Have Been Uploaded To ', $uploads).config('other.title').'!',
sprintf('In The Last 24 Hours [color=#93c47d][b]%s[/b][/color] Users Have Registered To ', $users).config('other.title').'!',
sprintf('There Are Currently [color=#93c47d][b]%s[/b][/color] Freeleech Torrents On ', $fl).config('other.title').'!',
sprintf('There Are Currently [color=#93c47d][b]%s[/b][/color] Double Upload Torrents On ', $du).config('other.title').'!',
sprintf('Currently [url=%s]%s[/url] Is The Best Seeded Torrent On ', $seeded_url, $seeded->name).config('other.title').'!',
sprintf('Currently [url=%s]%s[/url] Is The Most Leeched Torrent On ', $leeched_url, $leeched->name).config('other.title').'!',
sprintf('Currently [url=%s]%s[/url] Is The Most Snatched Torrent On ', $snatched_url, $snatched->name).config('other.title').'!',
sprintf('Currently [url=%s]%s[/url] Is The Top BON Holder On ', $banker_url, $banker->username).config('other.title').'!',
sprintf('Currently There Are [color=#93c47d][b]%s[/b][/color] Peers On ', $peers).config('other.title').'!',
sprintf('In The Last 24 Hours [color=#dd7e6b][b]%s[/b][/color] Users Have Been Banned From ', $bans).config('other.title').'!',
sprintf('In The Last 24 Hours [color=#dd7e6b][b]%s[/b][/color] Hit and Run Warnings Have Been Issued On ', $warnings).config('other.title').'!',
config('other.title').sprintf(' Birthday Is [b]%s[/b]!', $bday),
config('other.title').' Is King!',
\sprintf('In The Last 24 Hours [color=#93c47d][b]%s[/b][/color] Unique Users Have Logged Into ', $logins).\config('other.title').'!',
\sprintf('In The Last 24 Hours [color=#93c47d][b]%s[/b][/color] Torrents Have Been Uploaded To ', $uploads).\config('other.title').'!',
\sprintf('In The Last 24 Hours [color=#93c47d][b]%s[/b][/color] Users Have Registered To ', $users).\config('other.title').'!',
\sprintf('There Are Currently [color=#93c47d][b]%s[/b][/color] Freeleech Torrents On ', $fl).\config('other.title').'!',
\sprintf('There Are Currently [color=#93c47d][b]%s[/b][/color] Double Upload Torrents On ', $du).\config('other.title').'!',
\sprintf('Currently [url=%s]%s[/url] Is The Best Seeded Torrent On ', $seeded_url, $seeded->name).\config('other.title').'!',
\sprintf('Currently [url=%s]%s[/url] Is The Most Leeched Torrent On ', $leeched_url, $leeched->name).\config('other.title').'!',
\sprintf('Currently [url=%s]%s[/url] Is The Most Snatched Torrent On ', $snatched_url, $snatched->name).\config('other.title').'!',
\sprintf('Currently [url=%s]%s[/url] Is The Top BON Holder On ', $banker_url, $banker->username).\config('other.title').'!',
\sprintf('Currently There Are [color=#93c47d][b]%s[/b][/color] Peers On ', $peers).\config('other.title').'!',
\sprintf('In The Last 24 Hours [color=#dd7e6b][b]%s[/b][/color] Users Have Been Banned From ', $bans).\config('other.title').'!',
\sprintf('In The Last 24 Hours [color=#dd7e6b][b]%s[/b][/color] Hit and Run Warnings Have Been Issued On ', $warnings).\config('other.title').'!',
\config('other.title').\sprintf(' Birthday Is [b]%s[/b]!', $bday),
\config('other.title').' Is King!',
];
$selected = mt_rand(0, count($statArray) - 1);
$selected = \mt_rand(0, \count($statArray) - 1);
// Auto Shout Nerd Stat
$this->chat->systemMessage($statArray[$selected], 2);
$this->chatRepository->systemMessage($statArray[$selected], 2);
}
$this->comment('Automated Nerd Stat Command Complete');
}

View File

@@ -19,6 +19,9 @@ use App\Models\Warning;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoPreWarningTest
*/
class AutoPreWarning extends Command
{
/**
@@ -44,35 +47,35 @@ class AutoPreWarning extends Command
*/
public function handle()
{
if (config('hitrun.enabled') == true) {
$current = new Carbon();
if (\config('hitrun.enabled') == true) {
$carbon = new Carbon();
$prewarn = History::with(['user', 'torrent'])
->where('prewarn', '=', 0)
->where('hitrun', '=', 0)
->where('immune', '=', 0)
->where('actual_downloaded', '>', 0)
->where('active', '=', 0)
->where('seedtime', '<=', config('hitrun.seedtime'))
->where('updated_at', '<', $current->copy()->subDays(config('hitrun.prewarn'))->toDateTimeString())
->where('seedtime', '<=', \config('hitrun.seedtime'))
->where('updated_at', '<', $carbon->copy()->subDays(\config('hitrun.prewarn'))->toDateTimeString())
->get();
foreach ($prewarn as $pre) {
if (! $pre->user->group->is_immune && $pre->actual_downloaded > ($pre->torrent->size * (config('hitrun.buffer') / 100))) {
if (! $pre->user->group->is_immune && $pre->actual_downloaded > ($pre->torrent->size * (\config('hitrun.buffer') / 100))) {
$exsist = Warning::withTrashed()
->where('torrent', '=', $pre->torrent->id)
->where('user_id', '=', $pre->user->id)
->first();
// Send Pre Warning PM If Actual Warning Doesnt Already Exsist
if ($exsist === null) {
$timeleft = config('hitrun.grace') - config('hitrun.prewarn');
$timeleft = \config('hitrun.grace') - \config('hitrun.prewarn');
// Send Private Message
$pm = new PrivateMessage();
$pm->sender_id = 1;
$pm->receiver_id = $pre->user->id;
$pm->subject = 'Hit and Run Warning Incoming';
$pm->message = 'You have received a automated [b]PRE-WARNING PM[/b] from the system because [b]you have been disconnected for '.config('hitrun.prewarn').sprintf(' days on Torrent %s
and have not yet met the required seedtime rules set by ', $pre->torrent->name).config('other.title').sprintf('. If you fail to seed it within %s day(s) you will receive a automated WARNING which will last ', $timeleft).config('hitrun.expire').' days![/b]
$pm->message = 'You have received a automated [b]PRE-WARNING PM[/b] from the system because [b]you have been disconnected for '.\config('hitrun.prewarn').\sprintf(' days on Torrent %s
and have not yet met the required seedtime rules set by ', $pre->torrent->name).\config('other.title').\sprintf('. If you fail to seed it within %s day(s) you will receive a automated WARNING which will last ', $timeleft).\config('hitrun.expire').' days![/b]
[color=red][b] THIS IS AN AUTOMATED SYSTEM MESSAGE, PLEASE DO NOT REPLY![/b][/color]';
$pm->save();

View File

@@ -17,6 +17,9 @@ use App\Models\Audit;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoRecycleAuditsTest
*/
class AutoRecycleAudits extends Command
{
/**
@@ -41,7 +44,7 @@ class AutoRecycleAudits extends Command
public function handle()
{
$current = Carbon::now();
$audits = Audit::where('created_at', '<', $current->copy()->subDays(config('audit.recycle'))->toDateTimeString())->get();
$audits = Audit::where('created_at', '<', $current->copy()->subDays(\config('audit.recycle'))->toDateTimeString())->get();
foreach ($audits as $audit) {
$audit->delete();

View File

@@ -19,6 +19,9 @@ use App\Repositories\ChatRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoRecycleClaimedTorrentRequestsTest
*/
class AutoRecycleClaimedTorrentRequests extends Command
{
/**
@@ -38,18 +41,20 @@ class AutoRecycleClaimedTorrentRequests extends Command
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
parent::__construct();
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
* Execute the console command.
*
* @throws \Exception
*
* @return mixed
*/
public function handle()
@@ -66,9 +71,9 @@ class AutoRecycleClaimedTorrentRequests extends Command
->where('created_at', '<', $current->copy()->subDays(7)->toDateTimeString())
->first();
if ($requestClaim) {
$tr_url = href_request($torrentRequest);
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] claim has been reset due to not being filled within 7 days.', $tr_url, $torrentRequest->name)
$tr_url = \href_request($torrentRequest);
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] claim has been reset due to not being filled within 7 days.', $tr_url, $torrentRequest->name)
);
$requestClaim->delete();

View File

@@ -17,6 +17,9 @@ use App\Models\FailedLoginAttempt;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoRecycleFailedLoginsTest
*/
class AutoRecycleFailedLogins extends Command
{
/**

View File

@@ -17,6 +17,9 @@ use App\Models\Invite;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoRecycleInvitesTest
*/
class AutoRecycleInvites extends Command
{
/**

View File

@@ -19,18 +19,21 @@ use App\Repositories\ChatRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoRemoveFeaturedTorrentTest
*/
class AutoRemoveFeaturedTorrent extends Command
{
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
parent::__construct();
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
@@ -67,10 +70,10 @@ class AutoRemoveFeaturedTorrent extends Command
$torrent->save();
// Auto Announce Featured Expired
$appurl = config('app.url');
$appurl = \config('app.url');
$this->chat->systemMessage(
sprintf('Ladies and Gents, [url=%s/torrents/%s]%s[/url] is no longer featured. :poop:', $appurl, $torrent->id, $torrent->name)
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/torrents/%s]%s[/url] is no longer featured. :poop:', $appurl, $torrent->id, $torrent->name)
);
}

View File

@@ -18,6 +18,9 @@ use App\Models\PrivateMessage;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoRemovePersonalFreeleechTest
*/
class AutoRemovePersonalFreeleech extends Command
{
/**

View File

@@ -19,6 +19,9 @@ use App\Models\Warning;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* @see \Tests\Todo\Unit\Console\Commands\AutoRevokePermissionsTest
*/
class AutoRevokePermissions extends Command
{
/**
@@ -44,16 +47,16 @@ class AutoRevokePermissions extends Command
*/
public function handle()
{
$banned_group = cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$validating_group = cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$leech_group = cache()->rememberForever('leech_group', fn () => Group::where('slug', '=', 'leech')->pluck('id'));
$disabled_group = cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
$pruned_group = cache()->rememberForever('pruned_group', fn () => Group::where('slug', '=', 'pruned')->pluck('id'));
$banned_group = \cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$validating_group = \cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$leech_group = \cache()->rememberForever('leech_group', fn () => Group::where('slug', '=', 'leech')->pluck('id'));
$disabled_group = \cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
$pruned_group = \cache()->rememberForever('pruned_group', fn () => Group::where('slug', '=', 'pruned')->pluck('id'));
User::whereNotIn('group_id', [$banned_group[0], $validating_group[0], $leech_group[0], $disabled_group[0], $pruned_group[0]])->update(['can_download' => '1', 'can_request' => '1']);
User::whereIn('group_id', [$banned_group[0], $validating_group[0], $leech_group[0], $disabled_group[0], $pruned_group[0]])->update(['can_download' => '0', 'can_request' => '0']);
$warning = Warning::with('warneduser')->select(DB::raw('user_id, count(*) as value'))->where('active', '=', 1)->groupBy('user_id')->having('value', '>=', config('hitrun.revoke'))->get();
$warning = Warning::with('warneduser')->select(DB::raw('user_id, count(*) as value'))->where('active', '=', 1)->groupBy('user_id')->having('value', '>=', \config('hitrun.revoke'))->get();
foreach ($warning as $deny) {
if ($deny->warneduser->can_download == 1 && $deny->warneduser->can_request == 1) {

View File

@@ -14,11 +14,26 @@
namespace App\Console\Commands;
use App\Jobs\SendDeleteUserMail;
use App\Models\Comment;
use App\Models\Follow;
use App\Models\Group;
use App\Models\Invite;
use App\Models\Like;
use App\Models\Message;
use App\Models\Note;
use App\Models\Peer;
use App\Models\Post;
use App\Models\PrivateMessage;
use App\Models\Thank;
use App\Models\Topic;
use App\Models\Torrent;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoSoftDeleteDisabledUsersTest
*/
class AutoSoftDeleteDisabledUsers extends Command
{
/**
@@ -44,18 +59,18 @@ class AutoSoftDeleteDisabledUsers extends Command
*/
public function handle()
{
if (config('pruning.user_pruning') == true) {
$disabled_group = cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
$pruned_group = cache()->rememberForever('pruned_group', fn () => Group::where('slug', '=', 'pruned')->pluck('id'));
if (\config('pruning.user_pruning') == true) {
$disabled_group = \cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
$pruned_group = \cache()->rememberForever('pruned_group', fn () => Group::where('slug', '=', 'pruned')->pluck('id'));
$current = Carbon::now();
$users = User::where('group_id', '=', $disabled_group[0])
->where('disabled_at', '<', $current->copy()->subDays(config('pruning.soft_delete'))->toDateTimeString())
->where('disabled_at', '<', $current->copy()->subDays(\config('pruning.soft_delete'))->toDateTimeString())
->get();
foreach ($users as $user) {
// Send Email
dispatch(new SendDeleteUserMail($user));
\dispatch(new SendDeleteUserMail($user));
$user->can_upload = 0;
$user->can_download = 0;
@@ -66,6 +81,77 @@ class AutoSoftDeleteDisabledUsers extends Command
$user->group_id = $pruned_group[0];
$user->deleted_by = 1;
$user->save();
// Removes UserID from Torrents if any and replaces with System UserID (1)
foreach (Torrent::withAnyStatus()->where('user_id', '=', $user->id)->get() as $tor) {
$tor->user_id = 1;
$tor->save();
}
// Removes UserID from Comments if any and replaces with System UserID (1)
foreach (Comment::where('user_id', '=', $user->id)->get() as $com) {
$com->user_id = 1;
$com->save();
}
// Removes UserID from Posts if any and replaces with System UserID (1)
foreach (Post::where('user_id', '=', $user->id)->get() as $post) {
$post->user_id = 1;
$post->save();
}
// Removes UserID from Topic Creators if any and replaces with System UserID (1)
foreach (Topic::where('first_post_user_id', '=', $user->id)->get() as $topic) {
$topic->first_post_user_id = 1;
$topic->save();
}
// Removes UserID from Topic if any and replaces with System UserID (1)
foreach (Topic::where('last_post_user_id', '=', $user->id)->get() as $topic) {
$topic->last_post_user_id = 1;
$topic->save();
}
// Removes UserID from PM if any and replaces with System UserID (1)
foreach (PrivateMessage::where('sender_id', '=', $user->id)->get() as $sent) {
$sent->sender_id = 1;
$sent->save();
}
// Removes UserID from PM if any and replaces with System UserID (1)
foreach (PrivateMessage::where('receiver_id', '=', $user->id)->get() as $received) {
$received->receiver_id = 1;
$received->save();
}
// Removes all Posts made by User from the shoutbox
foreach (Message::where('user_id', '=', $user->id)->get() as $shout) {
$shout->delete();
}
// Removes all notes for user
foreach (Note::where('user_id', '=', $user->id)->get() as $note) {
$note->delete();
}
// Removes all likes for user
foreach (Like::where('user_id', '=', $user->id)->get() as $like) {
$like->delete();
}
// Removes all thanks for user
foreach (Thank::where('user_id', '=', $user->id)->get() as $thank) {
$thank->delete();
}
// Removes all follows for user
foreach (Follow::where('user_id', '=', $user->id)->get() as $follow) {
$follow->delete();
}
// Removes UserID from Sent Invites if any and replaces with System UserID (1)
foreach (Invite::where('user_id', '=', $user->id)->get() as $sent_invite) {
$sent_invite->user_id = 1;
$sent_invite->save();
}
// Removes UserID from Received Invite if any and replaces with System UserID (1)
foreach (Invite::where('accepted_by', '=', $user->id)->get() as $received_invite) {
$received_invite->accepted_by = 1;
$received_invite->save();
}
// Removes all Peers for user
foreach (Peer::where('user_id', '=', $user->id)->get() as $peer) {
$peer->delete();
}
$user->delete();
}
}

View File

@@ -19,6 +19,9 @@ use App\Models\Warning;
use Carbon\Carbon;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\AutoWarningTest
*/
class AutoWarning extends Command
{
/**
@@ -44,20 +47,20 @@ class AutoWarning extends Command
*/
public function handle()
{
if (config('hitrun.enabled') == true) {
$current = new Carbon();
if (\config('hitrun.enabled') == true) {
$carbon = new Carbon();
$hitrun = History::with(['user', 'torrent'])
->where('actual_downloaded', '>', 0)
->where('prewarn', '=', 1)
->where('hitrun', '=', 0)
->where('immune', '=', 0)
->where('active', '=', 0)
->where('seedtime', '<', config('hitrun.seedtime'))
->where('updated_at', '<', $current->copy()->subDays(config('hitrun.grace'))->toDateTimeString())
->where('seedtime', '<', \config('hitrun.seedtime'))
->where('updated_at', '<', $carbon->copy()->subDays(\config('hitrun.grace'))->toDateTimeString())
->get();
foreach ($hitrun as $hr) {
if (! $hr->user->group->is_immune && $hr->actual_downloaded > ($hr->torrent->size * (config('hitrun.buffer') / 100))) {
if (! $hr->user->group->is_immune && $hr->actual_downloaded > ($hr->torrent->size * (\config('hitrun.buffer') / 100))) {
$exsist = Warning::withTrashed()
->where('torrent', '=', $hr->torrent->id)
->where('user_id', '=', $hr->user->id)
@@ -68,8 +71,8 @@ class AutoWarning extends Command
$warning->user_id = $hr->user->id;
$warning->warned_by = '1';
$warning->torrent = $hr->torrent->id;
$warning->reason = sprintf('Hit and Run Warning For Torrent %s', $hr->torrent->name);
$warning->expires_on = $current->copy()->addDays(config('hitrun.expire'));
$warning->reason = \sprintf('Hit and Run Warning For Torrent %s', $hr->torrent->name);
$warning->expires_on = $carbon->copy()->addDays(\config('hitrun.expire'));
$warning->active = '1';
$warning->save();

View File

@@ -15,6 +15,9 @@ namespace App\Console\Commands;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\ClearCacheTest
*/
class ClearCache extends Command
{
/**

View File

@@ -37,11 +37,11 @@ class DbDump extends Command
*/
public function handle()
{
$outfile = config('database.pristine-db-file');
$host = config('database.connections.mysql.host');
$db = config('database.connections.mysql.database');
$user = config('database.connections.mysql.username');
$password = config('database.connections.mysql.password');
$outfile = \config('database.pristine-db-file');
$host = \config('database.connections.mysql.host');
$db = \config('database.connections.mysql.database');
$user = \config('database.connections.mysql.username');
$password = \config('database.connections.mysql.password');
if (! $outfile) {
$this->error('The dump file location is not set in the configuration. If you\'ve tried to set it, you may need to call "php artisan cache:clear" and/or specify the environment when calling Artisan, e.g., "php artisan --env=testing db:dump".');
@@ -51,25 +51,25 @@ class DbDump extends Command
// Necessary to avoid warning about supplying password on CLI.
putenv(sprintf('MYSQL_PWD=%s', $password));
\putenv(\sprintf('MYSQL_PWD=%s', $password));
$cmd = sprintf(
$cmd = \sprintf(
'mysqldump --user=%s --databases %s --add-drop-database --add-drop-table --default-character-set=utf8mb4 --skip-extended-insert --host=%s --quick --quote-names --routines --set-charset --single-transaction --triggers --tz-utc %s> %s;',
escapeshellarg($user),
escapeshellarg($db),
escapeshellarg($host),
\escapeshellarg($user),
\escapeshellarg($db),
\escapeshellarg($host),
$this->option('verbose') ? '--verbose ' : '',
escapeshellarg($outfile)
\escapeshellarg($outfile)
);
$return = null;
$output = null;
exec($cmd, $output, $return);
\exec($cmd, $output, $return);
if ($return !== 0) {
$this->error(sprintf('Could not dump database to file %s', $outfile));
$this->error(\sprintf('Could not dump database to file %s', $outfile));
}
}
}

View File

@@ -39,30 +39,30 @@ class DbLoad extends Command
*/
public function handle()
{
$input = config('database.pristine-db-file');
$db = config('database.connections.mysql.database');
$user = config('database.connections.mysql.username');
$password = config('database.connections.mysql.password');
$input = \config('database.pristine-db-file');
$db = \config('database.connections.mysql.database');
$user = \config('database.connections.mysql.username');
$password = \config('database.connections.mysql.password');
// Necessary to avoid warning about supplying password on CLI.
putenv(sprintf('MYSQL_PWD=%s', $password));
\putenv(\sprintf('MYSQL_PWD=%s', $password));
$cmd = sprintf(
$cmd = \sprintf(
'mysql -u %s %s < %s',
escapeshellarg($user),
escapeshellarg($db),
escapeshellarg($input)
\escapeshellarg($user),
\escapeshellarg($db),
\escapeshellarg($input)
);
$return = null;
$output = null;
exec($cmd, $output, $return);
\exec($cmd, $output, $return);
if ($return !== 0) {
throw new \Exception(sprintf('Could not load database from file %s', $input));
throw new \Exception(\sprintf('Could not load database from file %s', $input));
}
}
}

View File

@@ -54,7 +54,7 @@ class DemoSeed extends Command
$this->warn('*** This process could take a few minutes ***');
$this->warn('Press CTRL + C to abort');
sleep(5);
\sleep(5);
$abort = false;
@@ -62,17 +62,17 @@ class DemoSeed extends Command
// Users
$this->info('Creating User Account');
$uid = factory()->create()->id;
$uid = \factory()->create()->id;
// random boolean
if ([false, true][rand(0, 1)]) {
if ([false, true][\rand(0, 1)]) {
$r = $this->search($id);
// Torrents
$this->info('Creating Movie Torrents for Account ID #'.$uid);
try {
factory()->create([
\factory()->create([
'user_id' => $uid,
'tmdb' => $id,
'name' => $r->title.' ('.$r->releaseYear.')',
@@ -227,8 +227,8 @@ Menu
01:34:15.858 : en:Who Gets Away?
01:44:15.249 : en:End Credits
',
'created_at' => now(),
'updated_at' => now(),
'created_at' => \now(),
'updated_at' => \now(),
]);
} catch (Exception $e) {
$abort = true;
@@ -265,11 +265,11 @@ Menu
private function search($id)
{
// we delay between api calls to reduce throttling
usleep(500_000);
\usleep(500_000);
$client = new \App\Services\MovieScrapper(config('api-keys.tmdb'), config('api-keys.tvdb'), config('api-keys.omdb'));
$movieScrapper = new \App\Services\MovieScrapper(\config('api-keys.tmdb'), \config('api-keys.tvdb'), \config('api-keys.omdb'));
return $client->scrape('movie', null, $id);
return $movieScrapper->scrape('movie', null, $id);
}
private function ids()

View File

@@ -18,6 +18,9 @@ use App\Models\Torrent;
use App\Services\MovieScrapper;
use Illuminate\Console\Command;
/**
* @see \Tests\Todo\Unit\Console\Commands\FetchGenresTest
*/
class FetchGenres extends Command
{
/**
@@ -44,7 +47,7 @@ class FetchGenres extends Command
*/
public function handle()
{
$client = new MovieScrapper(config('api-keys.tmdb'), config('api-keys.tvdb'), config('api-keys.omdb'));
$movieScrapper = new MovieScrapper(\config('api-keys.tmdb'), \config('api-keys.tvdb'), \config('api-keys.omdb'));
$torrents = Torrent::withAnyStatus()
->select(['id', 'category_id', 'imdb', 'tmdb'])
@@ -53,16 +56,16 @@ class FetchGenres extends Command
foreach ($torrents as $torrent) {
if ($torrent->category->tv_meta) {
if ($torrent->tmdb && $torrent->tmdb != 0) {
$meta = $client->scrape('tv', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('tv', null, $torrent->tmdb);
} else {
$meta = $client->scrape('tv', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('tv', 'tt'.$torrent->imdb);
}
}
if ($torrent->category->movie_meta) {
if ($torrent->tmdb && $torrent->tmdb != 0) {
$meta = $client->scrape('movie', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('movie', null, $torrent->tmdb);
} else {
$meta = $client->scrape('movie', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('movie', 'tt'.$torrent->imdb);
}
}
@@ -76,7 +79,7 @@ class FetchGenres extends Command
}
// sleep for 1 second
sleep(1);
\sleep(1);
}
$this->comment('Torrent Genres Command Complete');
}

View File

@@ -18,6 +18,9 @@ use App\Services\MovieScrapper;
use Illuminate\Console\Command;
use MarcReichel\IGDBLaravel\Models\Game;
/**
* @see \Tests\Todo\Unit\Console\Commands\FetchReleaseYearsTest
*/
class FetchReleaseYears extends Command
{
/**
@@ -44,8 +47,8 @@ class FetchReleaseYears extends Command
*/
public function handle()
{
$client = new MovieScrapper(config('api-keys.tmdb'), config('api-keys.tvdb'), config('api-keys.omdb'));
$appurl = config('app.url');
$movieScrapper = new MovieScrapper(\config('api-keys.tmdb'), \config('api-keys.tvdb'), \config('api-keys.omdb'));
$appurl = \config('app.url');
$torrents = Torrent::withAnyStatus()
->with(['category'])
@@ -61,25 +64,25 @@ class FetchReleaseYears extends Command
->whereNull('release_year')
->count();
$this->alert(sprintf('%s Torrents Already Have A Release Year Value', $withyear));
$this->alert(sprintf('%s Torrents Are Missing A Release Year Value', $withoutyear));
$this->alert(\sprintf('%s Torrents Already Have A Release Year Value', $withyear));
$this->alert(\sprintf('%s Torrents Are Missing A Release Year Value', $withoutyear));
foreach ($torrents as $torrent) {
$meta = null;
if ($torrent->category->tv_meta) {
if ($torrent->tmdb && $torrent->tmdb != 0) {
$meta = $client->scrape('tv', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('tv', null, $torrent->tmdb);
} else {
$meta = $client->scrape('tv', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('tv', 'tt'.$torrent->imdb);
}
if (isset($meta->releaseYear) && $meta->releaseYear > '1900') {
$torrent->release_year = $meta->releaseYear;
$torrent->save();
$this->info(sprintf('(%s) Release Year Fetched For Torrent %s
$this->info(\sprintf('(%s) Release Year Fetched For Torrent %s
', $torrent->category->name, $torrent->name));
} else {
$this->warn(sprintf('(%s) No Release Year Found For Torrent %s
$this->warn(\sprintf('(%s) No Release Year Found For Torrent %s
%s/torrents/%s
', $torrent->category->name, $torrent->name, $appurl, $torrent->id));
}
@@ -87,17 +90,17 @@ class FetchReleaseYears extends Command
if ($torrent->category->movie_meta) {
if ($torrent->tmdb && $torrent->tmdb != 0) {
$meta = $client->scrape('movie', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('movie', null, $torrent->tmdb);
} else {
$meta = $client->scrape('movie', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('movie', 'tt'.$torrent->imdb);
}
if (isset($meta->releaseYear) && $meta->releaseYear > '1900') {
$torrent->release_year = $meta->releaseYear;
$torrent->save();
$this->info(sprintf('(%s) Release Year Fetched For Torrent %s
$this->info(\sprintf('(%s) Release Year Fetched For Torrent %s
', $torrent->category->name, $torrent->name));
} else {
$this->warn(sprintf('(%s) No Release Year Found For Torrent %s
$this->warn(\sprintf('(%s) No Release Year Found For Torrent %s
%s/torrents/%s
', $torrent->category->name, $torrent->name, $appurl, $torrent->id));
}
@@ -108,24 +111,24 @@ class FetchReleaseYears extends Command
$meta = Game::find($torrent->igdb);
}
if (isset($meta->first_release_date) && $meta->first_release_date > '1900') {
$torrent->release_year = date('Y', strtotime($meta->first_release_date));
$torrent->release_year = \date('Y', \strtotime($meta->first_release_date));
$torrent->save();
$this->info(sprintf('(%s) Release Year Fetched For Torrent %s
$this->info(\sprintf('(%s) Release Year Fetched For Torrent %s
', $torrent->category->name, $torrent->name));
} else {
$this->warn(sprintf('(%s) No Release Year Found For Torrent %s
$this->warn(\sprintf('(%s) No Release Year Found For Torrent %s
%s/torrents/%s
', $torrent->category->name, $torrent->name, $appurl, $torrent->id));
}
}
if ($torrent->category->no_meta || $torrent->category->music_meta) {
$this->warn(sprintf('(SKIPPED) %s Is In A Category That Does Not Have Meta.
$this->warn(\sprintf('(SKIPPED) %s Is In A Category That Does Not Have Meta.
', $torrent->name));
}
// sleep for 1 second
sleep(1);
\sleep(1);
}
$this->comment('Torrent Release Year Command Complete');
}

View File

@@ -20,6 +20,9 @@ use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* @see \Tests\Todo\Unit\Console\Commands\GitUpdaterTest
*/
class GitUpdater extends Command
{
use ConsoleTools;
@@ -94,14 +97,14 @@ class GitUpdater extends Command
if (! $this->io->confirm('Would you like to proceed', false)) {
$this->line('<fg=red>Aborted ...</>');
die();
exit();
}
$this->io->writeln('
Press CTRL + C ANYTIME to abort! Aborting can lead to unexpected results!
');
sleep(1);
\sleep(1);
$this->update();
@@ -114,7 +117,7 @@ class GitUpdater extends Command
{
$updating = $this->checkForUpdates();
if ((is_countable($updating) ? count($updating) : 0) > 0) {
if ((\is_countable($updating) ? \count($updating) : 0) > 0) {
$this->alertDanger('Found Updates');
$this->cyan('Files that need updated:');
@@ -141,8 +144,8 @@ class GitUpdater extends Command
$this->restore($paths);
$conflicts = array_intersect($updating, $paths);
if (count($conflicts) > 0) {
$conflicts = \array_intersect($updating, $paths);
if (\count($conflicts) > 0) {
$this->red('There are some files that was not updated because because of conflicts.');
$this->red('We will walk you through updating these files now.');
@@ -173,7 +176,7 @@ class GitUpdater extends Command
$this->call('up');
} else {
$this->alertDanger('Aborted Update');
die();
exit();
}
} else {
$this->alertSuccess('No Available Updates Found');
@@ -186,7 +189,7 @@ class GitUpdater extends Command
$this->process('git fetch origin');
$process = $this->process('git diff ..origin/master --name-only');
$updating = array_filter(explode("\n", $process->getOutput()), 'strlen');
$updating = \array_filter(\explode("\n", $process->getOutput()), 'strlen');
$this->done();
@@ -199,7 +202,7 @@ class GitUpdater extends Command
$this->red('Updating will cause you to LOSE any changes you might have made to the file!');
foreach ($updating as $file) {
if ($this->io->confirm(sprintf('Update %s', $file), true)) {
if ($this->io->confirm(\sprintf('Update %s', $file), true)) {
$this->updateFile($file);
}
}
@@ -209,7 +212,7 @@ class GitUpdater extends Command
private function updateFile($file)
{
$this->process(sprintf('git checkout origin/master -- %s', $file));
$this->process(\sprintf('git checkout origin/master -- %s', $file));
}
private function backup(array $paths)
@@ -217,14 +220,14 @@ class GitUpdater extends Command
$this->header('Backing Up Files');
$this->commands([
'rm -rf '.storage_path('gitupdate'),
'mkdir '.storage_path('gitupdate'),
'rm -rf '.\storage_path('gitupdate'),
'mkdir '.\storage_path('gitupdate'),
], true);
foreach ($paths as $path) {
$this->validatePath($path);
$this->createBackupPath($path);
$this->process($this->copy_command.' '.base_path($path).' '.storage_path('gitupdate').'/'.$path);
$this->process($this->copy_command.' '.\base_path($path).' '.\storage_path('gitupdate').'/'.$path);
}
$this->done();
@@ -235,15 +238,15 @@ class GitUpdater extends Command
$this->header('Restoring Backups');
foreach ($paths as $path) {
$to = Str::replaceLast('/.', '', base_path(dirname($path)));
$from = storage_path('gitupdate').'/'.$path;
$to = Str::replaceLast('/.', '', \base_path(\dirname($path)));
$from = \storage_path('gitupdate').'/'.$path;
if (is_dir($from)) {
$to .= '/'.basename($from).'/';
if (\is_dir($from)) {
$to .= '/'.\basename($from).'/';
$from .= '/*';
}
$this->process(sprintf('%s %s %s', $this->copy_command, $from, $to));
$this->process(\sprintf('%s %s %s', $this->copy_command, $from, $to));
}
$this->commands([
@@ -315,8 +318,8 @@ class GitUpdater extends Command
private function validatePath($path)
{
if (! is_file(base_path($path)) && ! is_dir(base_path($path))) {
$this->red(sprintf("The path '%s' is invalid", $path));
if (! \is_file(\base_path($path)) && ! \is_dir(\base_path($path))) {
$this->red(\sprintf("The path '%s' is invalid", $path));
//$this->call('up');
//die();
}
@@ -324,12 +327,12 @@ class GitUpdater extends Command
private function createBackupPath($path)
{
if (! is_dir(storage_path(sprintf('gitupdate/%s', $path))) && ! is_file(base_path($path))) {
mkdir(storage_path(sprintf('gitupdate/%s', $path)), 0775, true);
} elseif (is_file(base_path($path)) && dirname($path) !== '.') {
$path = dirname($path);
if (! is_dir(storage_path(sprintf('gitupdate/%s', $path)))) {
mkdir(storage_path(sprintf('gitupdate/%s', $path)), 0775, true);
if (! \is_dir(\storage_path(\sprintf('gitupdate/%s', $path))) && ! \is_file(\base_path($path))) {
\mkdir(\storage_path(\sprintf('gitupdate/%s', $path)), 0775, true);
} elseif (\is_file(\base_path($path)) && \dirname($path) !== '.') {
$path = \dirname($path);
if (! \is_dir(\storage_path(\sprintf('gitupdate/%s', $path)))) {
\mkdir(\storage_path(\sprintf('gitupdate/%s', $path)), 0775, true);
}
}
}
@@ -352,8 +355,8 @@ class GitUpdater extends Command
private function paths()
{
$p = $this->process('git diff master --name-only');
$paths = array_filter(explode("\n", $p->getOutput()), 'strlen');
$paths = \array_filter(\explode("\n", $p->getOutput()), 'strlen');
return array_merge($paths, self::ADDITIONAL);
return \array_merge($paths, self::ADDITIONAL);
}
}

View File

@@ -52,8 +52,8 @@ class IrcBroadcast extends Command
public function handle()
{
$this->info('Broadcasting: '.$this->argument('message'));
$bot = new IRCAnnounceBot();
$bot->broadcast($this->argument('message'));
$ircAnnounceBot = new IRCAnnounceBot();
$ircAnnounceBot->broadcast($this->argument('message'));
}
/**

View File

@@ -52,8 +52,8 @@ class IrcMessage extends Command
public function handle()
{
$this->info('Messaging '.$this->argument('channel').': '.$this->argument('message'));
$bot = new IRCAnnounceBot();
$bot->message($this->argument('channel'), $this->argument('message'));
$ircAnnounceBot = new IRCAnnounceBot();
$ircAnnounceBot->message($this->argument('channel'), $this->argument('message'));
}
/**

View File

@@ -15,6 +15,9 @@ namespace App\Console\Commands;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\SetCacheTest
*/
class SetCache extends Command
{
/**

View File

@@ -16,6 +16,9 @@ namespace App\Console\Commands;
use App\Models\Torrent;
use Illuminate\Console\Command;
/**
* @see \Tests\Unit\Console\Commands\SyncPeersTest
*/
class SyncPeers extends Command
{
/**

View File

@@ -17,6 +17,9 @@ use App\Mail\TestEmail;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
/**
* @see \Tests\Todo\Unit\Console\Commands\TestMailSettingsTest
*/
class TestMailSettings extends Command
{
/**
@@ -40,10 +43,10 @@ class TestMailSettings extends Command
*/
public function handle()
{
$owner = config('other.email');
$owner = \config('other.email');
$this->info('Sending Test Email To '.$owner);
sleep(5);
\sleep(5);
try {
Mail::to($owner)->send(new TestEmail());

View File

@@ -18,6 +18,9 @@ use Illuminate\Console\Command;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
/**
* @see \Tests\Todo\Unit\Console\Commands\VendorCleanupTest
*/
class VendorCleanup extends Command
{
protected $signature = 'vendor:cleanup {--check : Runs in dry mode without deleting files.}';
@@ -91,23 +94,25 @@ class VendorCleanup extends Command
*/
public function handle()
{
$patterns = array_diff($this->patterns, $this->excluded);
$patterns = \array_diff($this->patterns, $this->excluded);
$directories = $this->expandDirectoryTree(base_path('vendor'));
$directories = $this->expandDirectoryTree(\base_path('vendor'));
$isDry = $this->option('check');
foreach ($directories as $directory) {
foreach ($patterns as $pattern) {
$casePattern = preg_replace_callback('#([a-z])#i', [$this, 'prepareWord'], $pattern);
$casePattern = \preg_replace_callback('#([a-z])#i', function ($matches) {
return $this->prepareWord($matches);
}, $pattern);
$files = glob($directory.'/'.$casePattern, GLOB_BRACE);
$files = \glob($directory.'/'.$casePattern, GLOB_BRACE);
if (! $files) {
continue;
}
$files = array_diff($files, $this->excluded);
$files = \array_diff($files, $this->excluded);
foreach ($this->excluded as $excluded) {
$key = $this->arrayFind($excluded, $files);
@@ -118,7 +123,7 @@ class VendorCleanup extends Command
}
}
foreach ($files as $file) {
if (is_dir($file)) {
if (\is_dir($file)) {
$this->out('DELETING DIR: '.$file);
if (! $isDry) {
$this->delTree($file);
@@ -126,7 +131,7 @@ class VendorCleanup extends Command
} else {
$this->out('DELETING FILE: '.$file);
if (! $isDry) {
@unlink($file);
@\unlink($file);
}
}
}
@@ -145,12 +150,12 @@ class VendorCleanup extends Command
protected function expandDirectoryTree($dir)
{
$directories = [];
$files = array_diff(scandir($dir), ['.', '..']);
$files = \array_diff(\scandir($dir), ['.', '..']);
foreach ($files as $file) {
$directory = $dir.'/'.$file;
if (is_dir($directory)) {
if (\is_dir($directory)) {
$directories[] = $directory;
$directories = array_merge($directories, $this->expandDirectoryTree($directory));
$directories = \array_merge($directories, $this->expandDirectoryTree($directory));
}
}
@@ -166,7 +171,7 @@ class VendorCleanup extends Command
*/
protected function delTree($dir)
{
if (! file_exists($dir) || ! is_dir($dir)) {
if (! \file_exists($dir) || ! \is_dir($dir)) {
return false;
}
$iterator = new RecursiveIteratorIterator(
@@ -175,12 +180,12 @@ class VendorCleanup extends Command
);
foreach ($iterator as $filename => $fileInfo) {
if ($fileInfo->isDir()) {
@rmdir($filename);
@\rmdir($filename);
} else {
@unlink($filename);
@\unlink($filename);
}
}
@rmdir($dir);
@\rmdir($dir);
}
/**
@@ -192,13 +197,13 @@ class VendorCleanup extends Command
*/
protected function prepareWord($matches)
{
return '['.strtolower($matches[1]).strtoupper($matches[1]).']';
return '['.\strtolower($matches[1]).\strtoupper($matches[1]).']';
}
protected function arrayFind($needle, array $haystack)
{
foreach ($haystack as $key => $value) {
if (false !== stripos($value, $needle)) {
if (false !== \stripos($value, $needle)) {
return $key;
}
}

View File

@@ -27,7 +27,7 @@ trait ConsoleTools
private function cyan($line)
{
$this->io->writeln(sprintf('<fg=cyan>%s</>', $line));
$this->io->writeln(\sprintf('<fg=cyan>%s</>', $line));
}
private function white($line)
@@ -37,22 +37,22 @@ trait ConsoleTools
private function magenta($line)
{
$this->io->writeln(sprintf('<fg=magenta>%s</>', $line));
$this->io->writeln(\sprintf('<fg=magenta>%s</>', $line));
}
private function green($line)
{
$this->io->writeln(sprintf('<fg=green>%s</>', $line));
$this->io->writeln(\sprintf('<fg=green>%s</>', $line));
}
private function red($line)
{
$this->io->writeln(sprintf('<fg=red>%s</>', $line));
$this->io->writeln(\sprintf('<fg=red>%s</>', $line));
}
private function blue($line)
{
$this->io->writeln(sprintf('<fg=blue>%s</>', $line));
$this->io->writeln(\sprintf('<fg=blue>%s</>', $line));
}
private function done()
@@ -62,29 +62,29 @@ trait ConsoleTools
private function header($line)
{
$this->blue(str_repeat('=', 50));
$this->blue(\str_repeat('=', 50));
$this->io->write($line);
$this->blue(str_repeat('=', 50));
$this->blue(\str_repeat('=', 50));
}
private function alertSuccess($line)
{
$this->io->writeln(sprintf('<fg=white>[</><fg=green> !! %s !! </><fg=white>]</>', $line));
$this->io->writeln(\sprintf('<fg=white>[</><fg=green> !! %s !! </><fg=white>]</>', $line));
}
private function alertDanger($line)
{
$this->io->writeln(sprintf('<fg=white>[</><fg=red> !! %s !! </><fg=white>]</>', $line));
$this->io->writeln(\sprintf('<fg=white>[</><fg=red> !! %s !! </><fg=white>]</>', $line));
}
private function alertInfo($line)
{
$this->io->writeln(sprintf('<fg=white>[</><fg=cyan> !! %s !! </><fg=white>]</>', $line));
$this->io->writeln(\sprintf('<fg=white>[</><fg=cyan> !! %s !! </><fg=white>]</>', $line));
}
private function alertWarning($line)
{
$this->io->writeln(sprintf('<fg=white>[</><fg=yellow> !! %s !! </><fg=white>]</>', $line));
$this->io->writeln(\sprintf('<fg=white>[</><fg=yellow> !! %s !! </><fg=white>]</>', $line));
}
private function commands(array $commands, $silent = false)
@@ -106,7 +106,7 @@ trait ConsoleTools
$bar = $this->progressStart();
}
$process = new Process($command);
$process = Process::fromShellCommandline($command);
$process->setTimeout(3_600);
$process->start();
@@ -114,14 +114,14 @@ trait ConsoleTools
try {
$process->checkTimeout();
} catch (ProcessTimedOutException $e) {
$this->red(sprintf("'%s' timed out.!", $command));
$this->red(\sprintf("'%s' timed out.!", $command));
}
if (! $silent) {
$bar->advance();
}
usleep(200_000);
\usleep(200_000);
}
if (! $silent) {

2
app/Console/Kernel.php Executable file → Normal file
View File

@@ -72,6 +72,6 @@ class Kernel extends ConsoleKernel
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
require \base_path('routes/console.php');
}
}

15
app/Exceptions/Handler.php Executable file → Normal file
View File

@@ -15,6 +15,7 @@ namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
@@ -46,29 +47,29 @@ class Handler extends ExceptionHandler
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @param \Throwable $throwable
*
* @throws \Exception
*
* @return void
*/
public function report(Exception $exception)
public function report(Throwable $throwable)
{
parent::report($exception);
parent::report($throwable);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @param \Throwable $throwable
*
* @throws \Exception
* @throws \Throwable
*
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
public function render($request, Throwable $throwable)
{
return parent::render($request, $exception);
return parent::render($request, $throwable);
}
}

View File

@@ -36,9 +36,9 @@ class BBCodeConverter
*/
protected function replaceSize()
{
$this->text = preg_replace_callback('#\[size=([\W\D\w\s]*?)\]([\W\D\w\s]*?)\[/size\]#iu',
$this->text = \preg_replace_callback('#\[size=([\W\D\w\s]*?)\]([\W\D\w\s]*?)\[/size\]#iu',
fn ($matches) => '<span style="font-size: '.trim($matches[1], '').';">'.trim($matches[1], '').'</span>',
fn ($matches) => '<span style="font-size: '.\trim($matches[1], '').';">'.\trim($matches[1], '').'</span>',
$this->text
);
@@ -49,9 +49,9 @@ class BBCodeConverter
*/
protected function replaceCenter()
{
$this->text = preg_replace_callback('#\[center\]([\W\D\w\s]*?)\[/center\]#iu',
$this->text = \preg_replace_callback('#\[center\]([\W\D\w\s]*?)\[/center\]#iu',
fn ($matches) => '<span class="text-center">'.trim($matches[1], ' ').'</span>',
fn ($matches) => '<span class="text-center">'.\trim($matches[1], ' ').'</span>',
$this->text
);
@@ -62,9 +62,9 @@ class BBCodeConverter
*/
protected function replaceBold()
{
$this->text = preg_replace_callback('#\[b\]([\W\D\w\s]*?)\[/b\]#iu',
$this->text = \preg_replace_callback('#\[b\]([\W\D\w\s]*?)\[/b\]#iu',
fn ($matches) => '**'.trim($matches[1], ' ').'**',
fn ($matches) => '**'.\trim($matches[1], ' ').'**',
$this->text
);
@@ -75,9 +75,9 @@ class BBCodeConverter
*/
protected function replaceItalic()
{
$this->text = preg_replace_callback('#\[i\]([\W\D\w\s]*?)\[/i\]#iu',
$this->text = \preg_replace_callback('#\[i\]([\W\D\w\s]*?)\[/i\]#iu',
fn ($matches) => '*'.trim($matches[1], ' ').'*',
fn ($matches) => '*'.\trim($matches[1], ' ').'*',
$this->text
);
@@ -88,9 +88,9 @@ class BBCodeConverter
*/
protected function replaceUnderline()
{
$this->text = preg_replace_callback('#\[u\]([\W\D\w\s]*?)\[/u\]#iu',
$this->text = \preg_replace_callback('#\[u\]([\W\D\w\s]*?)\[/u\]#iu',
fn ($matches) => '_'.trim($matches[1], ' ').'_',
fn ($matches) => '_'.\trim($matches[1], ' ').'_',
$this->text
);
@@ -101,9 +101,9 @@ class BBCodeConverter
*/
protected function replaceStrikethrough()
{
$this->text = preg_replace_callback('#\[s\]([\W\D\w\s]*?)\[/s\]#iu',
$this->text = \preg_replace_callback('#\[s\]([\W\D\w\s]*?)\[/s\]#iu',
fn ($matches) => '~~'.trim($matches[1], ' ').'~~',
fn ($matches) => '~~'.\trim($matches[1], ' ').'~~',
$this->text
);
@@ -114,31 +114,31 @@ class BBCodeConverter
*/
protected function replaceLists()
{
$this->text = preg_replace_callback('#\[list(?P<type>=1)?\](?P<items>[\W\D\w\s]*?)\[/list\]#iu',
$this->text = \preg_replace_callback('#\[list(?P<type>=1)?\](?P<items>[\W\D\w\s]*?)\[/list\]#iu',
function ($matches) {
$buffer = '';
$list = preg_replace('#\s*$|^\s*#mu', '', $matches['items']);
if (is_null($list)) {
throw new \RuntimeException(sprintf("Text identified by '%d' has malformed BBCode lists", $this->id));
$list = \preg_replace('#\s*$|^\s*#mu', '', $matches['items']);
if (\is_null($list)) {
throw new \RuntimeException(\sprintf("Text identified by '%d' has malformed BBCode lists", $this->id));
}
$items = preg_split('#\[\*\]#u', $list);
$items = \preg_split('#\[\*\]#u', $list);
$counter = count($items);
$counter = is_countable($items) ? \count($items) : 0;
if (isset($matches['type']) && $matches['type'] == '=1') { // ordered list
// We start from 1 to discard the first string, in fact, it's empty.
for ($i = 1; $i < $counter; $i++) {
if (! empty($items[$i])) {
$buffer .= (string) ($i).'. '.trim($items[$i]).PHP_EOL;
$buffer .= (string) ($i).'. '.\trim($items[$i]).PHP_EOL;
}
}
} else { // unordered list
// We start from 1 to discard the first string, in fact, it's empty.
for ($i = 1; $i < $counter; $i++) {
if (! empty($items[$i])) {
$buffer .= '- '.trim($items[$i]).PHP_EOL;
$buffer .= '- '.\trim($items[$i]).PHP_EOL;
}
}
}
@@ -162,46 +162,46 @@ class BBCodeConverter
{
$replaceRow = function ($matches) {
$columns = $matches['columns'];
$columns = trim($columns);
$columns = \trim($columns);
$cells = preg_replace_callback('#\[td?\](?P<cells>[\W\w\s]*?)\[/td\]#iu', fn ($matches) => $matches['cells'].' | ', $columns);
$cells = \preg_replace_callback('#\[td?\](?P<cells>[\W\w\s]*?)\[/td\]#iu', fn ($matches) => $matches['cells'].' | ', $columns);
if ($cells !== '') {
$cells = '| '.$cells;
}
return trim($cells);
return \trim($cells);
};
$this->text = preg_replace_callback('#\[table?\](?P<rows>[\W\w\s]*?)\[/table\]#iu', function ($tableMatches) use ($replaceRow) {
preg_match_all('#\[th?\](?P<columns>[\W\w\s]*?)\[/th\]#iu', $tableMatches['rows'], $headerMatches, PREG_SET_ORDER);
$this->text = \preg_replace_callback('#\[table?\](?P<rows>[\W\w\s]*?)\[/table\]#iu', function ($tableMatches) use ($replaceRow) {
\preg_match_all('#\[th?\](?P<columns>[\W\w\s]*?)\[/th\]#iu', $tableMatches['rows'], $headerMatches, PREG_SET_ORDER);
$headers = [];
if (count($headerMatches) !== 0) {
$headers = array_map($replaceRow, $headerMatches);
if (\count($headerMatches) !== 0) {
$headers = \array_map($replaceRow, $headerMatches);
}
preg_match_all('#\[tr?\](?P<columns>[\W\w\s]*?)\[/tr\]#iu', $tableMatches['rows'], $contentMatches, PREG_SET_ORDER);
\preg_match_all('#\[tr?\](?P<columns>[\W\w\s]*?)\[/tr\]#iu', $tableMatches['rows'], $contentMatches, PREG_SET_ORDER);
$rows = [];
if (count($contentMatches) !== 0) {
$rows = array_map($replaceRow, $contentMatches);
if (\count($contentMatches) !== 0) {
$rows = \array_map($replaceRow, $contentMatches);
}
$headerSeparator = '';
if (count($rows) > 0) {
$columnCount = substr_count($rows[0], '|');
if (\count($rows) > 0) {
$columnCount = \substr_count($rows[0], '|');
if (count($headers) === 0) {
$headers[] = implode(' ', array_fill(0, $columnCount, '|'));
if (\count($headers) === 0) {
$headers[] = \implode(' ', \array_fill(0, $columnCount, '|'));
}
$headerSeparator = implode(' --- ', array_fill(0, $columnCount, '|'));
$headerSeparator = \implode(' --- ', \array_fill(0, $columnCount, '|'));
} else {
return $tableMatches['rows'];
}
$headers[] = $headerSeparator;
return implode("\n", array_merge($headers, $rows))."\n";
return \implode("\n", \array_merge($headers, $rows))."\n";
}, $this->text);
}
@@ -210,14 +210,14 @@ class BBCodeConverter
*/
protected function replaceUrls()
{
$this->text = preg_replace_callback('#\[url\s*=\s*("(?:[^"]*")|\A[^\']*\Z|(?:[^\'">\]\s]+))\s*(?:[^]\s]*)\]([\W\D\w\s]*?)\[/url\]#iu',
$this->text = \preg_replace_callback('#\[url\s*=\s*("(?:[^"]*")|\A[^\']*\Z|(?:[^\'">\]\s]+))\s*(?:[^]\s]*)\]([\W\D\w\s]*?)\[/url\]#iu',
function ($matches) {
if (isset($matches[1]) && isset($matches[2])) {
return '['.$matches[2].']('.$matches[1].')';
}
throw new \RuntimeException(sprintf("Text identified by '%d' has malformed BBCode urls", $this->id));
throw new \RuntimeException(\sprintf("Text identified by '%d' has malformed BBCode urls", $this->id));
},
$this->text
@@ -229,7 +229,7 @@ class BBCodeConverter
*/
protected function replaceImage()
{
$this->text = preg_replace_callback('#\[img\]([\W\D\w\s]*?)\[/img\]#iu',
$this->text = \preg_replace_callback('#\[img\]([\W\D\w\s]*?)\[/img\]#iu',
fn ($matches) => PHP_EOL.'![]'.'('.$matches[1].')'.PHP_EOL,
@@ -242,7 +242,7 @@ class BBCodeConverter
*/
protected function replaceImages()
{
$this->text = preg_replace_callback('#\[img\s*=\s*("(?:[^"]*")|\A[^\']*\Z|(?:[^\'">\]\s]+))\s*(?:[^]\s]*)\[/img\]#iu',
$this->text = \preg_replace_callback('#\[img\s*=\s*("(?:[^"]*")|\A[^\']*\Z|(?:[^\'">\]\s]+))\s*(?:[^]\s]*)\[/img\]#iu',
fn ($matches) => PHP_EOL.'!['.$matches[2].']'.'('.$matches[1].')'.PHP_EOL,
@@ -256,13 +256,13 @@ class BBCodeConverter
protected function replaceQuotes()
{
// Removes the inner quotes, leaving just one level.
$this->text = preg_replace('#\G(?<!^)(?>(\[quote\b[^]]*](?>[^[]++|\[(?!/?quote)|(?1))*\[/quote])|(?<!\[)(?>[^[]++|\[(?!/?quote))+\K)|\[quote\b[^]]*]\K#', '', $this->text);
$this->text = \preg_replace('#\G(?<!^)(?>(\[quote\b[^]]*](?>[^[]++|\[(?!/?quote)|(?1))*\[/quote])|(?<!\[)(?>[^[]++|\[(?!/?quote))+\K)|\[quote\b[^]]*]\K#', '', $this->text);
// Replaces all the remaining quotes with '> ' characters.
$this->text = preg_replace_callback('#\[quote\b[^]]*\]((?>[^[]++|\[(?!/?quote))*)\[/quote\]#i',
$this->text = \preg_replace_callback('#\[quote\b[^]]*\]((?>[^[]++|\[(?!/?quote))*)\[/quote\]#i',
function ($matches) {
$quote = preg_replace('#^\s*#mu', '', trim($matches[1]));
$quote = \preg_replace('#^\s*#mu', '', \trim($matches[1]));
return '> '.$quote.PHP_EOL.PHP_EOL;
},
@@ -276,21 +276,21 @@ class BBCodeConverter
*/
protected function replaceSnippets()
{
$this->text = preg_replace_callback('#\[code\s*=?(?P<language>\w*)\](?P<snippet>[\W\D\w\s]*?)\[\/code\]#iu',
$this->text = \preg_replace_callback('#\[code\s*=?(?P<language>\w*)\](?P<snippet>[\W\D\w\s]*?)\[\/code\]#iu',
function ($matches) {
if (isset($matches['snippet'])) {
$language = strtolower($matches['language']);
$language = \strtolower($matches['language']);
if ($language === 'html4strict' or $language === 'div') {
if ($language === 'html4strict' || $language === 'div') {
$language = 'html';
} elseif ($language === 'shell' or $language === 'dos' or $language === 'batch') {
} elseif ($language === 'shell' || $language === 'dos' || $language === 'batch') {
$language = 'sh';
} elseif ($language === 'xul' or $language === 'wpf') {
} elseif ($language === 'xul' || $language === 'wpf') {
$language = 'xml';
} elseif ($language === 'asm') {
$language = 'nasm';
} elseif ($language === 'vb' or $language === 'visualbasic' or $language === 'vba') {
} elseif ($language === 'vb' || $language === 'visualbasic' || $language === 'vba') {
$language = 'vb.net';
} elseif ($language === 'asp') {
$language = 'aspx-vb';
@@ -298,7 +298,7 @@ class BBCodeConverter
$language = 'xml';
} elseif ($language === 'cplusplus') {
$language = 'cpp';
} elseif ($language === 'txt' or $language === 'gettext') {
} elseif ($language === 'txt' || $language === 'gettext') {
$language = 'text';
} elseif ($language === 'basic') {
$language = 'cbmbas';
@@ -308,10 +308,10 @@ class BBCodeConverter
$language = 'aspx-vb';
}
return PHP_EOL.'```'.$language.PHP_EOL.trim($matches['snippet']).PHP_EOL.'```'.PHP_EOL;
return PHP_EOL.'```'.$language.PHP_EOL.\trim($matches['snippet']).PHP_EOL.'```'.PHP_EOL;
}
throw new \RuntimeException(sprintf("Text identified by '%d' has malformed BBCode snippet.", $this->id));
throw new \RuntimeException(\sprintf("Text identified by '%d' has malformed BBCode snippet.", $this->id));
},
$this->text
@@ -323,9 +323,9 @@ class BBCodeConverter
*/
protected function replaceSpoilers()
{
$this->text = preg_replace_callback('#\[spoiler\]([\W\D\w\s]*?)\[/spoiler\]#iu',
$this->text = \preg_replace_callback('#\[spoiler\]([\W\D\w\s]*?)\[/spoiler\]#iu',
fn ($matches) => '<details><summary>Spoiler!</summary><pre><code>'.trim($matches[1], ' ').'</code></pre></details>',
fn ($matches) => '<details><summary>Spoiler!</summary><pre><code>'.\trim($matches[1], ' ').'</code></pre></details>',
$this->text
);
@@ -336,9 +336,9 @@ class BBCodeConverter
*/
protected function replaceColor()
{
$this->text = preg_replace_callback('#\[color=([\W\D\w\s]*?)\]([\W\D\w\s]*?)\[/color\]#iu',
$this->text = \preg_replace_callback('#\[color=([\W\D\w\s]*?)\]([\W\D\w\s]*?)\[/color\]#iu',
fn ($matches) => '<span style="color: '.trim($matches[1], '').';">'.trim($matches[2], '').'</span>',
fn ($matches) => '<span style="color: '.\trim($matches[1], '').';">'.\trim($matches[2], '').'</span>',
$this->text
);
@@ -349,9 +349,9 @@ class BBCodeConverter
*/
protected function replaceVideo()
{
$this->text = preg_replace_callback('#\[video=.*\]([\W\D\w\s]*?)\[/video\]#iu',
$this->text = \preg_replace_callback('#\[video=.*\]([\W\D\w\s]*?)\[/video\]#iu',
fn ($matches) => '<iframe src="https://www.youtube-nocookie.com/embed/'.trim($matches[1], '').'?rel=0" width="640" height="480" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>',
fn ($matches) => '<iframe src="https://www.youtube-nocookie.com/embed/'.\trim($matches[1], '').'?rel=0" width="640" height="480" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>',
$this->text
);
@@ -362,9 +362,9 @@ class BBCodeConverter
*/
protected function replaceYoutube()
{
$this->text = preg_replace_callback('#\[youtube\]([\W\D\w\s]*?)\[/youtube\]#iu',
$this->text = \preg_replace_callback('#\[youtube\]([\W\D\w\s]*?)\[/youtube\]#iu',
fn ($matches) => '<iframe src="https://www.youtube-nocookie.com/embed/'.trim($matches[1], '').'?rel=0" width="640" height="480" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>',
fn ($matches) => '<iframe src="https://www.youtube-nocookie.com/embed/'.\trim($matches[1], '').'?rel=0" width="640" height="480" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>',
$this->text
);
@@ -375,9 +375,9 @@ class BBCodeConverter
*/
protected function replaceAlert()
{
$this->text = preg_replace_callback('#\[alert\]([\W\D\w\s]*?)\[/alert\]#iu',
$this->text = \preg_replace_callback('#\[alert\]([\W\D\w\s]*?)\[/alert\]#iu',
fn ($matches) => '<div class="decoda-alert">'.trim($matches[1], '').'</div>',
fn ($matches) => '<div class="decoda-alert">'.\trim($matches[1], '').'</div>',
$this->text
);
@@ -388,9 +388,9 @@ class BBCodeConverter
*/
protected function replaceNote()
{
$this->text = preg_replace_callback('#\[note\]([\W\D\w\s]*?)\[/note\]#iu',
$this->text = \preg_replace_callback('#\[note\]([\W\D\w\s]*?)\[/note\]#iu',
fn ($matches) => '<div class="decoda-note">'.trim($matches[1], '').'</div>',
fn ($matches) => '<div class="decoda-note">'.\trim($matches[1], '').'</div>',
$this->text
);

View File

@@ -82,7 +82,8 @@ class BackupEncryption
{
if ($engine == 'ZipArchive' && isset($this->zipArchiveOptions[$type])) {
return $this->zipArchiveOptions[$type];
} elseif ($engine == 'ZipFile' && isset($this->zipFileOptions[$type])) {
}
if ($engine == 'ZipFile' && isset($this->zipFileOptions[$type])) {
return $this->zipFileOptions[$type];
}

View File

@@ -36,48 +36,48 @@ class BackupPassword
/**
* Read the .zip, apply password and encryption, then rewrite the file.
*
* @param \App\Helpers\BackupEncryption $encryption
* @param string $path the path to the .zip-file
* @param \App\Helpers\BackupEncryption $backupEncryption
* @param string $path the path to the .zip-file
*
* @throws \PhpZip\Exception\ZipException
*/
public function __construct(BackupEncryption $encryption, string $path)
public function __construct(BackupEncryption $backupEncryption, string $path)
{
$this->password = config('backup.security.password');
$this->password = \config('backup.security.password');
if (! $this->password) {
return $this->path = $path;
}
// If ZipArchive is enabled
if (class_exists('ZipArchive') && in_array('setEncryptionIndex', get_class_methods('ZipArchive'))) {
consoleOutput()->info('Applying password and encryption to zip using ZipArchive...');
$this->makeZipArchive($encryption, $path);
if (\class_exists('ZipArchive') && \in_array('setEncryptionIndex', \get_class_methods('ZipArchive'))) {
\consoleOutput()->info('Applying password and encryption to zip using ZipArchive...');
$this->makeZipArchive($backupEncryption, $path);
}
// Fall back on PHP-driven ZipFile
else {
consoleOutput()->info('Applying password and encryption to zip using ZipFile...');
$this->makeZipFile($encryption, $path);
\consoleOutput()->info('Applying password and encryption to zip using ZipFile...');
$this->makeZipFile($backupEncryption, $path);
}
consoleOutput()->info('Successfully applied password and encryption to zip.');
\consoleOutput()->info('Successfully applied password and encryption to zip.');
}
/**
* Use native PHP ZipArchive.
*
* @param \App\Helpers\BackupEncryption $encryption
* @param \App\Helpers\BackupEncryption $backupEncryption
* @param string $path
*
* @throws \Exception
*
* @return void
*/
protected function makeZipArchive(BackupEncryption $encryption, string $path): void
protected function makeZipArchive(BackupEncryption $backupEncryption, string $path): void
{
$encryptionConstant = $encryption->getEncryptionConstant(
config('backup.security.encryption'),
$encryptionConstant = $backupEncryption->getEncryptionConstant(
\config('backup.security.encryption'),
'ZipArchive'
);
@@ -97,16 +97,17 @@ class BackupPassword
/**
* Use PhpZip\ZipFile-package to create the zip.
*
* @param \App\Helpers\BackupEncryption $encryption
* @param \App\Helpers\BackupEncryption $backupEncryption
* @param string $path
*
* @throws \PhpZip\Exception\ZipException
*
* @return void
*/
protected function makeZipFile(BackupEncryption $encryption, string $path): void
protected function makeZipFile(BackupEncryption $backupEncryption, string $path): void
{
$encryptionConstant = $encryption->getEncryptionConstant(
config('backup.security.encryption'),
$encryptionConstant = $backupEncryption->getEncryptionConstant(
\config('backup.security.encryption'),
'ZipFile'
);

View File

@@ -277,13 +277,13 @@ class Bbcode
'spoiler' => [
'pattern' => '/\[spoiler\](.*?)\[\/spoiler\]/s',
'replace' => '<details class="label label-primary"><summary>Spoiler</summary><pre><code>$1</code></pre></details>',
'replace' => '<details class="label label-primary"><summary>Spoiler</summary><pre><code><div style="text-align:left;">$1</div></code></pre></details>',
'content' => '$1',
],
'named-spoiler' => [
'pattern' => '/\[spoiler\=(.*?)\](.*?)\[\/spoiler\]/s',
'replace' => '<details class="label label-primary"><summary>$1</summary><pre><code>$2</code></pre></details>',
'replace' => '<details class="label label-primary"><summary>$1</summary><pre><code><div style="text-align:left;">$2</div></code></pre></details>',
'content' => '$1',
],
];
@@ -344,8 +344,8 @@ class Bbcode
*/
protected function searchAndReplace($pattern, $replace, $source)
{
while (preg_match($pattern, $source)) {
$source = preg_replace($pattern, $replace, $source);
while (\preg_match($pattern, $source)) {
$source = \preg_replace($pattern, $replace, $source);
}
return $source;

53
app/Helpers/Bencode.php Executable file → Normal file
View File

@@ -19,7 +19,7 @@ class Bencode
{
public static function parse_integer($s, &$pos)
{
$len = strlen($s);
$len = \strlen($s);
if ($len === 0 || $s[$pos] != 'i') {
return;
}
@@ -27,7 +27,7 @@ class Bencode
$result = '';
while ($pos < $len && $s[$pos] != 'e') {
if (is_numeric($s[$pos]) || $s[$pos] = '-') {
if (\is_numeric($s[$pos]) || $s[$pos] = '-') {
$result .= $s[$pos];
} else {
// We have an invalid character in the string.
@@ -50,11 +50,11 @@ class Bencode
public static function parse_string($s, &$pos)
{
$len = strlen($s);
$len = \strlen($s);
$length_str = '';
while ($pos < $len && $s[$pos] != ':') {
if (is_numeric($s[$pos])) {
if (\is_numeric($s[$pos])) {
$length_str .= $s[$pos];
} else {
// Non-numeric character, we return null in this case.
@@ -91,7 +91,7 @@ class Bencode
public static function bdecode($s, &$pos = 0)
{
$len = strlen($s);
$len = \strlen($s);
if ($pos >= $len) {
return;
}
@@ -100,20 +100,20 @@ class Bencode
if ($c == 'i') {
return self::parse_integer($s, $pos);
}
if (is_numeric($c)) {
if (\is_numeric($c)) {
return self::parse_string($s, $pos);
} elseif ($c == 'd') {
}
if ($c == 'd') {
$dict = [];
$pos++;
while ($pos < $len && $s[$pos] != 'e') {
$key = self::bdecode($s, $pos);
$value = self::bdecode($s, $pos);
if (is_null($key) || is_null($value)) {
if (\is_null($key) || \is_null($value)) {
return;
}
$dict[$key] = $value;
}
if ($pos >= $len) {
// We need a end marker here
return;
@@ -126,7 +126,7 @@ class Bencode
$pos++;
while ($pos < $len && $s[$pos] != 'e') {
$next = self::bdecode($s, $pos);
if (! is_null($next)) {
if (! \is_null($next)) {
$list[] = $next;
} else {
return;
@@ -145,12 +145,12 @@ class Bencode
public static function bencode($d)
{
if (is_array($d)) {
if (\is_array($d)) {
$ret = 'l';
$is_dict = false;
if (! isset($d['isDct'])) {
foreach (array_keys($d) as $key) {
if (! is_int($key)) {
foreach (\array_keys($d) as $key) {
if (! \is_int($key)) {
$is_dict = true;
break;
@@ -163,17 +163,17 @@ class Bencode
if ($is_dict) {
$ret = 'd';
// this is required by the specs, and BitTornado actualy chokes on unsorted dictionaries
ksort($d, SORT_STRING);
\ksort($d, SORT_STRING);
}
foreach ($d as $key => $value) {
if ($is_dict) {
$ret .= strlen($key).':'.$key;
$ret .= \strlen($key).':'.$key;
}
if (is_int($value) || is_float($value)) {
$ret .= sprintf('i%de', $value);
} elseif (is_string($value)) {
$ret .= strlen($value).':'.$value;
if (\is_int($value) || \is_float($value)) {
$ret .= \sprintf('i%de', $value);
} elseif (\is_string($value)) {
$ret .= \strlen($value).':'.$value;
} else {
$ret .= self::bencode($value);
}
@@ -181,23 +181,24 @@ class Bencode
return $ret.'e';
}
if (is_string($d)) {
return strlen($d).':'.$d;
} elseif (is_int($d) || is_float($d)) {
return sprintf('i%de', $d);
if (\is_string($d)) {
return \strlen($d).':'.$d;
}
if (\is_int($d) || \is_float($d)) {
return \sprintf('i%de', $d);
}
}
public static function bdecode_file($filename)
{
$f = file_get_contents($filename, FILE_BINARY);
$f = \file_get_contents($filename, FILE_BINARY);
return self::bdecode($f);
}
public static function get_infohash($t)
{
return sha1(self::bencode($t['info']));
return \sha1(self::bencode($t['info']));
}
public static function get_meta($t)
@@ -207,7 +208,7 @@ class Bencode
$count = 0;
// Multifile
if (isset($t['info']['files']) && is_array($t['info']['files'])) {
if (isset($t['info']['files']) && \is_array($t['info']['files'])) {
foreach ($t['info']['files'] as $file) {
$count++;
$size += $file['length'];

View File

@@ -19,19 +19,19 @@ class EmailBlacklistUpdater
{
public static function update()
{
$url = config('email-blacklist.source');
$url = \config('email-blacklist.source');
if ($url === null) {
return false;
}
// Define parameters for the cache
$key = config('email-blacklist.cache-key');
$key = \config('email-blacklist.cache-key');
$duration = Carbon::now()->addMonth();
$domains = json_decode(file_get_contents($url), true);
$count = count($domains);
$domains = \json_decode(\file_get_contents($url), true);
$count = is_countable($domains) ? \count($domains) : 0;
// Retrieve blacklisted domains
cache()->put($key, $domains, $duration);
\cache()->put($key, $domains, $duration);
return $count;
}

View File

@@ -13,7 +13,7 @@
namespace App\Helpers;
use Crypt;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use Illuminate\Validation\Validator;
@@ -28,23 +28,23 @@ class HiddenCaptcha
*/
public static function render($mustBeEmptyField = '_username')
{
$ts = time();
$ts = \time();
$random = Str::random(16);
// Generate the token
$token = [
'timestamp' => $ts,
'session_id' => session()->getId(),
'ip' => request()->ip(),
'user_agent' => request()->header('User-Agent'),
'session_id' => \session()->getId(),
'ip' => \request()->ip(),
'user_agent' => \request()->header('User-Agent'),
'random_field_name' => $random,
'must_be_empty' => $mustBeEmptyField,
];
// Encrypt the token
$token = Crypt::encrypt(serialize($token));
$token = Crypt::encrypt(\serialize($token));
return (string) view('partials.captcha', ['mustBeEmptyField' => $mustBeEmptyField, 'ts' => $ts, 'random' => $random, 'token' => $token]);
return (string) \view('partials.captcha', ['mustBeEmptyField' => $mustBeEmptyField, 'ts' => $ts, 'random' => $random, 'token' => $token]);
}
/**
@@ -66,12 +66,12 @@ class HiddenCaptcha
}
// Hidden "must be empty" field check
if (! array_key_exists($token['must_be_empty'], $formData) || ! empty($formData[$token['must_be_empty']])) {
if (! \array_key_exists($token['must_be_empty'], $formData) || ! empty($formData[$token['must_be_empty']])) {
return false;
}
// Check time limits
$now = time();
$now = \time();
if ($now - $token['timestamp'] < $minLimit || $now - $token['timestamp'] > $maxLimit) {
return false;
}
@@ -83,7 +83,7 @@ class HiddenCaptcha
// Check if the random field value is similar to the token value
$randomField = $formData[$token['random_field_name']];
if (! ctype_digit($randomField) || $token['timestamp'] != $randomField) {
if (! \ctype_digit($randomField) || $token['timestamp'] != $randomField) {
return false;
}
@@ -107,10 +107,10 @@ class HiddenCaptcha
return false;
}
$token = @unserialize($token);
$token = @\unserialize($token);
// Token is null or unserializable
if (! $token || ! is_array($token) || empty($token)) {
if (! $token || ! \is_array($token) || empty($token)) {
return false;
}
@@ -118,9 +118,9 @@ class HiddenCaptcha
if (empty($token['session_id']) ||
empty($token['ip']) ||
empty($token['user_agent']) ||
$token['session_id'] !== session()->getId() ||
$token['ip'] !== request()->ip() ||
$token['user_agent'] !== request()->header('User-Agent')
$token['session_id'] !== \session()->getId() ||
$token['ip'] !== \request()->ip() ||
$token['user_agent'] !== \request()->header('User-Agent')
) {
return false;
}

View File

@@ -27,22 +27,22 @@ class LanguageCensor
protected static function isSpecial($c)
{
return strpos(self::SPECIAL_CHARS, $c) !== false;
return \strpos(self::SPECIAL_CHARS, $c) !== false;
}
protected static function matchWordIndexes($string, $word)
{
$result = [];
$length = strlen($word);
$string_length = strlen($string);
$pos = stripos($string, $word, 0);
$length = \strlen($word);
$string_length = \strlen($string);
$pos = \stripos($string, $word, 0);
while ($pos !== false) {
$prev = ($pos === 0) ? ' ' : $string[$pos - 1];
$last = ($pos + $length) < $string_length ? $string[$pos + $length] : ' ';
if (self::isSpecial($prev) && self::isSpecial($last)) {
$result[] = $pos;
}
$pos = stripos($string, $word, $pos + $length);
$pos = \stripos($string, $word, $pos + $length);
}
return $result;
@@ -57,18 +57,18 @@ class LanguageCensor
*/
public static function censor($source)
{
$redactArray = config('censor.redact', []);
$redactArray = \config('censor.redact', []);
foreach ($redactArray as $word) {
$result = '';
$length = strlen($source);
$word_length = strlen($word);
assert($word_length > 0);
$length = \strlen($source);
$word_length = \strlen($word);
\assert($word_length > 0);
$indexes = self::matchWordIndexes($source, $word);
$ignore = 0;
for ($i = 0; $i < $length; $i++) {
if ((is_countable($indexes) ? count($indexes) : 0) > 0 && $indexes[0] == $i) {
$match = substr($source, $indexes[0], $word_length);
$result .= sprintf("<span class='censor'>%s</span>", $match);
if ((\is_countable($indexes) ? \count($indexes) : 0) > 0 && $indexes[0] == $i) {
$match = \substr($source, $indexes[0], $word_length);
$result .= \sprintf("<span class='censor'>%s</span>", $match);
$ignore = $word_length - 1;
} elseif ($ignore > 0) {
$ignore--;
@@ -79,9 +79,9 @@ class LanguageCensor
$source = $result;
}
$replaceDict = config('censor.replace', []);
$replaceDict = \config('censor.replace', []);
foreach ($replaceDict as $word => $replacement) {
$source = str_ireplace($word, $replacement, $source);
$source = \str_ireplace($word, $replacement, $source);
}
return $source;

View File

@@ -22,8 +22,8 @@ class Linkify
public function linky($text)
{
if (preg_match(self::REG_EX_URL, $text, $url)) {
return preg_replace(self::REG_EX_URL, sprintf("<a href='%s'>%s</a> ", $url[0], $url[0]), $text);
if (\preg_match(self::REG_EX_URL, $text, $url)) {
return \preg_replace(self::REG_EX_URL, \sprintf("<a href='%s'>%s</a> ", $url[0], $url[0]), $text);
}
return $text;

View File

@@ -26,19 +26,19 @@ class Markdown
$this->DefinitionData = [];
// standardize line breaks
$text = str_replace(["\r\n", "\r"], "\n", $text);
$text = \str_replace(["\r\n", "\r"], "\n", $text);
// remove surrounding line breaks
$text = trim($text, "\n");
$text = \trim($text, "\n");
// split text into lines
$lines = explode("\n", $text);
$lines = \explode("\n", $text);
// iterate through lines to identify blocks
$markup = $this->lines($lines);
// trim line breaks
$markup = trim($markup, "\n");
$markup = \trim($markup, "\n");
return $markup;
}
@@ -145,7 +145,7 @@ class Markdown
$CurrentBlock = null;
foreach ($lines as $line) {
if (rtrim($line) === '') {
if (\rtrim($line) === '') {
if (isset($CurrentBlock)) {
$CurrentBlock['interrupted'] = true;
}
@@ -153,17 +153,17 @@ class Markdown
continue;
}
if (strpos($line, "\t") !== false) {
$parts = explode("\t", $line);
if (\strpos($line, "\t") !== false) {
$parts = \explode("\t", $line);
$line = $parts[0];
unset($parts[0]);
foreach ($parts as $part) {
$shortage = 4 - mb_strlen($line, 'utf-8') % 4;
$shortage = 4 - \mb_strlen($line, 'utf-8') % 4;
$line .= str_repeat(' ', $shortage);
$line .= \str_repeat(' ', $shortage);
$line .= $part;
}
}
@@ -174,7 +174,7 @@ class Markdown
$indent++;
}
$text = $indent > 0 ? substr($line, $indent) : $line;
$text = $indent > 0 ? \substr($line, $indent) : $line;
// ~
@@ -279,12 +279,12 @@ class Markdown
protected function isBlockContinuable($Type)
{
return method_exists($this, 'block'.$Type.'Continue');
return \method_exists($this, 'block'.$Type.'Continue');
}
protected function isBlockCompletable($Type)
{
return method_exists($this, 'block'.$Type.'Complete');
return \method_exists($this, 'block'.$Type.'Complete');
}
//
@@ -297,7 +297,7 @@ class Markdown
}
if ($Line['indent'] >= 4) {
$text = substr($Line['body'], 4);
$text = \substr($Line['body'], 4);
return [
'element' => [
@@ -323,7 +323,7 @@ class Markdown
$Block['element']['text']['text'] .= "\n";
$text = substr($Line['body'], 4);
$text = \substr($Line['body'], 4);
$Block['element']['text']['text'] .= $text;
@@ -354,7 +354,7 @@ class Markdown
'markup' => $Line['body'],
];
if (preg_match('#-->$#', $Line['text'])) {
if (\preg_match('#-->$#', $Line['text'])) {
$Block['closed'] = true;
}
@@ -370,7 +370,7 @@ class Markdown
$Block['markup'] .= "\n".$Line['body'];
if (preg_match('#-->$#', $Line['text'])) {
if (\preg_match('#-->$#', $Line['text'])) {
$Block['closed'] = true;
}
@@ -382,7 +382,7 @@ class Markdown
protected function blockFencedCode($Line)
{
if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([^`]+)?[ ]*$/', $Line['text'], $matches)) {
if (\preg_match('/^['.$Line['text'][0].']{3,}[ ]*([^`]+)?[ ]*$/', $Line['text'], $matches)) {
$Element = [
'name' => 'code',
'text' => '',
@@ -419,8 +419,8 @@ class Markdown
unset($Block['interrupted']);
}
if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text'])) {
$Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
if (\preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text'])) {
$Block['element']['text']['text'] = \substr($Block['element']['text']['text'], 1);
$Block['complete'] = true;
@@ -457,11 +457,11 @@ class Markdown
return;
}
$text = trim($Line['text'], '# ');
$text = \trim($Line['text'], '# ');
return [
'element' => [
'name' => 'h'.min(6, $level),
'name' => 'h'.\min(6, $level),
'text' => $text,
'handler' => 'line',
],
@@ -476,7 +476,7 @@ class Markdown
{
[$name, $pattern] = $Line['text'][0] <= '-' ? ['ul', '[*+-]'] : ['ol', '[0-9]+[.]'];
if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches)) {
if (\preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches)) {
$Block = [
'indent' => $Line['indent'],
'pattern' => $pattern,
@@ -487,7 +487,7 @@ class Markdown
];
if ($name === 'ol') {
$listStart = stristr($matches[0], '.', true);
$listStart = \stristr($matches[0], '.', true);
if ($listStart !== '1') {
$Block['element']['attributes'] = ['start' => $listStart];
@@ -510,7 +510,7 @@ class Markdown
protected function blockListContinue($Line, array $Block)
{
if ($Block['indent'] === $Line['indent'] && preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches)) {
if ($Block['indent'] === $Line['indent'] && \preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches)) {
if (isset($Block['interrupted'])) {
$Block['li']['text'][] = '';
@@ -541,7 +541,7 @@ class Markdown
}
if (! isset($Block['interrupted'])) {
$text = preg_replace('#^[ ]{0,4}#', '', $Line['body']);
$text = \preg_replace('#^[ ]{0,4}#', '', $Line['body']);
$Block['li']['text'][] = $text;
@@ -551,7 +551,7 @@ class Markdown
if ($Line['indent'] > 0) {
$Block['li']['text'][] = '';
$text = preg_replace('#^[ ]{0,4}#', '', $Line['body']);
$text = \preg_replace('#^[ ]{0,4}#', '', $Line['body']);
$Block['li']['text'][] = $text;
@@ -565,7 +565,7 @@ class Markdown
{
if (isset($Block['loose'])) {
foreach ($Block['element']['text'] as &$li) {
if (end($li['text']) !== '') {
if (\end($li['text']) !== '') {
$li['text'][] = '';
}
}
@@ -579,7 +579,7 @@ class Markdown
protected function blockQuote($Line)
{
if (preg_match('#^>[ ]?(.*)#', $Line['text'], $matches)) {
if (\preg_match('#^>[ ]?(.*)#', $Line['text'], $matches)) {
return [
'element' => [
'name' => 'blockquote',
@@ -592,7 +592,7 @@ class Markdown
protected function blockQuoteContinue($Line, array $Block)
{
if ($Line['text'][0] === '>' && preg_match('#^>[ ]?(.*)#', $Line['text'], $matches)) {
if ($Line['text'][0] === '>' && \preg_match('#^>[ ]?(.*)#', $Line['text'], $matches)) {
if (isset($Block['interrupted'])) {
$Block['element']['text'][] = '';
@@ -616,7 +616,7 @@ class Markdown
protected function blockRule($Line)
{
if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text'])) {
if (\preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text'])) {
return [
'element' => [
'name' => 'hr',
@@ -634,7 +634,7 @@ class Markdown
return;
}
if (rtrim($Line['text'], $Line['text'][0]) === '') {
if (\rtrim($Line['text'], $Line['text'][0]) === '') {
$Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
return $Block;
@@ -650,10 +650,10 @@ class Markdown
return;
}
if (preg_match('/^<(\w[\w-]*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) {
$element = strtolower($matches[1]);
if (\preg_match('/^<(\w[\w-]*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) {
$element = \strtolower($matches[1]);
if (in_array($element, $this->textLevelElements)) {
if (\in_array($element, $this->textLevelElements)) {
return;
}
@@ -663,22 +663,22 @@ class Markdown
'markup' => $Line['text'],
];
$length = strlen($matches[0]);
$length = \strlen($matches[0]);
$remainder = substr($Line['text'], $length);
$remainder = \substr($Line['text'], $length);
if (trim($remainder) === '') {
if (isset($matches[2]) || in_array($matches[1], $this->voidElements)) {
if (\trim($remainder) === '') {
if (isset($matches[2]) || \in_array($matches[1], $this->voidElements)) {
$Block['closed'] = true;
$Block['void'] = true;
}
} else {
if (isset($matches[2]) || in_array($matches[1], $this->voidElements)) {
if (isset($matches[2]) || \in_array($matches[1], $this->voidElements)) {
return;
}
if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) {
if (\preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) {
$Block['closed'] = true;
}
}
@@ -693,11 +693,11 @@ class Markdown
return;
}
if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) { // open
if (\preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) { // open
$Block['depth']++;
}
if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) { // close
if (\preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) { // close
if ($Block['depth'] > 0) {
$Block['depth']--;
} else {
@@ -721,8 +721,8 @@ class Markdown
protected function blockReference($Line)
{
if (preg_match('#^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$#', $Line['text'], $matches)) {
$id = strtolower($matches[1]);
if (\preg_match('#^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$#', $Line['text'], $matches)) {
$id = \strtolower($matches[1]);
$Data = [
'url' => $matches[2],
@@ -750,18 +750,18 @@ class Markdown
return;
}
if (strpos($Block['element']['text'], '|') !== false && rtrim($Line['text'], ' -:|') === '') {
if (\strpos($Block['element']['text'], '|') !== false && \rtrim($Line['text'], ' -:|') === '') {
$alignments = [];
$divider = $Line['text'];
$divider = trim($divider);
$divider = trim($divider, '|');
$divider = \trim($divider);
$divider = \trim($divider, '|');
$dividerCells = explode('|', $divider);
$dividerCells = \explode('|', $divider);
foreach ($dividerCells as $dividerCell) {
$dividerCell = trim($dividerCell);
$dividerCell = \trim($dividerCell);
if ($dividerCell === '') {
continue;
@@ -773,7 +773,7 @@ class Markdown
$alignment = 'left';
}
if (substr($dividerCell, -1) === ':') {
if (\substr($dividerCell, -1) === ':') {
$alignment = $alignment === 'left' ? 'center' : 'right';
}
@@ -786,13 +786,13 @@ class Markdown
$header = $Block['element']['text'];
$header = trim($header);
$header = trim($header, '|');
$header = \trim($header);
$header = \trim($header, '|');
$headerCells = explode('|', $header);
$headerCells = \explode('|', $header);
foreach ($headerCells as $index => $headerCell) {
$headerCell = trim($headerCell);
$headerCell = \trim($headerCell);
$HeaderElement = [
'name' => 'th',
@@ -849,18 +849,18 @@ class Markdown
return;
}
if ($Line['text'][0] === '|' || strpos($Line['text'], '|')) {
if ($Line['text'][0] === '|' || \strpos($Line['text'], '|')) {
$Elements = [];
$row = $Line['text'];
$row = trim($row);
$row = trim($row, '|');
$row = \trim($row);
$row = \trim($row, '|');
preg_match_all('#(?:(\\\[|])|[^|`]|`[^`]+`|`)+#', $row, $matches);
\preg_match_all('#(?:(\\\[|])|[^|`]|`[^`]+`|`)+#', $row, $matches);
foreach ($matches[0] as $index => $cell) {
$cell = trim($cell);
$cell = \trim($cell);
$Element = [
'name' => 'td',
@@ -937,17 +937,17 @@ class Markdown
// $excerpt is based on the first occurrence of a marker
while ($excerpt = strpbrk($text, $this->inlineMarkerList)) {
while ($excerpt = \strpbrk($text, $this->inlineMarkerList)) {
$marker = $excerpt[0];
$markerPosition = strpos($text, $marker);
$markerPosition = \strpos($text, $marker);
$Excerpt = ['text' => $excerpt, 'context' => $text];
foreach ($this->InlineTypes[$marker] as $inlineType) {
// check to see if the current inline type is nestable in the current context
if (! empty($nonNestables) && in_array($inlineType, $nonNestables)) {
if (! empty($nonNestables) && \in_array($inlineType, $nonNestables)) {
continue;
}
@@ -976,7 +976,7 @@ class Markdown
}
// the text that comes before the inline
$unmarkedText = substr($text, 0, $Inline['position']);
$unmarkedText = \substr($text, 0, $Inline['position']);
// compile the unmarked text
$markup .= $this->unmarkedText($unmarkedText);
@@ -985,18 +985,18 @@ class Markdown
$markup .= $Inline['markup'] ?? $this->element($Inline['element']);
// remove the examined text
$text = substr($text, $Inline['position'] + $Inline['extent']);
$text = \substr($text, $Inline['position'] + $Inline['extent']);
continue 2;
}
// the marker does not belong to an inline
$unmarkedText = substr($text, 0, $markerPosition + 1);
$unmarkedText = \substr($text, 0, $markerPosition + 1);
$markup .= $this->unmarkedText($unmarkedText);
$text = substr($text, $markerPosition + 1);
$text = \substr($text, $markerPosition + 1);
}
return $markup.$this->unmarkedText($text);
@@ -1010,12 +1010,12 @@ class Markdown
{
$marker = $Excerpt['text'][0];
if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches)) {
if (\preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches)) {
$text = $matches[2];
$text = preg_replace("/[ ]*\n/", ' ', $text);
$text = \preg_replace("/[ ]*\n/", ' ', $text);
return [
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
'element' => [
'name' => 'code',
'text' => $text,
@@ -1026,7 +1026,7 @@ class Markdown
protected function inlineEmailTag($Excerpt)
{
if (strpos($Excerpt['text'], '>') !== false && preg_match('#^<((mailto:)?\S+?@\S+?)>#i', $Excerpt['text'], $matches)) {
if (\strpos($Excerpt['text'], '>') !== false && \preg_match('#^<((mailto:)?\S+?@\S+?)>#i', $Excerpt['text'], $matches)) {
$url = $matches[1];
if (! isset($matches[2])) {
@@ -1034,7 +1034,7 @@ class Markdown
}
return [
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
'element' => [
'name' => 'a',
'text' => $matches[1],
@@ -1054,16 +1054,16 @@ class Markdown
$marker = $Excerpt['text'][0];
if ($Excerpt['text'][1] === $marker && preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) {
if ($Excerpt['text'][1] === $marker && \preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) {
$emphasis = 'strong';
} elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) {
} elseif (\preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) {
$emphasis = 'em';
} else {
return;
}
return [
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
'element' => [
'name' => $emphasis,
'handler' => 'line',
@@ -1074,7 +1074,7 @@ class Markdown
protected function inlineEscapeSequence($Excerpt)
{
if (isset($Excerpt['text'][1]) && in_array($Excerpt['text'][1], $this->specialCharacters)) {
if (isset($Excerpt['text'][1]) && \in_array($Excerpt['text'][1], $this->specialCharacters)) {
return [
'markup' => $Excerpt['text'][1],
'extent' => 2,
@@ -1088,7 +1088,7 @@ class Markdown
return;
}
$Excerpt['text'] = substr($Excerpt['text'], 1);
$Excerpt['text'] = \substr($Excerpt['text'], 1);
$Link = $this->inlineLink($Excerpt);
@@ -1131,32 +1131,32 @@ class Markdown
$remainder = $Excerpt['text'];
if (preg_match('#\[((?:[^][]++|(?R))*+)\]#', $remainder, $matches)) {
if (\preg_match('#\[((?:[^][]++|(?R))*+)\]#', $remainder, $matches)) {
$Element['text'] = $matches[1];
$extent += strlen($matches[0]);
$extent += \strlen($matches[0]);
$remainder = substr($remainder, $extent);
$remainder = \substr($remainder, $extent);
} else {
return;
}
if (preg_match('#^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]#', $remainder, $matches)) {
if (\preg_match('#^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]#', $remainder, $matches)) {
$Element['attributes']['href'] = $matches[1];
if (isset($matches[2])) {
$Element['attributes']['title'] = substr($matches[2], 1, -1);
$Element['attributes']['title'] = \substr($matches[2], 1, -1);
}
$extent += strlen($matches[0]);
$extent += \strlen($matches[0]);
} else {
if (preg_match('#^\s*\[(.*?)\]#', $remainder, $matches)) {
$definition = strlen($matches[1]) !== 0 ? $matches[1] : $Element['text'];
$definition = strtolower($definition);
if (\preg_match('#^\s*\[(.*?)\]#', $remainder, $matches)) {
$definition = \strlen($matches[1]) !== 0 ? $matches[1] : $Element['text'];
$definition = \strtolower($definition);
$extent += strlen($matches[0]);
$extent += \strlen($matches[0]);
} else {
$definition = strtolower($Element['text']);
$definition = \strtolower($Element['text']);
}
if (! isset($this->DefinitionData['Reference'][$definition])) {
@@ -1177,35 +1177,35 @@ class Markdown
protected function inlineMarkup($Excerpt)
{
if ($this->markupEscaped || $this->safeMode || strpos($Excerpt['text'], '>') === false) {
if ($this->markupEscaped || $this->safeMode || \strpos($Excerpt['text'], '>') === false) {
return;
}
if ($Excerpt['text'][1] === '/' && preg_match('#^<\/\w[\w-]*[ ]*>#s', $Excerpt['text'], $matches)) {
if ($Excerpt['text'][1] === '/' && \preg_match('#^<\/\w[\w-]*[ ]*>#s', $Excerpt['text'], $matches)) {
return [
'markup' => $matches[0],
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
];
}
if ($Excerpt['text'][1] === '!' && preg_match('#^<!---?[^>-](?:-?[^-])*-->#s', $Excerpt['text'], $matches)) {
if ($Excerpt['text'][1] === '!' && \preg_match('#^<!---?[^>-](?:-?[^-])*-->#s', $Excerpt['text'], $matches)) {
return [
'markup' => $matches[0],
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
];
}
if ($Excerpt['text'][1] !== ' ' && preg_match('/^<\w[\w-]*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches)) {
if ($Excerpt['text'][1] !== ' ' && \preg_match('/^<\w[\w-]*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches)) {
return [
'markup' => $matches[0],
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
];
}
}
protected function inlineSpecialCharacter($Excerpt)
{
if ($Excerpt['text'][0] === '&' && ! preg_match('#^&#?\w+;#', $Excerpt['text'])) {
if ($Excerpt['text'][0] === '&' && ! \preg_match('#^&#?\w+;#', $Excerpt['text'])) {
return [
'markup' => '&amp;',
'extent' => 1,
@@ -1226,9 +1226,9 @@ class Markdown
return;
}
if ($Excerpt['text'][1] === '~' && preg_match('#^~~(?=\S)(.+?)(?<=\S)~~#', $Excerpt['text'], $matches)) {
if ($Excerpt['text'][1] === '~' && \preg_match('#^~~(?=\S)(.+?)(?<=\S)~~#', $Excerpt['text'], $matches)) {
return [
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
'element' => [
'name' => 'del',
'text' => $matches[1],
@@ -1244,11 +1244,11 @@ class Markdown
return;
}
if (preg_match('#\bhttps?:[\/]{2}[^\s<]+\b\/*#ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) {
if (\preg_match('#\bhttps?:[\/]{2}[^\s<]+\b\/*#ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) {
$url = $matches[0][0];
return [
'extent' => strlen($matches[0][0]),
'extent' => \strlen($matches[0][0]),
'position' => $matches[0][1],
'element' => [
'name' => 'a',
@@ -1263,11 +1263,11 @@ class Markdown
protected function inlineUrlTag($Excerpt)
{
if (strpos($Excerpt['text'], '>') !== false && preg_match('#^<(\w+:\/{2}[^ >]+)>#i', $Excerpt['text'], $matches)) {
if (\strpos($Excerpt['text'], '>') !== false && \preg_match('#^<(\w+:\/{2}[^ >]+)>#i', $Excerpt['text'], $matches)) {
$url = $matches[1];
return [
'extent' => strlen($matches[0]),
'extent' => \strlen($matches[0]),
'element' => [
'name' => 'a',
'text' => $url,
@@ -1284,11 +1284,11 @@ class Markdown
protected function unmarkedText($text)
{
if ($this->breaksEnabled) {
return preg_replace('#[ ]*\n#', "<br />\n", $text);
return \preg_replace('#[ ]*\n#', "<br />\n", $text);
}
$text = preg_replace('#(?:[ ][ ]+|[ ]*\\\)\n#', "<br />\n", $text);
$text = \preg_replace('#(?:[ ][ ]+|[ ]*\\\)\n#', "<br />\n", $text);
return str_replace(" \n", "\n", $text);
return \str_replace(" \n", "\n", $text);
}
//
@@ -1351,15 +1351,15 @@ class Markdown
{
$markup = $this->lines($lines);
$trimmedMarkup = trim($markup);
$trimmedMarkup = \trim($markup);
if (! in_array('', $lines) && substr($trimmedMarkup, 0, 3) === '<p>') {
if (! \in_array('', $lines) && \substr($trimmedMarkup, 0, 3) === '<p>') {
$markup = $trimmedMarkup;
$markup = substr($markup, 3);
$markup = \substr($markup, 3);
$position = strpos($markup, '</p>');
$position = \strpos($markup, '</p>');
$markup = substr_replace($markup, '', $position, 4);
$markup = \substr_replace($markup, '', $position, 4);
}
return $markup;
@@ -1387,9 +1387,9 @@ class Markdown
}
if (! empty($Element['attributes'])) {
foreach (array_keys($Element['attributes']) as $att) {
foreach (\array_keys($Element['attributes']) as $att) {
// filter out badly parsed attribute
if (! preg_match($goodAttribute, $att)) {
if (! \preg_match($goodAttribute, $att)) {
unset($Element['attributes'][$att]);
}
// dump onevent attribute
@@ -1410,7 +1410,7 @@ class Markdown
}
}
$Element['attributes'][$attribute] = str_replace(':', '%3A', $Element['attributes'][$attribute]);
$Element['attributes'][$attribute] = \str_replace(':', '%3A', $Element['attributes'][$attribute]);
return $Element;
}
@@ -1421,18 +1421,18 @@ class Markdown
protected static function escape($text, $allowQuotes = false)
{
return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8');
return \htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8');
}
protected static function striAtStart($string, $needle)
{
$len = strlen($needle);
$len = \strlen($needle);
if ($len > strlen($string)) {
if ($len > \strlen($string)) {
return false;
}
return strtolower(substr($string, 0, $len)) === strtolower($needle);
return \strtolower(\substr($string, 0, $len)) === \strtolower($needle);
}
public static function instance($name = 'default')
@@ -1441,11 +1441,11 @@ class Markdown
return self::$instances[$name];
}
$instance = new static();
$static = new static();
self::$instances[$name] = $instance;
self::$instances[$name] = $static;
return $instance;
return $static;
}
private static $instances = [];

48
app/Helpers/MediaInfo.php Executable file → Normal file
View File

@@ -37,13 +37,13 @@ class MediaInfo
public function parse($string)
{
$string = trim($string);
$lines = preg_split("/\r\n|\n|\r/", $string);
$string = \trim($string);
$lines = \preg_split("/\r\n|\n|\r/", $string);
$output = [];
foreach ($lines as $line) {
$line = trim($line); // removed strtolower, unnecessary with the i-switch in the regexp (caseless) and adds problems with values; added it in the required places instead.
if (preg_match(self::REGEX_SECTION, $line)) {
$line = \trim($line); // removed strtolower, unnecessary with the i-switch in the regexp (caseless) and adds problems with values; added it in the required places instead.
if (\preg_match(self::REGEX_SECTION, $line)) {
$section = $line;
$output[$section] = [];
}
@@ -52,7 +52,7 @@ class MediaInfo
}
}
if (count($output) > 0) {
if (\count($output) > 0) {
$output = $this->parseSections($output);
}
@@ -63,7 +63,7 @@ class MediaInfo
{
$output = [];
foreach ($sections as $key => $section) {
$key_section = strtolower(explode(' ', $key)[0]);
$key_section = \strtolower(\explode(' ', $key)[0]);
if (! empty($section)) {
if ($key_section === 'general') {
$output[$key_section] = $this->parseProperty($section, $key_section);
@@ -82,13 +82,13 @@ class MediaInfo
foreach ($sections as $info) {
$property = null;
$value = null;
$info = explode(':', $info, 2);
if (count($info) >= 2) {
$property = trim(strtolower($info[0]));
$value = trim($info[1]);
$info = \explode(':', $info, 2);
if (\count($info) >= 2) {
$property = \trim(\strtolower($info[0]));
$value = \trim($info[1]);
}
if ($property && $value) {
switch (strtolower($section)) {
switch (\strtolower($section)) {
case 'general':
switch ($property) {
case 'complete name':
@@ -165,7 +165,7 @@ class MediaInfo
break;
case 'display aspect ratio':
case 'displayaspectratio':
$output['aspect_ratio'] = str_replace('/', ':', $value); // mediainfo sometimes uses / instead of :
$output['aspect_ratio'] = \str_replace('/', ':', $value); // mediainfo sometimes uses / instead of :
break;
case 'bit rate':
case 'bitrate':
@@ -301,8 +301,8 @@ class MediaInfo
public static function stripPath($string)
{
$string = str_replace('\\', '/', $string);
$path_parts = pathinfo($string);
$string = \str_replace('\\', '/', $string);
$path_parts = \pathinfo($string);
return $path_parts['basename'];
}
@@ -310,7 +310,7 @@ class MediaInfo
private function parseFileSize($string)
{
$number = (float) $string;
preg_match('#[KMGTPEZ]#i', $string, $size);
\preg_match('#[KMGTPEZ]#i', $string, $size);
if (! empty($size[0])) {
$number = $this->computerSize($number, $size[0].'b');
}
@@ -320,19 +320,19 @@ class MediaInfo
private function parseBitRate($string)
{
$string = str_replace(' ', '', strtolower($string));
$string = \str_replace(' ', '', \strtolower($string));
return str_replace('kbps', ' kbps', $string);
return \str_replace('kbps', ' kbps', $string);
}
private function parseWidthHeight($string)
{
return str_replace(['pixels', ' '], null, strtolower($string));
return \str_replace(['pixels', ' '], null, \strtolower($string));
}
private function parseAudioChannels($string)
{
return str_ireplace(array_keys(self::REPLACE), self::REPLACE, $string);
return \str_ireplace(\array_keys(self::REPLACE), self::REPLACE, $string);
}
private function formatOutput($data)
@@ -356,7 +356,7 @@ class MediaInfo
$output['general'] = null;
} else {
if (isset($data['general']['format'])) {
$output['general'][] = ucfirst($data['general']['format']);
$output['general'][] = \ucfirst($data['general']['format']);
}
if (isset($data['general']['duration'])) {
$output['general'][] = $data['general']['duration'];
@@ -370,7 +370,7 @@ class MediaInfo
foreach ($data['video'] as $video_element) {
$temp_video_output = [];
if (isset($video_element['format'])) {
$temp_video_output[] = strtoupper($video_element['format']);
$temp_video_output[] = \strtoupper($video_element['format']);
}
if (isset($video_element['width']) && isset($video_element['height'])) {
$temp_video_output[] = $video_element['width'].' x '.$video_element['height'];
@@ -420,7 +420,7 @@ class MediaInfo
$temp_text_output[] = $text_element[$property];
}
}
if (isset($text_element['forced']) && strtolower($text_element['forced']) === 'yes') {
if (isset($text_element['forced']) && \strtolower($text_element['forced']) === 'yes') {
$temp_text_output[] = 'Forced';
}
@@ -442,10 +442,10 @@ class MediaInfo
private function computerSize($number, $size)
{
$bytes = (float) $number;
$size = strtolower($size);
$size = \strtolower($size);
if (isset(self::FACTORS[$size])) {
return (float) number_format($bytes * pow(1_024, self::FACTORS[$size]), 2, '.', '');
return (float) \number_format($bytes * \pow(1_024, self::FACTORS[$size]), 2, '.', '');
}
return $bytes;

View File

@@ -39,7 +39,7 @@ class StringHelper
{
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= self::CHARACTERS[rand(0, strlen(self::CHARACTERS) - 1)];
$string .= self::CHARACTERS[\rand(0, \strlen(self::CHARACTERS) - 1)];
}
return $string;
@@ -47,7 +47,7 @@ class StringHelper
public static function formatBytes($bytes, $precision = 2)
{
$bytes = max($bytes, 0);
$bytes = \max($bytes, 0);
$suffix = 'B';
$value = $bytes;
if ($bytes >= self::PIB) {
@@ -67,7 +67,7 @@ class StringHelper
$value = $bytes / self::KIB;
}
return round($value, $precision).' '.$suffix;
return \round($value, $precision).' '.$suffix;
}
/**
@@ -86,7 +86,7 @@ class StringHelper
$months = 0;
$years = 0;
$seconds = config('hitrun.seedtime') - $seconds;
$seconds = \config('hitrun.seedtime') - $seconds;
if ($seconds == 0) {
return 'N/A';
@@ -115,13 +115,13 @@ class StringHelper
$minutes++;
$seconds -= 60;
}
$years = ($years === 0) ? '' : $years.trans('common.abbrev-years');
$months = ($months === 0) ? '' : $months.trans('common.abbrev-months');
$weeks = ($weeks === 0) ? '' : $weeks.trans('common.abbrev-weeks');
$days = ($days === 0) ? '' : $days.trans('common.abbrev-days');
$hours = ($hours === 0) ? '' : $hours.trans('common.abbrev-hours');
$minutes = ($minutes === 0) ? '' : $minutes.trans('common.abbrev-minutes');
$seconds = ($seconds == 0) ? '' : $seconds.trans('common.abbrev-seconds');
$years = ($years === 0) ? '' : $years.\trans('common.abbrev-years');
$months = ($months === 0) ? '' : $months.\trans('common.abbrev-months');
$weeks = ($weeks === 0) ? '' : $weeks.\trans('common.abbrev-weeks');
$days = ($days === 0) ? '' : $days.\trans('common.abbrev-days');
$hours = ($hours === 0) ? '' : $hours.\trans('common.abbrev-hours');
$minutes = ($minutes === 0) ? '' : $minutes.\trans('common.abbrev-minutes');
$seconds = ($seconds == 0) ? '' : $seconds.\trans('common.abbrev-seconds');
return $years.$months.$weeks.$days.$hours.$minutes.$seconds;
}
@@ -169,13 +169,13 @@ class StringHelper
$minutes++;
$seconds -= 60;
}
$years = ($years === 0) ? '' : $years.trans('common.abbrev-years');
$months = ($months === 0) ? '' : $months.trans('common.abbrev-months');
$weeks = ($weeks === 0) ? '' : $weeks.trans('common.abbrev-weeks');
$days = ($days === 0) ? '' : $days.trans('common.abbrev-days');
$hours = ($hours === 0) ? '' : $hours.trans('common.abbrev-hours');
$minutes = ($minutes === 0) ? '' : $minutes.trans('common.abbrev-minutes');
$seconds = ($seconds == 0) ? '' : $seconds.trans('common.abbrev-seconds');
$years = ($years === 0) ? '' : $years.\trans('common.abbrev-years');
$months = ($months === 0) ? '' : $months.\trans('common.abbrev-months');
$weeks = ($weeks === 0) ? '' : $weeks.\trans('common.abbrev-weeks');
$days = ($days === 0) ? '' : $days.\trans('common.abbrev-days');
$hours = ($hours === 0) ? '' : $hours.\trans('common.abbrev-hours');
$minutes = ($minutes === 0) ? '' : $minutes.\trans('common.abbrev-minutes');
$seconds = ($seconds == 0) ? '' : $seconds.\trans('common.abbrev-seconds');
return $years.$months.$weeks.$days.$hours.$minutes.$seconds;
}

View File

@@ -35,18 +35,18 @@ class SystemInformation
public function avg()
{
if (is_readable('/proc/loadavg')) {
return (float) file_get_contents('/proc/loadavg');
if (\is_readable('/proc/loadavg')) {
return (float) \file_get_contents('/proc/loadavg');
}
}
public function memory()
{
if (is_readable('/proc/meminfo')) {
$content = file_get_contents('/proc/meminfo');
preg_match('#^MemTotal: \s*(\d*)#m', $content, $matches);
if (\is_readable('/proc/meminfo')) {
$content = \file_get_contents('/proc/meminfo');
\preg_match('#^MemTotal: \s*(\d*)#m', $content, $matches);
$total = $matches[1] * 1_024;
preg_match('#^MemFree: \s*(\d*)#m', $content, $matches);
\preg_match('#^MemFree: \s*(\d*)#m', $content, $matches);
$free = $matches[1] * 1_024;
//preg_match('/^MemAvailable: \s*(\d*)/m', $content, $matches);
//$used = $this->formatBytes($matches[1] * 1024);
@@ -67,20 +67,20 @@ class SystemInformation
protected function formatBytes($bytes, $precision = 2)
{
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1_024));
$pow = min($pow, count(self::UNITS) - 1);
$bytes = \max($bytes, 0);
$pow = \floor(($bytes ? \log($bytes) : 0) / \log(1_024));
$pow = \min($pow, (is_countable(self::UNITS) ? \count(self::UNITS) : 0) - 1);
// Uncomment one of the following alternatives
$bytes /= pow(1_024, $pow);
$bytes /= \pow(1_024, $pow);
// $bytes /= (1 << (10 * $pow));
return round($bytes, $precision).' '.self::UNITS[$pow];
return \round($bytes, $precision).' '.self::UNITS[$pow];
}
public function disk()
{
$total = disk_total_space(base_path());
$free = disk_free_space(base_path());
$total = \disk_total_space(\base_path());
$free = \disk_free_space(\base_path());
return [
'total' => $this->formatBytes($total),
@@ -91,8 +91,8 @@ class SystemInformation
public function uptime()
{
if (is_readable('/proc/uptime')) {
return (float) file_get_contents('/proc/uptime');
if (\is_readable('/proc/uptime')) {
return (float) \file_get_contents('/proc/uptime');
}
}
@@ -104,16 +104,16 @@ class SystemInformation
public function basic()
{
return [
'os' => php_uname('s'),
'php' => phpversion(),
'os' => \php_uname('s'),
'php' => \phpversion(),
'database' => $this->getDatabase(),
'laravel' => app()->version(),
'laravel' => \app()->version(),
];
}
private function getDatabase()
{
if (! in_array(config('database.default'), self::KNOWN_DATABASES)) {
if (! \in_array(\config('database.default'), self::KNOWN_DATABASES)) {
return 'Unkown';
}
$results = DB::select(DB::raw('select version()'));
@@ -130,22 +130,22 @@ class SystemInformation
{
return [
[
'directory' => base_path('bootstrap/cache'),
'directory' => \base_path('bootstrap/cache'),
'permission' => $this->getDirectoryPermission('bootstrap/cache'),
'recommended' => '0775',
],
[
'directory' => base_path('public'),
'directory' => \base_path('public'),
'permission' => $this->getDirectoryPermission('public'),
'recommended' => '0775',
],
[
'directory' => base_path('storage'),
'directory' => \base_path('storage'),
'permission' => $this->getDirectoryPermission('storage'),
'recommended' => '0775',
],
[
'directory' => base_path('vendor'),
'directory' => \base_path('vendor'),
'permission' => $this->getDirectoryPermission('vendor'),
'recommended' => '0775',
],
@@ -162,9 +162,9 @@ class SystemInformation
public function getDirectoryPermission($path)
{
try {
return substr(sprintf('%o', fileperms(base_path($path))), -4);
return \substr(\sprintf('%o', \fileperms(\base_path($path))), -4);
} catch (\Exception $ex) {
return trans('site.error');
return \trans('site.error');
}
}
}

View File

@@ -32,22 +32,26 @@ use App\Models\Torrent;
use App\Models\User;
use App\Models\Wish;
use App\Notifications\NewUpload;
use Carbon\Carbon;
class TorrentHelper
{
public static function approveHelper($id)
{
$appurl = config('app.url');
$appname = config('app.name');
$appurl = \config('app.url');
$appname = \config('app.name');
Torrent::approve($id);
$torrent = Torrent::with('uploader')->withAnyStatus()->where('id', '=', $id)->first();
$torrent->created_at = Carbon::now();
$torrent->save();
$uploader = $torrent->uploader;
$wishes = Wish::where('imdb', '=', 'tt'.$torrent->imdb)->whereNull('source')->get();
if ($wishes) {
foreach ($wishes as $wish) {
$wish->source = sprintf('%s/torrents/%s', $appurl, $torrent->id);
$wish->source = \sprintf('%s/torrents/%s', $appurl, $torrent->id);
$wish->save();
// Send Private Message
@@ -55,7 +59,7 @@ class TorrentHelper
$pm->sender_id = 1;
$pm->receiver_id = $wish->user_id;
$pm->subject = 'Wish List Notice!';
$pm->message = sprintf('The following item, %s, from your wishlist has been uploaded to %s! You can view it [url=%s/torrents/', $wish->title, $appname, $appurl).$torrent->id.'] HERE [/url]
$pm->message = \sprintf('The following item, %s, from your wishlist has been uploaded to %s! You can view it [url=%s/torrents/', $wish->title, $appname, $appurl).$torrent->id.'] HERE [/url]
[color=red][b]THIS IS AN AUTOMATED SYSTEM MESSAGE, PLEASE DO NOT REPLY![/b][/color]';
$pm->save();
}
@@ -94,17 +98,17 @@ class TorrentHelper
}
// Announce To IRC
if (config('irc-bot.enabled') == true) {
$appname = config('app.name');
$bot = new IRCAnnounceBot();
if (\config('irc-bot.enabled') == true) {
$appname = \config('app.name');
$ircAnnounceBot = new IRCAnnounceBot();
if ($anon == 0) {
$bot->message(config('irc-bot.channels'), '['.$appname.'] User '.$username.' has uploaded '.$torrent->name.' grab it now!');
$bot->message(config('irc-bot.channels'), '[Category: '.$torrent->category->name.'] [Type: '.$torrent->type->name.'] [Size:'.$torrent->getSize().']');
$bot->message(config('irc-bot.channels'), sprintf('[Link: %s/torrents/', $appurl).$id.']');
$ircAnnounceBot->message(\config('irc-bot.channels'), '['.$appname.'] User '.$username.' has uploaded '.$torrent->name.' grab it now!');
$ircAnnounceBot->message(\config('irc-bot.channels'), '[Category: '.$torrent->category->name.'] [Type: '.$torrent->type->name.'] [Size:'.$torrent->getSize().']');
$ircAnnounceBot->message(\config('irc-bot.channels'), \sprintf('[Link: %s/torrents/', $appurl).$id.']');
} else {
$bot->message(config('irc-bot.channels'), '['.$appname.'] An anonymous user has uploaded '.$torrent->name.' grab it now!');
$bot->message(config('irc-bot.channels'), '[Category: '.$torrent->category->name.'] [Type: '.$torrent->type->name.'] [Size: '.$torrent->getSize().']');
$bot->message(config('irc-bot.channels'), sprintf('[Link: %s/torrents/', $appurl).$id.']');
$ircAnnounceBot->message(\config('irc-bot.channels'), '['.$appname.'] An anonymous user has uploaded '.$torrent->name.' grab it now!');
$ircAnnounceBot->message(\config('irc-bot.channels'), '[Category: '.$torrent->category->name.'] [Type: '.$torrent->type->name.'] [Size: '.$torrent->getSize().']');
$ircAnnounceBot->message(\config('irc-bot.channels'), \sprintf('[Link: %s/torrents/', $appurl).$id.']');
}
}
}

42
app/Helpers/TorrentTools.php Executable file → Normal file
View File

@@ -38,23 +38,23 @@ class TorrentTools
// The PID will be set if an user downloads the torrent, but for
// security purposes it's better to overwrite the user-provided
// announce URL.
$announce = config('app.url');
$announce = \config('app.url');
$announce .= '/announce/PID';
$result['announce'] = $announce;
$result['info']['source'] = config('torrent.source');
$result['info']['source'] = \config('torrent.source');
$result['info']['private'] = 1;
$created_by = config('torrent.created_by', null);
$created_by_append = config('torrent.created_by_append', false);
$created_by = \config('torrent.created_by', null);
$created_by_append = \config('torrent.created_by_append', false);
if ($created_by !== null) {
if ($created_by_append && array_key_exists('created by', $result)) {
if ($created_by_append && \array_key_exists('created by', $result)) {
$c = $result['created by'];
$c = trim($c, '. ');
$c = \trim($c, '. ');
$c .= '. '.$created_by;
$created_by = $c;
}
$result['created by'] = $created_by;
}
$comment = config('torrent.comment', null);
$comment = \config('torrent.comment', null);
if ($comment !== null) {
$result['comment'] = $comment;
}
@@ -72,8 +72,8 @@ class TorrentTools
public static function getFileCount($decodedTorrent)
{
// Multiple file torrent ?
if (array_key_exists('files', $decodedTorrent['info']) && (is_countable($decodedTorrent['info']['files']) ? count($decodedTorrent['info']['files']) : 0)) {
return is_countable($decodedTorrent['info']['files']) ? count($decodedTorrent['info']['files']) : 0;
if (\array_key_exists('files', $decodedTorrent['info']) && (\is_countable($decodedTorrent['info']['files']) ? \count($decodedTorrent['info']['files']) : 0)) {
return \is_countable($decodedTorrent['info']['files']) ? \count($decodedTorrent['info']['files']) : 0;
}
return 1;
@@ -89,11 +89,11 @@ class TorrentTools
public static function getTorrentSize($decodedTorrent)
{
$size = 0;
if (array_key_exists('files', $decodedTorrent['info']) && (is_countable($decodedTorrent['info']['files']) ? count($decodedTorrent['info']['files']) : 0)) {
if (\array_key_exists('files', $decodedTorrent['info']) && (\is_countable($decodedTorrent['info']['files']) ? \count($decodedTorrent['info']['files']) : 0)) {
foreach ($decodedTorrent['info']['files'] as $k => $file) {
$dir = '';
$size += $file['length'];
$count = is_countable($file['path']) ? count($file['path']) : 0;
$count = \is_countable($file['path']) ? \count($file['path']) : 0;
}
} else {
$size = $decodedTorrent['info']['length'];
@@ -112,10 +112,10 @@ class TorrentTools
*/
public static function getTorrentFiles($decodedTorrent)
{
if (array_key_exists('files', $decodedTorrent['info']) && (is_countable($decodedTorrent['info']['files']) ? count($decodedTorrent['info']['files']) : 0)) {
if (\array_key_exists('files', $decodedTorrent['info']) && (\is_countable($decodedTorrent['info']['files']) ? \count($decodedTorrent['info']['files']) : 0)) {
foreach ($decodedTorrent['info']['files'] as $k => $file) {
$dir = '';
$count = is_countable($file['path']) ? count($file['path']) : 0;
$count = \is_countable($file['path']) ? \count($file['path']) : 0;
for ($i = 0; $i < $count; $i++) {
if ($i + 1 === $count) {
$fname = $dir.$file['path'][$i];
@@ -144,7 +144,7 @@ class TorrentTools
*/
public static function getTorrentHash($decodedTorrent)
{
return sha1(Bencode::bencode($decodedTorrent['info']));
return \sha1(Bencode::bencode($decodedTorrent['info']));
}
/**
@@ -156,8 +156,8 @@ class TorrentTools
*/
public static function getTorrentFileCount($decodedTorrent)
{
if (array_key_exists('files', $decodedTorrent['info'])) {
return is_countable($decodedTorrent['info']['files']) ? count($decodedTorrent['info']['files']) : 0;
if (\array_key_exists('files', $decodedTorrent['info'])) {
return \is_countable($decodedTorrent['info']['files']) ? \count($decodedTorrent['info']['files']) : 0;
}
return 1;
@@ -172,11 +172,11 @@ class TorrentTools
*/
public static function getNfo($inputFile)
{
$fileName = uniqid().'.nfo';
$inputFile->move(getcwd().'/files/tmp/', $fileName);
if (file_exists(getcwd().'/files/tmp/'.$fileName)) {
$fileContent = file_get_contents(getcwd().'/files/tmp/'.$fileName);
unlink(getcwd().'/files/tmp/'.$fileName);
$fileName = \uniqid().'.nfo';
$inputFile->move(\getcwd().'/files/tmp/', $fileName);
if (\file_exists(\getcwd().'/files/tmp/'.$fileName)) {
$fileContent = \file_get_contents(\getcwd().'/files/tmp/'.$fileName);
\unlink(\getcwd().'/files/tmp/'.$fileName);
} else {
$fileContent = null;
}

View File

@@ -25,7 +25,7 @@ class BaseController extends Controller
'message' => $message,
];
return response()->json($response, 200);
return \response()->json($response, 200);
}
public function sendError($error, $errorMessages = [], $code = 404)
@@ -39,6 +39,6 @@ class BaseController extends Controller
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
return \response()->json($response, $code);
}
}

View File

@@ -32,88 +32,91 @@ use Carbon\Carbon;
use Illuminate\Auth\AuthManager;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\API\ChatControllerTest
*/
class ChatController extends Controller
{
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* @var AuthManager
*/
private $auth;
private $authManager;
public function __construct(ChatRepository $chat, \Illuminate\Contracts\Auth\Factory $auth)
public function __construct(ChatRepository $chatRepository, \Illuminate\Contracts\Auth\Factory $factory)
{
$this->chat = $chat;
$this->auth = $auth;
$this->chatRepository = $chatRepository;
$this->authManager = $factory;
}
/* STATUSES */
public function statuses()
{
return response($this->chat->statuses());
return \response($this->chatRepository->statuses());
}
/* ECHOES */
public function echoes()
{
$user = User::with(['echoes'])->findOrFail($this->auth->user()->id);
$user = User::with(['echoes'])->findOrFail($this->authManager->user()->id);
if (! $user->echoes || (is_countable($user->echoes->toArray()) ? count($user->echoes->toArray()) : 0) < 1) {
$echoes = new UserEcho();
$echoes->user_id = $this->auth->user()->id;
$echoes->room_id = 1;
$echoes->save();
if (! $user->echoes || (\is_countable($user->echoes->toArray()) ? \count($user->echoes->toArray()) : 0) < 1) {
$userEcho = new UserEcho();
$userEcho->user_id = $this->authManager->user()->id;
$userEcho->room_id = 1;
$userEcho->save();
}
return UserEchoResource::collection($this->chat->echoes($this->auth->user()->id));
return UserEchoResource::collection($this->chatRepository->echoes($this->authManager->user()->id));
}
/* AUDIBLES */
public function audibles()
{
$user = User::with(['audibles'])->findOrFail($this->auth->user()->id);
$user = User::with(['audibles'])->findOrFail($this->authManager->user()->id);
if (! $user->audibles || (is_countable($user->audibles->toArray()) ? count($user->audibles->toArray()) : 0) < 1) {
$audibles = new UserAudible();
$audibles->user_id = $this->auth->user()->id;
$audibles->room_id = 1;
$audibles->status = 1;
$audibles->save();
if (! $user->audibles || (\is_countable($user->audibles->toArray()) ? \count($user->audibles->toArray()) : 0) < 1) {
$userAudible = new UserAudible();
$userAudible->user_id = $this->authManager->user()->id;
$userAudible->room_id = 1;
$userAudible->status = 1;
$userAudible->save();
}
return UserAudibleResource::collection($this->chat->audibles($this->auth->user()->id));
return UserAudibleResource::collection($this->chatRepository->audibles($this->authManager->user()->id));
}
/* BOTS */
public function bots()
{
return BotResource::collection($this->chat->bots());
return BotResource::collection($this->chatRepository->bots());
}
/* ROOMS */
public function rooms()
{
return ChatRoomResource::collection($this->chat->rooms());
return ChatRoomResource::collection($this->chatRepository->rooms());
}
public function config()
{
return response($this->chat->config());
return \response($this->chatRepository->config());
}
/* MESSAGES */
public function messages($room_id)
{
return ChatMessageResource::collection($this->chat->messages($room_id));
return ChatMessageResource::collection($this->chatRepository->messages($room_id));
}
/* MESSAGES */
public function privateMessages($target_id)
{
return ChatMessageResource::collection($this->chat->privateMessages($this->auth->user()->id, $target_id));
return ChatMessageResource::collection($this->chatRepository->privateMessages($this->authManager->user()->id, $target_id));
}
/* MESSAGES */
@@ -121,18 +124,18 @@ class ChatController extends Controller
{
$bot = Bot::where('id', '=', $bot_id)->firstOrFail();
if ($bot->is_systembot) {
$runbot = new SystemBot($this->chat);
$runbot = new SystemBot($this->chatRepository);
} elseif ($bot->is_nerdbot) {
$runbot = new NerdBot($this->chat);
$runbot = new NerdBot($this->chatRepository);
}
$runbot->process('message', $this->auth->user(), '', 0);
$runbot->process('message', $this->authManager->user(), '', 0);
return ChatMessageResource::collection($this->chat->botMessages($this->auth->user()->id, $bot->id));
return ChatMessageResource::collection($this->chatRepository->botMessages($this->authManager->user()->id, $bot->id));
}
public function createMessage(Request $request)
{
$user = $this->auth->user();
$user = $this->authManager->user();
$user_id = $user->id;
$receiver_id = $request->input('receiver_id');
@@ -143,71 +146,71 @@ class ChatController extends Controller
$save = $request->get('save');
if ($user->can_chat === 0) {
return response('error', 401);
return \response('error', 401);
}
// Temp Fix For HTMLPurifier
if ($message === '<') {
return response('error', 401);
return \response('error', 401);
}
$bot_dirty = 0;
$bots = cache()->get('bots');
if (! $bots || ! is_array($bots) || count($bots) < 1) {
$bots = \cache()->get('bots');
if (! $bots || ! \is_array($bots) || \count($bots) < 1) {
$bots = Bot::where('active', '=', 1)->orderBy('position', 'asc')->get();
$bot_dirty = 1;
}
if ($bot_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('bots', $bots, $expiresAt);
\cache()->put('bots', $bots, $expiresAt);
}
$which = null;
$target = null;
$runbot = null;
$trip = 'msg';
if ($message && substr($message, 0, 1 + (strlen($trip))) === '/'.$trip) {
if ($message && \substr($message, 0, 1 + (\strlen($trip))) === '/'.$trip) {
$which = 'skip';
$command = @explode(' ', $message);
if (array_key_exists(1, $command)) {
$command = @\explode(' ', $message);
if (\array_key_exists(1, $command)) {
$receiver = User::where('username', 'like', $command[1])->firstOrFail();
$receiver_id = $receiver->id;
$clone = $command;
array_shift($clone);
array_shift($clone);
$message = trim(implode(' ', $clone));
\array_shift($clone);
\array_shift($clone);
$message = \trim(\implode(' ', $clone));
}
$bot_id = 1;
}
$trip = 'gift';
if ($message && substr($message, 0, 1 + (strlen($trip))) === '/'.$trip) {
if ($message && \substr($message, 0, 1 + (\strlen($trip))) === '/'.$trip) {
$which = 'echo';
$target = 'system';
$message = '/bot gift'.substr($message, strlen($trip) + 1, strlen($message));
$message = '/bot gift'.\substr($message, \strlen($trip) + 1, \strlen($message));
}
if ($target == 'system') {
$runbot = new SystemBot($this->chat);
$runbot = new SystemBot($this->chatRepository);
}
if ($which == null) {
foreach ($bots as $bot) {
if ($message && substr($message, 0, 1 + (strlen($bot->command))) === '/'.$bot->command) {
if ($message && \substr($message, 0, 1 + (\strlen($bot->command))) === '/'.$bot->command) {
$which = 'echo';
} elseif ($message && substr($message, 0, 1 + (strlen($bot->command))) === '!'.$bot->command) {
} elseif ($message && \substr($message, 0, 1 + (\strlen($bot->command))) === '!'.$bot->command) {
$which = 'public';
} elseif ($message && substr($message, 0, 1 + (strlen($bot->command))) === '@'.$bot->command) {
$message = substr($message, 1 + strlen($bot->command), strlen($message));
} elseif ($message && \substr($message, 0, 1 + (\strlen($bot->command))) === '@'.$bot->command) {
$message = \substr($message, 1 + \strlen($bot->command), \strlen($message));
$which = 'private';
} elseif ($message && $receiver_id == 1 && $bot->id == $bot_id) {
if ($message && substr($message, 0, 1 + (strlen($bot->command))) === '/'.$bot->command) {
$message = substr($message, 1 + strlen($bot->command), strlen($message));
if ($message && \substr($message, 0, 1 + (\strlen($bot->command))) === '/'.$bot->command) {
$message = \substr($message, 1 + \strlen($bot->command), \strlen($message));
}
if ($message && substr($message, 0, 1 + (strlen($bot->command))) === '!'.$bot->command) {
$message = substr($message, 1 + strlen($bot->command), strlen($message));
if ($message && \substr($message, 0, 1 + (\strlen($bot->command))) === '!'.$bot->command) {
$message = \substr($message, 1 + \strlen($bot->command), \strlen($message));
}
if ($message && substr($message, 0, 1 + (strlen($bot->command))) === '@'.$bot->command) {
$message = substr($message, 1 + strlen($bot->command), strlen($message));
if ($message && \substr($message, 0, 1 + (\strlen($bot->command))) === '@'.$bot->command) {
$message = \substr($message, 1 + \strlen($bot->command), \strlen($message));
}
$which = 'message';
}
@@ -219,27 +222,27 @@ class ChatController extends Controller
if ($which != null && $which != 'skip' && ! $runbot) {
if ($bot->is_systembot) {
$runbot = new SystemBot($this->chat);
$runbot = new SystemBot($this->chatRepository);
} elseif ($bot->is_nerdbot) {
$runbot = new NerdBot($this->chat);
$runbot = new NerdBot($this->chatRepository);
} elseif ($bot->is_casinobot) {
$runbot = new CasinoBot($this->chat);
$runbot = new CasinoBot($this->chatRepository);
}
}
if ($runbot !== null) {
return $runbot->process($which, $this->auth->user(), $message, 0);
return $runbot->process($which, $this->authManager->user(), $message, 0);
}
$echo = false;
if ($receiver_id && $receiver_id > 0) {
$sender_dirty = 0;
$receiver_dirty = 0;
$sender_echoes = cache()->get('user-echoes'.$user_id);
$receiver_echoes = cache()->get('user-echoes'.$receiver_id);
if (! $sender_echoes || ! is_array($sender_echoes) || count($sender_echoes) < 1) {
$sender_echoes = \cache()->get('user-echoes'.$user_id);
$receiver_echoes = \cache()->get('user-echoes'.$receiver_id);
if (! $sender_echoes || ! \is_array($sender_echoes) || \count($sender_echoes) < 1) {
$sender_echoes = UserEcho::with(['room', 'target', 'bot'])->where('user_id', $user_id)->get();
}
if (! $receiver_echoes || ! is_array($receiver_echoes) || count($receiver_echoes) < 1) {
if (! $receiver_echoes || ! \is_array($receiver_echoes) || \count($receiver_echoes) < 1) {
$receiver_echoes = UserEcho::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$receiver_id])->get();
}
$sender_listening = false;
@@ -272,23 +275,23 @@ class ChatController extends Controller
}
if ($sender_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
\cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
\event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$receiver_id, $receiver_echoes, $expiresAt);
event(new Chatter('echo', $receiver_id, UserEchoResource::collection($receiver_echoes)));
\cache()->put('user-echoes'.$receiver_id, $receiver_echoes, $expiresAt);
\event(new Chatter('echo', $receiver_id, UserEchoResource::collection($receiver_echoes)));
}
$sender_dirty = 0;
$receiver_dirty = 0;
$sender_audibles = cache()->get('user-audibles'.$user_id);
$receiver_audibles = cache()->get('user-audibles'.$receiver_id);
if (! $sender_audibles || ! is_array($sender_audibles) || count($sender_audibles) < 1) {
$sender_audibles = \cache()->get('user-audibles'.$user_id);
$receiver_audibles = \cache()->get('user-audibles'.$receiver_id);
if (! $sender_audibles || ! \is_array($sender_audibles) || \count($sender_audibles) < 1) {
$sender_audibles = UserAudible::with(['room', 'target', 'bot'])->where('user_id', $user_id)->get();
}
if (! $receiver_audibles || ! is_array($receiver_audibles) || count($receiver_audibles) < 1) {
if (! $receiver_audibles || ! \is_array($receiver_audibles) || \count($receiver_audibles) < 1) {
$receiver_audibles = UserAudible::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$receiver_id])->get();
}
$sender_listening = false;
@@ -323,24 +326,24 @@ class ChatController extends Controller
}
if ($sender_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
\cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
\event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
}
if ($receiver_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$receiver_id, $receiver_audibles, $expiresAt);
event(new Chatter('audible', $receiver_id, UserAudibleResource::collection($receiver_audibles)));
\cache()->put('user-audibles'.$receiver_id, $receiver_audibles, $expiresAt);
\event(new Chatter('audible', $receiver_id, UserAudibleResource::collection($receiver_audibles)));
}
$room_id = 0;
$ignore = $bot_id > 0 && $receiver_id == 1 ? true : null;
$save = true;
$echo = true;
$message = $this->chat->privateMessage($user_id, $room_id, $message, $receiver_id, null, $ignore);
$message = $this->chatRepository->privateMessage($user_id, $room_id, $message, $receiver_id, null, $ignore);
} else {
$receiver_id = null;
$bot_id = null;
$message = $this->chat->message($user_id, $room_id, $message, $receiver_id, $bot_id);
$message = $this->chatRepository->message($user_id, $room_id, $message, $receiver_id, $bot_id);
}
if (! $save) {
@@ -351,14 +354,14 @@ class ChatController extends Controller
return new ChatMessageResource($message);
}
return response('success');
return \response('success');
}
public function deleteMessage($id)
{
$this->chat->deleteMessage($id);
$this->chatRepository->deleteMessage($id);
return response('success');
return \response('success');
}
public function deleteRoomEcho(Request $request, $user_id)
@@ -367,7 +370,7 @@ class ChatController extends Controller
$echo->delete();
$user = User::with(['chatStatus', 'chatroom', 'group', 'echoes'])->findOrFail($user_id);
$room = $this->chat->roomFindOrFail($request->input('room_id'));
$room = $this->chatRepository->roomFindOrFail($request->input('room_id'));
$user->chatroom()->dissociate();
$user->chatroom()->associate($room);
@@ -377,10 +380,10 @@ class ChatController extends Controller
$sender_echoes = UserEcho::with(['room', 'target', 'bot'])->where('user_id', $user_id)->get();
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
\cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
\event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
return response($user);
return \response($user);
}
public function deleteTargetEcho(Request $request, $user_id)
@@ -392,10 +395,10 @@ class ChatController extends Controller
$sender_echoes = UserEcho::with(['room', 'target', 'bot'])->where('user_id', $user_id)->get();
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
\cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
\event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
return response($user);
return \response($user);
}
public function deleteBotEcho(Request $request, $user_id)
@@ -407,10 +410,10 @@ class ChatController extends Controller
$sender_echoes = UserEcho::with(['room', 'target', 'bot'])->where('user_id', $user_id)->get();
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
\cache()->put('user-echoes'.$user_id, $sender_echoes, $expiresAt);
\event(new Chatter('echo', $user_id, UserEchoResource::collection($sender_echoes)));
return response($user);
return \response($user);
}
public function toggleRoomAudible(Request $request, $user_id)
@@ -423,10 +426,10 @@ class ChatController extends Controller
$sender_audibles = UserAudible::with(['room', 'target', 'bot'])->where('user_id', $user_id)->get();
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
\cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
\event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
return response($user);
return \response($user);
}
public function toggleTargetAudible(Request $request, $user_id)
@@ -439,10 +442,10 @@ class ChatController extends Controller
$sender_audibles = UserAudible::with(['target', 'room', 'bot'])->where('user_id', $user_id)->get();
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
\cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
\event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
return response($user);
return \response($user);
}
public function toggleBotAudible(Request $request, $user_id)
@@ -455,10 +458,10 @@ class ChatController extends Controller
$sender_audibles = UserAudible::with(['bot', 'room', 'bot'])->where('user_id', $user_id)->get();
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
\cache()->put('user-audibles'.$user_id, $sender_audibles, $expiresAt);
\event(new Chatter('audible', $user_id, UserAudibleResource::collection($sender_audibles)));
return response($user);
return \response($user);
}
/* USERS */
@@ -467,24 +470,24 @@ class ChatController extends Controller
$systemUser = User::where('username', 'System')->firstOrFail();
$user = User::with(['chatStatus', 'chatroom', 'group', 'echoes'])->findOrFail($id);
$status = $this->chat->statusFindOrFail($request->input('status_id'));
$status = $this->chatRepository->statusFindOrFail($request->input('status_id'));
$log = '[url=/users/'.$user->username.']'.$user->username.'[/url] has updated their status to [b]'.$status->name.'[/b]';
$message = $this->chat->message($systemUser->id, $user->chatroom->id, $log, null);
$message = $this->chatRepository->message($systemUser->id, $user->chatroom->id, $log, null);
$message->save();
$user->chatStatus()->dissociate();
$user->chatStatus()->associate($status);
$user->save();
return response($user);
return \response($user);
}
public function updateUserRoom(Request $request, $id)
{
$user = User::with(['chatStatus', 'chatroom', 'group', 'echoes'])->findOrFail($id);
$room = $this->chat->roomFindOrFail($request->input('room_id'));
$room = $this->chatRepository->roomFindOrFail($request->input('room_id'));
$user->chatroom()->dissociate();
$user->chatroom()->associate($room);
@@ -492,8 +495,8 @@ class ChatController extends Controller
$user->save();
$sender_dirty = 0;
$sender_echoes = cache()->get('user-echoes'.$id);
if (! $sender_echoes || ! is_array($sender_echoes) || count($sender_echoes) < 1) {
$sender_echoes = \cache()->get('user-echoes'.$id);
if (! $sender_echoes || ! \is_array($sender_echoes) || \count($sender_echoes) < 1) {
$sender_echoes = UserEcho::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$id])->get();
}
$sender_listening = false;
@@ -503,33 +506,33 @@ class ChatController extends Controller
}
}
if (! $sender_listening) {
$sender_port = new UserEcho();
$sender_port->user_id = $id;
$sender_port->room_id = $room->id;
$sender_port->save();
$userEcho = new UserEcho();
$userEcho->user_id = $id;
$userEcho->room_id = $room->id;
$userEcho->save();
$sender_echoes = UserEcho::with(['room', 'target', 'bot'])->whereRaw('user_id = ?', [$id])->get();
$sender_dirty = 1;
}
if ($sender_dirty == 1) {
$expiresAt = Carbon::now()->addMinutes(60);
cache()->put('user-echoes'.$id, $sender_echoes, $expiresAt);
event(new Chatter('echo', $id, UserEchoResource::collection($sender_echoes)));
\cache()->put('user-echoes'.$id, $sender_echoes, $expiresAt);
\event(new Chatter('echo', $id, UserEchoResource::collection($sender_echoes)));
}
return response($user);
return \response($user);
}
public function updateUserTarget($id)
{
$user = User::with(['chatStatus', 'chatroom', 'group', 'echoes'])->findOrFail($id);
return response($user);
return \response($user);
}
public function updateBotTarget($id)
{
$user = User::with(['chatStatus', 'chatroom', 'group', 'echoes'])->findOrFail($id);
return response($user);
return \response($user);
}
}

View File

@@ -32,21 +32,24 @@ use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
/**
* @see \Tests\Todo\Feature\Http\Controllers\TorrentControllerTest
*/
class TorrentController extends BaseController
{
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* RequestController Constructor.
*
* @param ChatRepository $chat
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
@@ -83,7 +86,7 @@ class TorrentController extends BaseController
return $this->sendError('Validation Error.', 'You Must Provide A Valid Torrent File For Upload!');
}
$client = new \App\Services\MovieScrapper(config('api-keys.tmdb'), config('api-keys.tvdb'), config('api-keys.omdb'));
$movieScrapper = new \App\Services\MovieScrapper(\config('api-keys.tmdb'), \config('api-keys.tvdb'), \config('api-keys.omdb'));
// Deplace and decode the torrent temporarily
$decodedTorrent = TorrentTools::normalizeTorrent($requestFile);
$infohash = Bencode::get_infohash($decodedTorrent);
@@ -94,14 +97,14 @@ class TorrentController extends BaseController
return $this->sendError('Validation Error.', 'You Must Provide A Valid Torrent File For Upload!');
}
$fileName = sprintf('%s.torrent', uniqid()); // Generate a unique name
$fileName = \sprintf('%s.torrent', \uniqid()); // Generate a unique name
Storage::disk('torrents')->put($fileName, Bencode::bencode($decodedTorrent));
// Find the right category
$category = Category::withCount('torrents')->findOrFail($request->input('category_id'));
// Create the torrent (DB)
$torrent = app()->make(Torrent::class);
$torrent = \app()->make(Torrent::class);
$torrent->name = $request->input('name');
$torrent->slug = Str::slug($torrent->name);
$torrent->description = $request->input('description');
@@ -113,13 +116,14 @@ class TorrentController extends BaseController
$torrent->size = $meta['size'];
$torrent->nfo = ($request->hasFile('nfo')) ? TorrentTools::getNfo($request->file('nfo')) : '';
$torrent->category_id = $category->id;
$torrent->type_id = $request->input('type_id');
$torrent->resolution_id = $request->input('resolution_id');
$torrent->user_id = $user->id;
$torrent->imdb = $request->input('imdb');
$torrent->tvdb = $request->input('tvdb');
$torrent->tmdb = $request->input('tmdb');
$torrent->mal = $request->input('mal');
$torrent->igdb = $request->input('igdb');
$torrent->type_id = $request->input('type_id');
$torrent->anon = $request->input('anonymous');
$torrent->stream = $request->input('stream');
$torrent->sd = $request->input('sd');
@@ -131,32 +135,39 @@ class TorrentController extends BaseController
$torrent->moderated_at = Carbon::now();
$torrent->moderated_by = User::where('username', 'System')->first()->id; //System ID
// Set freeleech and doubleup if featured
if ($torrent->featured == 1) {
$torrent->free = '1';
$torrent->doubleup = '1';
}
// Validation
$v = validator($torrent->toArray(), [
'name' => 'required|unique:torrents',
'slug' => 'required',
'description' => 'required',
'info_hash' => 'required|unique:torrents',
'file_name' => 'required',
'num_file' => 'required|numeric',
'announce' => 'required',
'size' => 'required',
'category_id' => 'required',
'user_id' => 'required',
'imdb' => 'required|numeric',
'tvdb' => 'required|numeric',
'tmdb' => 'required|numeric',
'mal' => 'required|numeric',
'igdb' => 'required|numeric',
'type_id' => 'required',
'anon' => 'required',
'stream' => 'required',
'sd' => 'required',
'internal' => 'required',
'featured' => 'required',
'free' => 'required',
'doubleup' => 'required',
'sticky' => 'required',
$v = \validator($torrent->toArray(), [
'name' => 'required|unique:torrents',
'slug' => 'required',
'description' => 'required',
'info_hash' => 'required|unique:torrents',
'file_name' => 'required',
'num_file' => 'required|numeric',
'announce' => 'required',
'size' => 'required',
'category_id' => 'required|exists:categories,id',
'type_id' => 'required|exists:types,id',
'resolution_id' => 'nullable|exists:resolutions,id',
'user_id' => 'required|exists:users,id',
'imdb' => 'required|numeric',
'tvdb' => 'required|numeric',
'tmdb' => 'required|numeric',
'mal' => 'required|numeric',
'igdb' => 'required|numeric',
'anon' => 'required',
'stream' => 'required',
'sd' => 'required',
'internal' => 'required',
'featured' => 'required',
'free' => 'required',
'doubleup' => 'required',
'sticky' => 'required',
]);
if ($v->fails()) {
@@ -170,10 +181,10 @@ class TorrentController extends BaseController
$torrent->save();
// Set torrent to featured
if ($torrent->featured == 1) {
$feature = new FeaturedTorrent();
$feature->user_id = $user->id;
$feature->torrent_id = $torrent->id;
$feature->save();
$featuredTorrent = new FeaturedTorrent();
$featuredTorrent->user_id = $user->id;
$featuredTorrent->torrent_id = $torrent->id;
$featuredTorrent->save();
}
// Count and save the torrent number in this category
$category->num_torrent = $category->torrents_count;
@@ -181,27 +192,27 @@ class TorrentController extends BaseController
// Backup the files contained in the torrent
$fileList = TorrentTools::getTorrentFiles($decodedTorrent);
foreach ($fileList as $file) {
$f = new TorrentFile();
$f->name = $file['name'];
$f->size = $file['size'];
$f->torrent_id = $torrent->id;
$f->save();
unset($f);
$torrentFile = new TorrentFile();
$torrentFile->name = $file['name'];
$torrentFile->size = $file['size'];
$torrentFile->torrent_id = $torrent->id;
$torrentFile->save();
unset($torrentFile);
}
$meta = null;
// Torrent Tags System
if ($torrent->category->tv_meta) {
if ($torrent->tmdb && $torrent->tmdb != 0) {
$meta = $client->scrape('tv', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('tv', null, $torrent->tmdb);
} else {
$meta = $client->scrape('tv', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('tv', 'tt'.$torrent->imdb);
}
}
if ($torrent->category->movie_meta) {
if ($torrent->tmdb && $torrent->tmdb != 0) {
$meta = $client->scrape('movie', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('movie', null, $torrent->tmdb);
} else {
$meta = $client->scrape('movie', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('movie', 'tt'.$torrent->imdb);
}
}
if (isset($meta) && $meta->genres) {
@@ -214,7 +225,7 @@ class TorrentController extends BaseController
}
// check for trusted user and update torrent
if ($user->group->is_trusted) {
$appurl = config('app.url');
$appurl = \config('app.url');
$user = $torrent->user;
$user_id = $user->id;
$username = $user->username;
@@ -225,41 +236,41 @@ class TorrentController extends BaseController
// Announce To Shoutbox
if ($anon == 0) {
$this->chat->systemMessage(
sprintf('User [url=%s/users/', $appurl).$username.']'.$username.sprintf('[/url] has uploaded [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] grab it now! :slight_smile:'
$this->chatRepository->systemMessage(
\sprintf('User [url=%s/users/', $appurl).$username.']'.$username.\sprintf('[/url] has uploaded [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] grab it now! :slight_smile:'
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user has uploaded [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] grab it now! :slight_smile:'
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has uploaded [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] grab it now! :slight_smile:'
);
}
if ($anon == 1 && $featured == 1) {
$this->chat->systemMessage(
sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] has been added to the Featured Torrents Slider by an anonymous user! Grab It While You Can! :fire:'
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] has been added to the Featured Torrents Slider by an anonymous user! Grab It While You Can! :fire:'
);
} elseif ($anon == 0 && $featured == 1) {
$this->chat->systemMessage(
sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.sprintf('[/url] has been added to the Featured Torrents Slider by [url=%s/users/', $appurl).$username.']'.$username.'[/url]! Grab It While You Can! :fire:'
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.\sprintf('[/url] has been added to the Featured Torrents Slider by [url=%s/users/', $appurl).$username.']'.$username.'[/url]! Grab It While You Can! :fire:'
);
}
if ($free == 1 && $featured == 0) {
$this->chat->systemMessage(
sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] has been granted 100%% FreeLeech! Grab It While You Can! :fire:'
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] has been granted 100%% FreeLeech! Grab It While You Can! :fire:'
);
}
if ($doubleup == 1 && $featured == 0) {
$this->chat->systemMessage(
sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] has been granted Double Upload! Grab It While You Can! :fire:'
$this->chatRepository->systemMessage(
\sprintf('Ladies and Gents, [url=%s/torrents/', $appurl).$torrent->id.']'.$torrent->name.'[/url] has been granted Double Upload! Grab It While You Can! :fire:'
);
}
TorrentHelper::approveHelper($torrent->id);
}
return $this->sendResponse(route('torrent.download.rsskey', ['id' => $torrent->id, 'rsskey' => auth('api')->user()->rsskey]), 'Torrent uploaded successfully.');
return $this->sendResponse(\route('torrent.download.rsskey', ['id' => $torrent->id, 'rsskey' => \auth('api')->user()->rsskey]), 'Torrent uploaded successfully.');
}
/**
@@ -328,6 +339,7 @@ class TorrentController extends BaseController
$end_year = $request->input('end_year');
$categories = $request->input('categories');
$types = $request->input('types');
$resolutions = $request->input('resolutions');
$genres = $request->input('genres');
$freeleech = $request->input('freeleech');
$doubleupload = $request->input('doubleupload');
@@ -340,19 +352,19 @@ class TorrentController extends BaseController
$dying = $request->input('dying');
$dead = $request->input('dead');
$terms = explode(' ', $search);
$terms = \explode(' ', $search);
$search = '';
foreach ($terms as $term) {
$search .= '%'.$term.'%';
}
$usernames = explode(' ', $uploader);
$usernames = \explode(' ', $uploader);
$uploader = null;
foreach ($usernames as $username) {
$uploader .= $username.'%';
}
$keywords = explode(' ', $description);
$keywords = \explode(' ', $description);
$description = '';
foreach ($keywords as $keyword) {
$description .= '%'.$keyword.'%';
@@ -395,7 +407,7 @@ class TorrentController extends BaseController
}
if ($request->has('imdb') && $request->input('imdb') != null) {
$torrent->where('torrents.imdb', '=', str_replace('tt', '', $imdb));
$torrent->where('torrents.imdb', '=', \str_replace('tt', '', $imdb));
}
if ($request->has('tvdb') && $request->input('tvdb') != null) {
@@ -426,6 +438,10 @@ class TorrentController extends BaseController
$torrent->whereIn('torrents.type_id', $types);
}
if ($request->has('resolutions') && $request->input('resolutions') != null) {
$torrent->whereIn('torrents.resolution_id', $resolutions);
}
if ($request->has('genres') && $request->input('genres') != null) {
$genreID = TagTorrent::select(['torrent_id'])->distinct()->whereIn('tag_name', $genres)->get();
$torrent->whereIn('torrents.id', $genreID);
@@ -494,16 +510,16 @@ class TorrentController extends BaseController
if ($mediainfo === null) {
return;
}
$complete_name_i = strpos($mediainfo, 'Complete name');
$complete_name_i = \strpos($mediainfo, 'Complete name');
if ($complete_name_i !== false) {
$path_i = strpos($mediainfo, ': ', $complete_name_i);
$path_i = \strpos($mediainfo, ': ', $complete_name_i);
if ($path_i !== false) {
$path_i += 2;
$end_i = strpos($mediainfo, "\n", $path_i);
$path = substr($mediainfo, $path_i, $end_i - $path_i);
$end_i = \strpos($mediainfo, "\n", $path_i);
$path = \substr($mediainfo, $path_i, $end_i - $path_i);
$new_path = MediaInfo::stripPath($path);
return substr_replace($mediainfo, $new_path, $path_i, strlen($path));
return \substr_replace($mediainfo, $new_path, $path_i, \strlen($path));
}
}

7
app/Http/Controllers/AchievementsController.php Executable file → Normal file
View File

@@ -16,6 +16,9 @@ namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\AchievementsControllerTest
*/
class AchievementsController extends Controller
{
/**
@@ -32,7 +35,7 @@ class AchievementsController extends Controller
$achievements = $user->unlockedAchievements();
$pending = $user->inProgressAchievements();
return view('achievement.index', [
return \view('achievement.index', [
'route' => 'achievement',
'user' => $user,
'achievements' => $achievements,
@@ -53,7 +56,7 @@ class AchievementsController extends Controller
$achievements = $user->unlockedAchievements();
return view('achievement.show', [
return \view('achievement.show', [
'route' => 'achievement',
'user' => $user,
'achievements' => $achievements,

View File

@@ -18,23 +18,26 @@ use App\Services\Clients\OmdbClient;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Image;
use Intervention\Image\Facades\Image;
/**
* @see \Tests\Feature\Http\Controllers\AlbumControllerTest
*/
class AlbumController extends Controller
{
/**
* @var OmdbClient
*/
private $client;
private $omdbClient;
/**
* AlbumController Constructor.
*
* @param OmdbClient $client
* @param \App\Services\Clients\OmdbClient $omdbClient
*/
public function __construct(OmdbClient $client)
public function __construct(OmdbClient $omdbClient)
{
$this->client = $client;
$this->omdbClient = $omdbClient;
}
/**
@@ -46,7 +49,7 @@ class AlbumController extends Controller
{
$albums = Album::withCount('images')->get();
return view('album.index')->with('albums', $albums);
return \view('album.index')->with('albums', $albums);
}
/**
@@ -56,7 +59,7 @@ class AlbumController extends Controller
*/
public function create()
{
return view('album.create');
return \view('album.create');
}
/**
@@ -69,10 +72,10 @@ class AlbumController extends Controller
public function store(Request $request)
{
$imdb = Str::startsWith($request->input('imdb'), 'tt') ? $request->input('imdb') : 'tt'.$request->input('imdb');
$omdb = $this->client->find(['imdb' => $imdb]);
$omdb = $this->omdbClient->find(['imdb' => $imdb]);
if ($omdb === null || ! $omdb) {
return redirect()->route('albums.create')
return \redirect()->route('albums.create')
->withErrors('Bad IMDB Request!');
}
@@ -83,12 +86,12 @@ class AlbumController extends Controller
$album->imdb = $request->input('imdb');
$image = $request->file('cover_image');
$filename = 'album-cover_'.uniqid().'.'.$image->getClientOriginalExtension();
$path = public_path('/files/img/'.$filename);
$filename = 'album-cover_'.\uniqid().'.'.$image->getClientOriginalExtension();
$path = \public_path('/files/img/'.$filename);
Image::make($image->getRealPath())->fit(400, 225)->encode('png', 100)->save($path);
$album->cover_image = $filename;
$v = validator($album->toArray(), [
$v = \validator($album->toArray(), [
'user_id' => 'required',
'name' => 'required',
'description' => 'required',
@@ -97,13 +100,13 @@ class AlbumController extends Controller
]);
if ($v->fails()) {
return redirect()->route('albums.create')
return \redirect()->route('albums.create')
->withInput()
->withErrors($v->errors());
}
$album->save();
return redirect()->route('albums.show', ['id' => $album->id])
return \redirect()->route('albums.show', ['id' => $album->id])
->withSuccess('Your album has successfully published!');
}
@@ -119,7 +122,7 @@ class AlbumController extends Controller
$album = Album::with('images')->find($id);
$albums = Album::with('images')->get();
return view('album.show', ['album' => $album, 'albums' => $albums]);
return \view('album.show', ['album' => $album, 'albums' => $albums]);
}
/**
@@ -128,6 +131,8 @@ class AlbumController extends Controller
* @param \Illuminate\Http\Request $request
* @param \App\Models\Album $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request, $id)
@@ -135,10 +140,10 @@ class AlbumController extends Controller
$user = $request->user();
$album = Album::findOrFail($id);
abort_unless($user->group->is_modo || ($user->id === $album->user_id && Carbon::now()->lt($album->created_at->addDay())), 403);
\abort_unless($user->group->is_modo || ($user->id === $album->user_id && Carbon::now()->lt($album->created_at->addDay())), 403);
$album->delete();
return redirect()->route('albums.index')
return \redirect()->route('albums.index')
->withSuccess('Album has successfully been deleted');
}
}

7
app/Http/Controllers/ArticleController.php Executable file → Normal file
View File

@@ -15,6 +15,9 @@ namespace App\Http\Controllers;
use App\Models\Article;
/**
* @see \Tests\Feature\Http\Controllers\ArticleControllerTest
*/
class ArticleController extends Controller
{
/**
@@ -26,7 +29,7 @@ class ArticleController extends Controller
{
$articles = Article::latest()->paginate(6);
return view('article.index', ['articles' => $articles]);
return \view('article.index', ['articles' => $articles]);
}
/**
@@ -40,6 +43,6 @@ class ArticleController extends Controller
{
$article = Article::with(['user', 'comments'])->findOrFail($id);
return view('article.show', ['article' => $article]);
return \view('article.show', ['article' => $article]);
}
}

View File

@@ -17,12 +17,15 @@ use App\Http\Controllers\Controller;
use App\Models\Group;
use App\Models\UserActivation;
/**
* @see \Tests\Feature\Http\Controllers\Auth\ActivationControllerTest
*/
class ActivationController extends Controller
{
public function activate($token)
{
$banned_group = cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$member_group = cache()->rememberForever('member_group', fn () => Group::where('slug', '=', 'user')->pluck('id'));
$banned_group = \cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$member_group = \cache()->rememberForever('member_group', fn () => Group::where('slug', '=', 'user')->pluck('id'));
$activation = UserActivation::with('user')->where('token', '=', $token)->firstOrFail();
if ($activation->user->id && $activation->user->group->id != $banned_group[0]) {
@@ -37,11 +40,11 @@ class ActivationController extends Controller
$activation->delete();
return redirect()->route('login')
->withSuccess(trans('auth.activation-success'));
return \redirect()->route('login')
->withSuccess(\trans('auth.activation-success'));
}
return redirect()->route('login')
->withErrors(trans('auth.activation-error'));
return \redirect()->route('login')
->withErrors(\trans('auth.activation-error'));
}
}

View File

@@ -19,6 +19,9 @@ use App\Models\ApplicationImageProof;
use App\Models\ApplicationUrlProof;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\Staff\ApplicationControllerTest
*/
class ApplicationController extends Controller
{
/**
@@ -28,7 +31,7 @@ class ApplicationController extends Controller
*/
public function create()
{
return view('auth.application.create');
return \view('auth.application.create');
}
/**
@@ -40,14 +43,14 @@ class ApplicationController extends Controller
*/
public function store(Request $request)
{
$application = resolve(Application::class);
$application = \resolve(Application::class);
$application->type = $request->input('type');
$application->email = $request->input('email');
$application->referrer = $request->input('referrer');
if (config('email-blacklist.enabled') == true) {
if (config('captcha.enabled') == false) {
$v = validator($request->all(), [
if (\config('email-blacklist.enabled') == true) {
if (\config('captcha.enabled') == false) {
$v = \validator($request->all(), [
'type' => 'required',
'email' => 'required|string|email|max:70|blacklist|unique:invites|unique:users|unique:applications',
'referrer' => 'required',
@@ -57,7 +60,7 @@ class ApplicationController extends Controller
'links' => 'min:2',
]);
} else {
$v = validator($request->all(), [
$v = \validator($request->all(), [
'type' => 'required',
'email' => 'required|string|email|max:70|blacklist|unique:invites|unique:users|unique:applications',
'referrer' => 'required',
@@ -68,8 +71,8 @@ class ApplicationController extends Controller
'captcha' => 'hiddencaptcha',
]);
}
} elseif (config('captcha.enabled') == false) {
$v = validator($request->all(), [
} elseif (\config('captcha.enabled') == false) {
$v = \validator($request->all(), [
'type' => 'required',
'email' => 'required|string|email|max:70|unique:invites|unique:users|unique:applications',
'referrer' => 'required',
@@ -79,7 +82,7 @@ class ApplicationController extends Controller
'links' => 'min:2',
]);
} else {
$v = validator($request->all(), [
$v = \validator($request->all(), [
'type' => 'required',
'email' => 'required|string|email|max:70|unique:invites|unique:users|unique:applications',
'referrer' => 'required',
@@ -92,18 +95,18 @@ class ApplicationController extends Controller
}
if ($v->fails()) {
return redirect()->route('application.create')
return \redirect()->route('application.create')
->withErrors($v->errors());
}
$application->save();
// Map And Save IMG Proofs
$imgs = collect($request->input('images'))->map(fn ($value) => new ApplicationImageProof(['image' => $value]));
$imgs = \collect($request->input('images'))->map(fn ($value) => new ApplicationImageProof(['image' => $value]));
$application->imageProofs()->saveMany($imgs);
// Map And Save URL Proofs
$urls = collect($request->input('links'))->map(fn ($value) => new ApplicationUrlProof(['url' => $value]));
$urls = \collect($request->input('links'))->map(fn ($value) => new ApplicationUrlProof(['url' => $value]));
$application->urlProofs()->saveMany($urls);
return redirect()->route('login')
->withSuccess(trans('auth.application-submitted'));
return \redirect()->route('login')
->withSuccess(\trans('auth.application-submitted'));
}
}

2
app/Http/Controllers/Auth/ForgotPasswordController.php Executable file → Normal file
View File

@@ -28,7 +28,7 @@ class ForgotPasswordController extends Controller
protected function validateEmail(Request $request)
{
if (config('captcha.enabled') == false) {
if (\config('captcha.enabled') == false) {
$request->validate(['email' => 'required|email']);
} else {
$request->validate([

View File

@@ -18,6 +18,9 @@ use App\Models\User;
use App\Notifications\UsernameReminder;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\Auth\ForgotUsernameControllerTest
*/
class ForgotUsernameController extends Controller
{
/**
@@ -27,7 +30,7 @@ class ForgotUsernameController extends Controller
*/
public function showForgotUsernameForm()
{
return view('auth.username');
return \view('auth.username');
}
/**
@@ -41,30 +44,30 @@ class ForgotUsernameController extends Controller
{
$email = $request->get('email');
if (config('captcha.enabled') == false) {
$v = validator($request->all(), [
if (\config('captcha.enabled') == false) {
$v = \validator($request->all(), [
'email' => 'required',
]);
} else {
$v = validator($request->all(), [
$v = \validator($request->all(), [
'email' => 'required',
'captcha' => 'hiddencaptcha',
]);
}
if ($v->fails()) {
return redirect()->route('username.request')
return \redirect()->route('username.request')
->withErrors($v->errors());
}
$user = User::where('email', '=', $email)->first();
if (empty($user)) {
return redirect()->route('username.request')
->withErrors(trans('email.no-email-found'));
return \redirect()->route('username.request')
->withErrors(\trans('email.no-email-found'));
}
//send username reminder notification
$user->notify(new UsernameReminder());
return redirect()->route('login')
->withSuccess(trans('email.username-sent'));
return \redirect()->route('login')
->withSuccess(\trans('email.username-sent'));
}
}

View File

@@ -53,7 +53,7 @@ class LoginController extends Controller
*/
protected function validateLogin(Request $request)
{
if (config('captcha.enabled') == true) {
if (\config('captcha.enabled') == true) {
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
@@ -69,25 +69,25 @@ class LoginController extends Controller
protected function authenticated(Request $request, $user)
{
$banned_group = cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$validating_group = cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$disabled_group = cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
$member_group = cache()->rememberForever('member_group', fn () => Group::where('slug', '=', 'user')->pluck('id'));
$banned_group = \cache()->rememberForever('banned_group', fn () => Group::where('slug', '=', 'banned')->pluck('id'));
$validating_group = \cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$disabled_group = \cache()->rememberForever('disabled_group', fn () => Group::where('slug', '=', 'disabled')->pluck('id'));
$member_group = \cache()->rememberForever('member_group', fn () => Group::where('slug', '=', 'user')->pluck('id'));
if ($user->active == 0 || $user->group_id == $validating_group[0]) {
$this->guard()->logout();
$request->session()->invalidate();
return redirect()->route('login')
->withErrors(trans('auth.not-activated'));
return \redirect()->route('login')
->withErrors(\trans('auth.not-activated'));
}
if ($user->group_id == $banned_group[0]) {
$this->guard()->logout();
$request->session()->invalidate();
return redirect()->route('login')
->withErrors(trans('auth.banned'));
return \redirect()->route('login')
->withErrors(\trans('auth.banned'));
}
if ($user->group_id == $disabled_group[0]) {
@@ -101,11 +101,11 @@ class LoginController extends Controller
$user->disabled_at = null;
$user->save();
return redirect()->route('home.index')
->withSuccess(trans('auth.welcome-restore'));
return \redirect()->route('home.index')
->withSuccess(\trans('auth.welcome-restore'));
}
if (auth()->viaRemember() && $user->group_id == $disabled_group[0]) {
if (\auth()->viaRemember() && $user->group_id == $disabled_group[0]) {
$user->group_id = $member_group[0];
$user->can_upload = 1;
$user->can_download = 1;
@@ -116,16 +116,16 @@ class LoginController extends Controller
$user->disabled_at = null;
$user->save();
return redirect()->route('home.index')
->withSuccess(trans('auth.welcome-restore'));
return \redirect()->route('home.index')
->withSuccess(\trans('auth.welcome-restore'));
}
if ($user->read_rules == 0) {
return redirect()->to(config('other.rules_url'))
->withWarning(trans('auth.require-rules'));
return \redirect()->to(\config('other.rules_url'))
->withWarning(\trans('auth.require-rules'));
}
return redirect()->route('home.index')
->withSuccess(trans('auth.welcome'));
return \redirect()->route('home.index')
->withSuccess(\trans('auth.welcome'));
}
}

View File

@@ -33,16 +33,16 @@ class RegisterController extends Controller
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* RegisterController Constructor.
*
* @param ChatRepository $chat
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
@@ -55,66 +55,66 @@ class RegisterController extends Controller
public function registrationForm($code = null)
{
// Make sure open reg is off, invite code is not present and application signups enabled
if ($code === 'null' && config('other.invite-only') == 1 && config('other.application_signups') == true) {
return redirect()->route('application.create')
->withInfo(trans('auth.allow-invite-appl'));
if ($code === 'null' && \config('other.invite-only') == 1 && \config('other.application_signups') == true) {
return \redirect()->route('application.create')
->withInfo(\trans('auth.allow-invite-appl'));
}
// Make sure open reg is off and invite code is not present
if ($code === 'null' && config('other.invite-only') == 1) {
return redirect()->route('login')
->withWarning(trans('auth.allow-invite'));
if ($code === 'null' && \config('other.invite-only') == 1) {
return \redirect()->route('login')
->withWarning(\trans('auth.allow-invite'));
}
return view('auth.register', ['code' => $code]);
return \view('auth.register', ['code' => $code]);
}
public function register(Request $request, $code = null)
{
// Make sure open reg is off and invite code exist and has not been used already
$key = Invite::where('code', '=', $code)->first();
if (config('other.invite-only') == 1 && (! $key || $key->accepted_by !== null)) {
return redirect()->route('registrationForm', ['code' => $code])
->withErrors(trans('auth.invalid-key'));
if (\config('other.invite-only') == 1 && (! $key || $key->accepted_by !== null)) {
return \redirect()->route('registrationForm', ['code' => $code])
->withErrors(\trans('auth.invalid-key'));
}
$validating_group = cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$validating_group = \cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$user = new User();
$user->username = $request->input('username');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
$user->passkey = md5(uniqid().time().microtime());
$user->rsskey = md5(uniqid().time().microtime().$user->password);
$user->uploaded = config('other.default_upload');
$user->downloaded = config('other.default_download');
$user->style = config('other.default_style', 0);
$user->locale = config('app.locale');
$user->passkey = \md5(\uniqid().\time().\microtime());
$user->rsskey = \md5(\uniqid().\time().\microtime().$user->password);
$user->uploaded = \config('other.default_upload');
$user->downloaded = \config('other.default_download');
$user->style = \config('other.default_style', 0);
$user->locale = \config('app.locale');
$user->group_id = $validating_group[0];
if (config('email-blacklist.enabled') == true) {
if (config('captcha.enabled') == false) {
$v = validator($request->all(), [
if (\config('email-blacklist.enabled') == true) {
if (\config('captcha.enabled') == false) {
$v = \validator($request->all(), [
'username' => 'required|alpha_dash|string|between:3,25|unique:users',
'password' => 'required|string|between:8,16',
'email' => 'required|string|email|max:70|blacklist|unique:users',
]);
} else {
$v = validator($request->all(), [
$v = \validator($request->all(), [
'username' => 'required|alpha_dash|string|between:3,25|unique:users',
'password' => 'required|string|between:8,16',
'email' => 'required|string|email|max:70|blacklist|unique:users',
'captcha' => 'hiddencaptcha',
]);
}
} elseif (config('captcha.enabled') == false) {
$v = validator($request->all(), [
} elseif (\config('captcha.enabled') == false) {
$v = \validator($request->all(), [
'username' => 'required|alpha_dash|string|between:3,25|unique:users',
'password' => 'required|string|between:8,16',
'email' => 'required|string|email|max:70|unique:users',
]);
} else {
$v = validator($request->all(), [
$v = \validator($request->all(), [
'username' => 'required|alpha_dash|string|between:3,25|unique:users',
'password' => 'required|string|between:6,16',
'email' => 'required|string|email|max:70|unique:users',
@@ -123,18 +123,18 @@ class RegisterController extends Controller
}
if ($v->fails()) {
return redirect()->route('registrationForm', ['code' => $code])
return \redirect()->route('registrationForm', ['code' => $code])
->withErrors($v->errors());
}
$user->save();
$privacy = new UserPrivacy();
$privacy->setDefaultValues();
$privacy->user_id = $user->id;
$privacy->save();
$notification = new UserNotification();
$notification->setDefaultValues();
$notification->user_id = $user->id;
$notification->save();
$userPrivacy = new UserPrivacy();
$userPrivacy->setDefaultValues();
$userPrivacy->user_id = $user->id;
$userPrivacy->save();
$userNotification = new UserNotification();
$userNotification->setDefaultValues();
$userNotification->user_id = $user->id;
$userNotification->save();
if ($key) {
// Update The Invite Record
$key->accepted_by = $user->id;
@@ -142,36 +142,36 @@ class RegisterController extends Controller
$key->save();
}
// Handle The Activation System
$token = hash_hmac('sha256', $user->username.$user->email.Str::random(16), config('app.key'));
$activation = new UserActivation();
$activation->user_id = $user->id;
$activation->token = $token;
$activation->save();
$token = \hash_hmac('sha256', $user->username.$user->email.Str::random(16), \config('app.key'));
$userActivation = new UserActivation();
$userActivation->user_id = $user->id;
$userActivation->token = $token;
$userActivation->save();
$this->dispatch(new SendActivationMail($user, $token));
// Select A Random Welcome Message
$profile_url = href_profile($user);
$profile_url = \href_profile($user);
$welcomeArray = [
sprintf('[url=%s]%s[/url], Welcome to ', $profile_url, $user->username).config('other.title').'! Hope you enjoy the community :rocket:',
sprintf("[url=%s]%s[/url], We've been expecting you :space_invader:", $profile_url, $user->username),
sprintf("[url=%s]%s[/url] has arrived. Party's over. :cry:", $profile_url, $user->username),
sprintf("It's a bird! It's a plane! Nevermind, it's just [url=%s]%s[/url].", $profile_url, $user->username),
sprintf('Ready player [url=%s]%s[/url].', $profile_url, $user->username),
sprintf('A wild [url=%s]%s[/url] appeared.', $profile_url, $user->username),
'Welcome to '.config('other.title').sprintf(' [url=%s]%s[/url]. We were expecting you ( ͡° ͜ʖ ͡°)', $profile_url, $user->username),
\sprintf('[url=%s]%s[/url], Welcome to ', $profile_url, $user->username).\config('other.title').'! Hope you enjoy the community :rocket:',
\sprintf("[url=%s]%s[/url], We've been expecting you :space_invader:", $profile_url, $user->username),
\sprintf("[url=%s]%s[/url] has arrived. Party's over. :cry:", $profile_url, $user->username),
\sprintf("It's a bird! It's a plane! Nevermind, it's just [url=%s]%s[/url].", $profile_url, $user->username),
\sprintf('Ready player [url=%s]%s[/url].', $profile_url, $user->username),
\sprintf('A wild [url=%s]%s[/url] appeared.', $profile_url, $user->username),
'Welcome to '.\config('other.title').\sprintf(' [url=%s]%s[/url]. We were expecting you ( ͡° ͜ʖ ͡°)', $profile_url, $user->username),
];
$selected = mt_rand(0, count($welcomeArray) - 1);
$this->chat->systemMessage(
$selected = \mt_rand(0, \count($welcomeArray) - 1);
$this->chatRepository->systemMessage(
$welcomeArray[$selected]
);
// Send Welcome PM
$pm = new PrivateMessage();
$pm->sender_id = 1;
$pm->receiver_id = $user->id;
$pm->subject = config('welcomepm.subject');
$pm->message = config('welcomepm.message');
$pm->save();
$privateMessage = new PrivateMessage();
$privateMessage->sender_id = 1;
$privateMessage->receiver_id = $user->id;
$privateMessage->subject = \config('welcomepm.subject');
$privateMessage->message = \config('welcomepm.message');
$privateMessage->save();
return redirect()->route('login')
->withSuccess(trans('auth.register-thanks'));
return \redirect()->route('login')
->withSuccess(\trans('auth.register-thanks'));
}
}

6
app/Http/Controllers/Auth/ResetPasswordController.php Executable file → Normal file
View File

@@ -32,9 +32,9 @@ class ResetPasswordController extends Controller
protected function resetPassword($user, $password)
{
$validating_group = cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$member_group = cache()->rememberForever('member_group', fn () => Group::where('slug', '=', 'user')->pluck('id'));
$user->password = bcrypt($password);
$validating_group = \cache()->rememberForever('validating_group', fn () => Group::where('slug', '=', 'validating')->pluck('id'));
$member_group = \cache()->rememberForever('member_group', fn () => Group::where('slug', '=', 'user')->pluck('id'));
$user->password = \bcrypt($password);
$user->remember_token = Str::random(60);
if ($user->group_id === $validating_group[0]) {

View File

@@ -18,6 +18,9 @@ use App\Traits\TwoStep;
use Carbon\Carbon;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\Auth\TwoStepControllerTest
*/
class TwoStepController extends Controller
{
use TwoStep;
@@ -55,14 +58,14 @@ class TwoStepController extends Controller
*/
private function setUser2StepData()
{
$user = auth()->user();
$user = \auth()->user();
$twoStepAuth = $this->getTwoStepAuthStatus($user->id);
$authCount = $twoStepAuth->authCount;
$this->_user = $user;
$this->_twoStepAuth = $twoStepAuth;
$this->_authCount = $authCount;
$this->_authStatus = $twoStepAuth->authStatus;
$this->_remainingAttempts = config('auth.TwoStepExceededCount') - $authCount;
$this->_remainingAttempts = \config('auth.TwoStepExceededCount') - $authCount;
}
/**
@@ -78,7 +81,7 @@ class TwoStepController extends Controller
$this->_twoStepAuth->save();
$returnData = [
'message' => trans('auth.titleFailed'),
'message' => \trans('auth.titleFailed'),
'authCount' => $this->_authCount,
'remainingAttempts' => $this->_remainingAttempts,
];
@@ -95,12 +98,12 @@ class TwoStepController extends Controller
*
* @throws \Exception
*
* @return \Illuminate\Http\Response
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showVerification()
{
if (! config('auth.TwoStepEnabled')) {
abort(404);
if (! \config('auth.TwoStepEnabled')) {
\abort(404);
}
$twoStepAuth = $this->_twoStepAuth;
@@ -115,16 +118,16 @@ class TwoStepController extends Controller
'remainingAttempts' => $this->_remainingAttempts + 1,
];
if ($this->_authCount > config('auth.TwoStepExceededCount')) {
if ($this->_authCount > \config('auth.TwoStepExceededCount')) {
$exceededTimeDetails = $this->exceededTimeParser($twoStepAuth->updated_at);
$data['timeUntilUnlock'] = $exceededTimeDetails['tomorrow'];
$data['timeCountdownUnlock'] = $exceededTimeDetails['remaining'];
return view('auth.twostep-exceeded')->with($data);
return \view('auth.twostep-exceeded')->with($data);
}
$now = new Carbon();
$carbon = new Carbon();
$sentTimestamp = $twoStepAuth->requestDate;
if (! $twoStepAuth->authCode) {
@@ -135,16 +138,16 @@ class TwoStepController extends Controller
if (! $sentTimestamp) {
$this->sendVerificationCodeNotification($twoStepAuth);
} else {
$timeBuffer = config('laravel2step.laravel2stepTimeResetBufferSeconds');
$timeBuffer = \config('laravel2step.laravel2stepTimeResetBufferSeconds');
$timeAllowedToSendCode = $sentTimestamp->addSeconds($timeBuffer);
if ($now->gt($timeAllowedToSendCode)) {
if ($carbon->gt($timeAllowedToSendCode)) {
$this->sendVerificationCodeNotification($twoStepAuth);
$twoStepAuth->requestDate = new Carbon();
$twoStepAuth->save();
}
}
return view('auth.twostep-verification')->with($data);
return \view('auth.twostep-verification')->with($data);
}
/**
@@ -152,16 +155,18 @@ class TwoStepController extends Controller
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
* @throws \Exception
*
* @return \Illuminate\Http\JsonResponse
*/
public function verify(Request $request)
{
if (! config('auth.TwoStepEnabled')) {
abort(404);
if (! \config('auth.TwoStepEnabled')) {
\abort(404);
}
if ($request->ajax()) {
$validator = validator($request->all(), [
$validator = \validator($request->all(), [
'v_input_1' => 'required|min:1|max:1',
'v_input_2' => 'required|min:1|max:1',
'v_input_3' => 'required|min:1|max:1',
@@ -171,7 +176,7 @@ class TwoStepController extends Controller
if ($validator->fails()) {
$returnData = $this->invalidCodeReturnData($validator->errors());
return response()->json($returnData, 418);
return \response()->json($returnData, 418);
}
$code = $request->v_input_1.$request->v_input_2.$request->v_input_3.$request->v_input_4;
@@ -180,40 +185,40 @@ class TwoStepController extends Controller
if ($validCode != $code) {
$returnData = $this->invalidCodeReturnData();
return response()->json($returnData, 418);
return \response()->json($returnData, 418);
}
$this->resetActivationCountdown($this->_twoStepAuth);
$returnData = [
'nextUri' => session('nextUri', '/'),
'message' => trans('auth.titlePassed'),
'nextUri' => \session('nextUri', '/'),
'message' => \trans('auth.titlePassed'),
];
return response()->json($returnData, 200);
return \response()->json($returnData, 200);
}
abort(404);
\abort(404);
}
/**
* Resend the validation code triggered by user.
*
* @return \Illuminate\Http\Response
* @return \Illuminate\Http\JsonResponse
*/
public function resend()
{
if (! config('auth.TwoStepEnabled')) {
abort(404);
if (! \config('auth.TwoStepEnabled')) {
\abort(404);
}
$twoStepAuth = $this->_twoStepAuth;
$this->sendVerificationCodeNotification($twoStepAuth);
$returnData = [
'title' => trans('auth.verificationEmailSuccess'),
'message' => trans('auth.verificationEmailSentMsg'),
'title' => \trans('auth.verificationEmailSuccess'),
'message' => \trans('auth.verificationEmailSentMsg'),
];
return response()->json($returnData, 200);
return \response()->json($returnData, 200);
}
}

View File

@@ -29,12 +29,15 @@ use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* @see \Tests\Feature\Http\Controllers\BonusControllerTest
*/
class BonusController extends Controller
{
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* The library used for parsing byte units.
@@ -46,16 +49,16 @@ class BonusController extends Controller
/**
* BonusController Constructor.
*
* @param ByteUnits $byteUnits
* @param ChatRepository $chat
* @param \App\Interfaces\ByteUnitsInterface $byteUnits
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(
\App\Interfaces\ByteUnitsInterface $byteUnits,
ChatRepository $chat
ChatRepository $chatRepository
) {
$this->byteUnits = $byteUnits;
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
@@ -76,7 +79,7 @@ class BonusController extends Controller
$gifts_sent = BonTransactions::where('sender', '=', $user->id)->where('name', '=', 'gift')->sum('cost');
$gifts_received = BonTransactions::where('receiver', '=', $user->id)->where('name', '=', 'gift')->sum('cost');
return view('bonus.gifts', [
return \view('bonus.gifts', [
'user' => $user,
'gifttransactions' => $gifttransactions,
'userbon' => $userbon,
@@ -103,7 +106,7 @@ class BonusController extends Controller
$tips_sent = BonTransactions::where('sender', '=', $user->id)->where('name', '=', 'tip')->sum('cost');
$tips_received = BonTransactions::where('receiver', '=', $user->id)->where('name', '=', 'tip')->sum('cost');
return view('bonus.tips', [
return \view('bonus.tips', [
'user' => $user,
'bontransactions' => $bontransactions,
'userbon' => $userbon,
@@ -131,7 +134,7 @@ class BonusController extends Controller
$personalFreeleech = $BonExchange->getPersonalFreeleechOption();
$invite = $BonExchange->getInviteOption();
return view('bonus.store', [
return \view('bonus.store', [
'userbon' => $userbon,
'activefl' => $activefl,
'bontransactions' => $bontransactions,
@@ -154,7 +157,7 @@ class BonusController extends Controller
$user = $request->user();
$userbon = $user->getSeedbonus();
return view('bonus.gift', [
return \view('bonus.gift', [
'userbon' => $userbon,
]);
}
@@ -208,7 +211,7 @@ class BonusController extends Controller
$minute = $total / 60;
$second = $minute / 60;
return view('bonus.index', [
return \view('bonus.index', [
'userbon' => $userbon,
'dying' => $dying,
'legendary' => $legendary,
@@ -245,25 +248,25 @@ class BonusController extends Controller
$user = $request->user();
$userbon = $user->seedbonus;
$BonExchange = resolve(BonExchange::class);
$BonExchange = \resolve(BonExchange::class);
$itemCost = $BonExchange->getItemCost($id);
if ($userbon >= $itemCost) {
$flag = $this->doItemExchange($user->id, $id);
if ($flag === '') {
return redirect()->route('bonus_store')
return \redirect()->route('bonus_store')
->withErrors('Bonus Exchange Failed!');
}
$user->seedbonus -= $itemCost;
$user->save();
} else {
return redirect()->route('bonus_store')
return \redirect()->route('bonus_store')
->withErrors('Bonus Exchange Failed!');
}
return redirect()->route('bonus_store')
return \redirect()->route('bonus_store')
->withSuccess('Bonus Exchange Successful');
}
@@ -282,7 +285,7 @@ class BonusController extends Controller
$user_acc = User::findOrFail($userID);
$activefl = PersonalFreeleech::where('user_id', '=', $user_acc->id)->first();
$bon_transactions = resolve(BonTransactions::class);
$bon_transactions = \resolve(BonTransactions::class);
if ($item['upload'] == true) {
$user_acc->uploaded += $item['value'];
@@ -296,18 +299,18 @@ class BonusController extends Controller
}
} elseif ($item['personal_freeleech'] == true) {
if (! $activefl) {
$personal_freeleech = new PersonalFreeleech();
$personal_freeleech->user_id = $user_acc->id;
$personal_freeleech->save();
$personalFreeleech = new PersonalFreeleech();
$personalFreeleech->user_id = $user_acc->id;
$personalFreeleech->save();
// Send Private Message
$pm = new PrivateMessage();
$pm->sender_id = 1;
$pm->receiver_id = $user_acc->id;
$pm->subject = 'Personal 24 Hour Freeleech Activated';
$pm->message = sprintf('Your [b]Personal 24 Hour Freeleech[/b] session has started! It will expire on %s [b]', $current->addDays(1)->toDayDateTimeString()).config('app.timezone').'[/b]!
$privateMessage = new PrivateMessage();
$privateMessage->sender_id = 1;
$privateMessage->receiver_id = $user_acc->id;
$privateMessage->subject = 'Personal 24 Hour Freeleech Activated';
$privateMessage->message = \sprintf('Your [b]Personal 24 Hour Freeleech[/b] session has started! It will expire on %s [b]', $current->addDays(1)->toDayDateTimeString()).\config('app.timezone').'[/b]!
[color=red][b]THIS IS AN AUTOMATED SYSTEM MESSAGE, PLEASE DO NOT REPLY![/b][/color]';
$pm->save();
$privateMessage->save();
} else {
return false;
}
@@ -341,9 +344,9 @@ class BonusController extends Controller
{
$user = $request->user();
$v = validator($request->all(), [
$v = \validator($request->all(), [
'to_username' => 'required|exists:users,username|max:180',
'bonus_points' => sprintf('required|numeric|min:1|max:%s', $user->seedbonus),
'bonus_points' => \sprintf('required|numeric|min:1|max:%s', $user->seedbonus),
'bonus_message' => 'required|string',
]);
@@ -356,7 +359,7 @@ class BonusController extends Controller
$recipient = User::where('username', '=', $request->input('to_username'))->first();
if (! $recipient || $recipient->id == $user->id) {
return redirect()->route('bonus_store')
return \redirect()->route('bonus_store')
->withErrors('Unable to find specified user');
}
@@ -367,56 +370,56 @@ class BonusController extends Controller
$user->seedbonus -= $value;
$user->save();
$transaction = new BonTransactions();
$transaction->itemID = 0;
$transaction->name = 'gift';
$transaction->cost = $value;
$transaction->sender = $user->id;
$transaction->receiver = $recipient->id;
$transaction->comment = $request->input('bonus_message');
$transaction->torrent_id = null;
$transaction->save();
$bonTransactions = new BonTransactions();
$bonTransactions->itemID = 0;
$bonTransactions->name = 'gift';
$bonTransactions->cost = $value;
$bonTransactions->sender = $user->id;
$bonTransactions->receiver = $recipient->id;
$bonTransactions->comment = $request->input('bonus_message');
$bonTransactions->torrent_id = null;
$bonTransactions->save();
if ($user->id != $recipient->id && $recipient->acceptsNotification($request->user(), $recipient, 'bon', 'show_bon_gift')) {
$recipient->notify(new NewBon('gift', $user->username, $transaction));
$recipient->notify(new NewBon('gift', $user->username, $bonTransactions));
}
$profile_url = href_profile($user);
$recipient_url = href_profile($recipient);
$profile_url = \href_profile($user);
$recipient_url = \href_profile($recipient);
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has gifted %s BON to [url=%s]%s[/url]', $profile_url, $user->username, $value, $recipient_url, $recipient->username)
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has gifted %s BON to [url=%s]%s[/url]', $profile_url, $user->username, $value, $recipient_url, $recipient->username)
);
if ($dest == 'profile') {
return redirect()->route('users.show', ['username' => $recipient->username])
return \redirect()->route('users.show', ['username' => $recipient->username])
->withSuccess('Gift Sent');
}
return redirect()->route('bonus_gift')
return \redirect()->route('bonus_gift')
->withSuccess('Gift Sent');
}
$v = validator($request->all(), [
$v = \validator($request->all(), [
'to_username' => 'required|exists:users,username|max:180',
]);
if ($v->passes()) {
$recipient = User::where('username', 'LIKE', $request->input('to_username'))->first();
if (! $recipient || $recipient->id == $user->id) {
return redirect()->route('bonus_store')
return \redirect()->route('bonus_store')
->withErrors('Unable to find specified user');
}
if ($dest == 'profile') {
return redirect()->route('users.show', ['username' => $recipient->username])
return \redirect()->route('users.show', ['username' => $recipient->username])
->withErrors('You Must Enter An Amount And Message!');
}
return redirect()->route('bonus_gift')
return \redirect()->route('bonus_gift')
->withErrors('You Must Enter An Amount And Message!');
}
return redirect()->route('bonus_store')
return \redirect()->route('bonus_store')
->withErrors('Unable to find specified user');
}
@@ -436,15 +439,15 @@ class BonusController extends Controller
$tip_amount = $request->input('tip');
if ($tip_amount > $user->seedbonus) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors('Your To Broke To Tip The Uploader!');
}
if ($user->id == $torrent->user_id) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors('You Cannot Tip Yourself!');
}
if ($tip_amount <= 0) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors('You Cannot Tip A Negative Amount!');
}
$uploader->seedbonus += $tip_amount;
@@ -453,21 +456,21 @@ class BonusController extends Controller
$user->seedbonus -= $tip_amount;
$user->save();
$transaction = new BonTransactions();
$transaction->itemID = 0;
$transaction->name = 'tip';
$transaction->cost = $tip_amount;
$transaction->sender = $user->id;
$transaction->receiver = $uploader->id;
$transaction->comment = 'tip';
$transaction->torrent_id = $torrent->id;
$transaction->save();
$bonTransactions = new BonTransactions();
$bonTransactions->itemID = 0;
$bonTransactions->name = 'tip';
$bonTransactions->cost = $tip_amount;
$bonTransactions->sender = $user->id;
$bonTransactions->receiver = $uploader->id;
$bonTransactions->comment = 'tip';
$bonTransactions->torrent_id = $torrent->id;
$bonTransactions->save();
if ($uploader->acceptsNotification($request->user(), $uploader, 'torrent', 'show_torrent_tip')) {
$uploader->notify(new NewUploadTip('torrent', $user->username, $tip_amount, $torrent));
}
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withSuccess('Your Tip Was Successfully Applied!');
}
@@ -486,20 +489,20 @@ class BonusController extends Controller
$post = Post::with('topic')->findOrFail($request->input('post'));
$poster = User::where('id', '=', $post->user_id)->firstOrFail();
} else {
abort(404);
\abort(404);
}
$tip_amount = $request->input('tip');
if ($tip_amount > $user->seedbonus) {
return redirect()->route('forum_topic', ['id' => $post->topic->id])
return \redirect()->route('forum_topic', ['id' => $post->topic->id])
->withErrors('You Are To Broke To Tip The Poster!');
}
if ($user->id == $poster->id) {
return redirect()->route('forum_topic', ['id' => $post->topic->id])
return \redirect()->route('forum_topic', ['id' => $post->topic->id])
->withErrors('You Cannot Tip Yourself!');
}
if ($tip_amount <= 0) {
return redirect()->route('forum_topic', ['id' => $post->topic->id])
return \redirect()->route('forum_topic', ['id' => $post->topic->id])
->withErrors('You Cannot Tip A Negative Amount!');
}
$poster->seedbonus += $tip_amount;
@@ -508,19 +511,19 @@ class BonusController extends Controller
$user->seedbonus -= $tip_amount;
$user->save();
$transaction = new BonTransactions();
$transaction->itemID = 0;
$transaction->name = 'tip';
$transaction->cost = $tip_amount;
$transaction->sender = $user->id;
$transaction->receiver = $poster->id;
$transaction->comment = 'tip';
$transaction->post_id = $post->id;
$transaction->save();
$bonTransactions = new BonTransactions();
$bonTransactions->itemID = 0;
$bonTransactions->name = 'tip';
$bonTransactions->cost = $tip_amount;
$bonTransactions->sender = $user->id;
$bonTransactions->receiver = $poster->id;
$bonTransactions->comment = 'tip';
$bonTransactions->post_id = $post->id;
$bonTransactions->save();
$poster->notify(new NewPostTip('forum', $user->username, $tip_amount, $post));
return redirect()->route('forum_topic', ['id' => $post->topic->id])
return \redirect()->route('forum_topic', ['id' => $post->topic->id])
->withSuccess('Your Tip Was Successfully Applied!');
}

View File

@@ -18,6 +18,9 @@ use App\Models\Torrent;
use App\Models\User;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\BookmarkControllerTest
*/
class BookmarkController extends Controller
{
/**
@@ -32,12 +35,12 @@ class BookmarkController extends Controller
{
$user = User::with('bookmarks')->where('username', '=', $username)->firstOrFail();
abort_unless(($request->user()->group->is_modo || $request->user()->id == $user->id), 403);
\abort_unless(($request->user()->group->is_modo || $request->user()->id == $user->id), 403);
$bookmarks = $user->bookmarks()->latest()->paginate(25);
$personal_freeleech = PersonalFreeleech::where('user_id', '=', $user->id)->first();
return view('user.bookmarks', [
return \view('user.bookmarks', [
'user' => $user,
'personal_freeleech' => $personal_freeleech,
'bookmarks' => $bookmarks,
@@ -58,12 +61,12 @@ class BookmarkController extends Controller
$torrent = Torrent::withAnyStatus()->findOrFail($id);
if ($request->user()->isBookmarked($torrent->id)) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors('Torrent has already been bookmarked.');
}
$request->user()->bookmarks()->attach($torrent->id);
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withSuccess('Torrent Has Been Bookmarked Successfully!');
}
@@ -80,7 +83,7 @@ class BookmarkController extends Controller
$torrent = Torrent::withAnyStatus()->findOrFail($id);
$request->user()->bookmarks()->detach($torrent->id);
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withSuccess('Torrent Has Been Unbookmarked Successfully!');
}
}

11
app/Http/Controllers/CategoryController.php Executable file → Normal file
View File

@@ -18,6 +18,9 @@ use App\Models\PersonalFreeleech;
use App\Models\Torrent;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\CategoryControllerTest
*/
class CategoryController extends Controller
{
/**
@@ -29,7 +32,7 @@ class CategoryController extends Controller
{
$categories = Category::withCount('torrents')->get()->sortBy('position');
return view('category.index', ['categories' => $categories]);
return \view('category.index', ['categories' => $categories]);
}
/**
@@ -43,13 +46,13 @@ class CategoryController extends Controller
public function show(Request $request, $id)
{
$user = $request->user();
$client = new \App\Services\MovieScrapper(config('api-keys.tmdb'), config('api-keys.tvdb'), config('api-keys.omdb'));
$movieScrapper = new \App\Services\MovieScrapper(\config('api-keys.tmdb'), \config('api-keys.tvdb'), \config('api-keys.omdb'));
$category = Category::select(['id', 'name'])->findOrFail($id);
$torrents = Torrent::with(['user', 'category', 'type'])->withCount(['thanks', 'comments'])->where('category_id', '=', $id)->orderBy('sticky', 'desc')->latest()->paginate(25);
$personal_freeleech = PersonalFreeleech::where('user_id', '=', $user->id)->first();
return view('category.show', [
'client' => $client,
return \view('category.show', [
'client' => $movieScrapper,
'torrents' => $torrents,
'user' => $user,
'category' => $category,

View File

@@ -36,28 +36,31 @@ use App\Repositories\ChatRepository;
use App\Repositories\TaggedUserRepository;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\CommentControllerTest
*/
class CommentController extends Controller
{
/**
* @var TaggedUserRepository
*/
private $tag;
private $taggedUserRepository;
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* CommentController Constructor.
*
* @param TaggedUserRepository $tag
* @param ChatRepository $chat
* @param \App\Repositories\TaggedUserRepository $taggedUserRepository
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(TaggedUserRepository $tag, ChatRepository $chat)
public function __construct(TaggedUserRepository $taggedUserRepository, ChatRepository $chatRepository)
{
$this->tag = $tag;
$this->chat = $chat;
$this->taggedUserRepository = $taggedUserRepository;
$this->chatRepository = $chatRepository;
}
/**
@@ -74,7 +77,7 @@ class CommentController extends Controller
$user = $request->user();
if ($user->can_comment == 0) {
return redirect()->route('articles.show', ['id' => $article->id])
return \redirect()->route('articles.show', ['id' => $article->id])
->withErrors('Your Comment Rights Have Been Revoked!');
}
@@ -84,7 +87,7 @@ class CommentController extends Controller
$comment->user_id = $user->id;
$comment->article_id = $article->id;
$v = validator($comment->toArray(), [
$v = \validator($comment->toArray(), [
'content' => 'required',
'user_id' => 'required',
'article_id' => 'required',
@@ -92,30 +95,30 @@ class CommentController extends Controller
]);
if ($v->fails()) {
return redirect()->route('articles.show', ['id' => $article->id])
return \redirect()->route('articles.show', ['id' => $article->id])
->withErrors($v->errors());
}
$comment->save();
$article_url = href_article($article);
$profile_url = href_profile($user);
$article_url = \href_article($article);
$profile_url = \href_profile($user);
// Auto Shout
if ($comment->anon == 0) {
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has left a comment on article [url=%s]%s[/url]', $profile_url, $user->username, $article_url, $article->title)
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has left a comment on article [url=%s]%s[/url]', $profile_url, $user->username, $article_url, $article->title)
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user has left a comment on article [url=%s]%s[/url]', $article_url, $article->title)
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has left a comment on article [url=%s]%s[/url]', $article_url, $article->title)
);
}
if ($this->tag->hasTags($request->input('content'))) {
if ($this->tag->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = collect([]);
if ($this->taggedUserRepository->hasTags($request->input('content'))) {
if ($this->taggedUserRepository->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = \collect([]);
$article->comments()->get()->each(function ($c) use ($users) {
$users->push($c->user);
});
$this->tag->messageCommentUsers(
$this->taggedUserRepository->messageCommentUsers(
'article',
$users,
$user,
@@ -124,7 +127,7 @@ class CommentController extends Controller
);
} else {
$sender = $comment->anon ? 'Anonymous' : $user->username;
$this->tag->messageTaggedCommentUsers(
$this->taggedUserRepository->messageTaggedCommentUsers(
'article',
$request->input('content'),
$user,
@@ -147,7 +150,7 @@ class CommentController extends Controller
$user->addProgress(new UserMade800Comments(), 1);
$user->addProgress(new UserMade900Comments(), 1);
return redirect()->route('articles.show', ['id' => $article->id])
return \redirect()->route('articles.show', ['id' => $article->id])
->withSuccess('Your Comment Has Been Added!');
}
@@ -162,10 +165,10 @@ class CommentController extends Controller
public function playlist(Request $request, $id)
{
$playlist = Playlist::findOrFail($id);
$user = auth()->user();
$user = \auth()->user();
if ($user->can_comment == 0) {
return redirect()->route('playlists.show', ['id' => $playlist->id])
return \redirect()->route('playlists.show', ['id' => $playlist->id])
->withErrors('Your Comment Rights Have Been Revoked!');
}
@@ -175,7 +178,7 @@ class CommentController extends Controller
$comment->user_id = $user->id;
$comment->playlist_id = $playlist->id;
$v = validator($comment->toArray(), [
$v = \validator($comment->toArray(), [
'content' => 'required',
'user_id' => 'required',
'playlist_id' => 'required',
@@ -183,30 +186,30 @@ class CommentController extends Controller
]);
if ($v->fails()) {
return redirect()->route('playlists.show', ['id' => $playlist->id])
return \redirect()->route('playlists.show', ['id' => $playlist->id])
->withErrors($v->errors());
}
$comment->save();
$playlist_url = href_playlist($playlist);
$profile_url = href_profile($user);
$playlist_url = \href_playlist($playlist);
$profile_url = \href_profile($user);
// Auto Shout
if ($comment->anon == 0) {
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has left a comment on playlist [url=%s]%s[/url]', $profile_url, $user->username, $playlist_url, $playlist->name)
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has left a comment on playlist [url=%s]%s[/url]', $profile_url, $user->username, $playlist_url, $playlist->name)
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user has left a comment on playlist [url=%s]%s[/url]', $playlist_url, $playlist->name)
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has left a comment on playlist [url=%s]%s[/url]', $playlist_url, $playlist->name)
);
}
if ($this->tag->hasTags($request->input('content'))) {
if ($this->tag->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = collect([]);
if ($this->taggedUserRepository->hasTags($request->input('content'))) {
if ($this->taggedUserRepository->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = \collect([]);
$playlist->comments()->get()->each(function ($c) use ($users) {
$users->push($c->user);
});
$this->tag->messageCommentUsers(
$this->taggedUserRepository->messageCommentUsers(
'playlist',
$users,
$user,
@@ -215,7 +218,7 @@ class CommentController extends Controller
);
} else {
$sender = $comment->anon ? 'Anonymous' : $user->username;
$this->tag->messageTaggedCommentUsers(
$this->taggedUserRepository->messageTaggedCommentUsers(
'playlist',
$request->input('content'),
$user,
@@ -238,7 +241,7 @@ class CommentController extends Controller
$user->addProgress(new UserMade800Comments(), 1);
$user->addProgress(new UserMade900Comments(), 1);
return redirect()->route('playlists.show', ['id' => $playlist->id, 'hash' => '#comments'])
return \redirect()->route('playlists.show', ['id' => $playlist->id, 'hash' => '#comments'])
->withSuccess('Your Comment Has Been Added!');
}
@@ -256,7 +259,7 @@ class CommentController extends Controller
$user = $request->user();
if ($user->can_comment == 0) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors('Your Comment Rights Have Been Revoked!');
}
@@ -266,7 +269,7 @@ class CommentController extends Controller
$comment->user_id = $user->id;
$comment->torrent_id = $torrent->id;
$v = validator($comment->toArray(), [
$v = \validator($comment->toArray(), [
'content' => 'required',
'user_id' => 'required',
'torrent_id' => 'required',
@@ -274,7 +277,7 @@ class CommentController extends Controller
]);
if ($v->fails()) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors($v->errors());
}
$comment->save();
@@ -282,26 +285,26 @@ class CommentController extends Controller
if ($user->id != $torrent->user_id) {
$torrent->notifyUploader('comment', $comment);
}
$torrent_url = href_torrent($torrent);
$profile_url = href_profile($user);
$torrent_url = \href_torrent($torrent);
$profile_url = \href_profile($user);
// Auto Shout
if ($comment->anon == 0) {
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has left a comment on Torrent [url=%s]%s[/url]', $profile_url, $user->username, $torrent_url, $torrent->name)
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has left a comment on Torrent [url=%s]%s[/url]', $profile_url, $user->username, $torrent_url, $torrent->name)
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user has left a comment on torrent [url=%s]%s[/url]', $torrent_url, $torrent->name)
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has left a comment on torrent [url=%s]%s[/url]', $torrent_url, $torrent->name)
);
}
if ($this->tag->hasTags($request->input('content'))) {
if ($this->tag->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = collect([]);
if ($this->taggedUserRepository->hasTags($request->input('content'))) {
if ($this->taggedUserRepository->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = \collect([]);
$torrent->comments()->get()->each(function ($c) use ($users) {
$users->push($c->user);
});
$this->tag->messageCommentUsers(
$this->taggedUserRepository->messageCommentUsers(
'torrent',
$users,
$user,
@@ -310,7 +313,7 @@ class CommentController extends Controller
);
} else {
$sender = $comment->anon ? 'Anonymous' : $user->username;
$this->tag->messageTaggedCommentUsers(
$this->taggedUserRepository->messageTaggedCommentUsers(
'torrent',
$request->input('content'),
$user,
@@ -333,7 +336,7 @@ class CommentController extends Controller
$user->addProgress(new UserMade800Comments(), 1);
$user->addProgress(new UserMade900Comments(), 1);
return redirect()->route('torrent', ['id' => $torrent->id, 'hash' => '#comments'])
return \redirect()->route('torrent', ['id' => $torrent->id, 'hash' => '#comments'])
->withSuccess('Your Comment Has Been Added!');
}
@@ -351,7 +354,7 @@ class CommentController extends Controller
$user = $request->user();
if ($user->can_comment == 0) {
return redirect()->route('request', ['id' => $tr->id])
return \redirect()->route('request', ['id' => $tr->id])
->withErrors('Your Comment Rights Have Been Revoked!');
}
@@ -361,7 +364,7 @@ class CommentController extends Controller
$comment->user_id = $user->id;
$comment->requests_id = $tr->id;
$v = validator($comment->toArray(), [
$v = \validator($comment->toArray(), [
'content' => 'required',
'user_id' => 'required',
'requests_id' => 'required',
@@ -369,34 +372,34 @@ class CommentController extends Controller
]);
if ($v->fails()) {
return redirect()->route('request', ['id' => $tr->id])
return \redirect()->route('request', ['id' => $tr->id])
->withErrors($v->errors());
}
$comment->save();
$tr_url = href_request($tr);
$profile_url = href_profile($user);
$tr_url = \href_request($tr);
$profile_url = \href_profile($user);
// Auto Shout
if ($comment->anon == 0) {
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has left a comment on Request [url=%s]%s[/url]', $profile_url, $user->username, $tr_url, $tr->name)
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has left a comment on Request [url=%s]%s[/url]', $profile_url, $user->username, $tr_url, $tr->name)
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user has left a comment on Request [url=%s]%s[/url]', $tr_url, $tr->name)
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has left a comment on Request [url=%s]%s[/url]', $tr_url, $tr->name)
);
}
//Notification
if ($user->id != $tr->user_id) {
$tr->notifyRequester('comment', $comment);
}
if ($this->tag->hasTags($request->input('content'))) {
if ($this->tag->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = collect([]);
if ($this->taggedUserRepository->hasTags($request->input('content'))) {
if ($this->taggedUserRepository->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = \collect([]);
$tr->comments()->get()->each(function ($c) use ($users) {
$users->push($c->user);
});
$this->tag->messageCommentUsers(
$this->taggedUserRepository->messageCommentUsers(
'request',
$users,
$user,
@@ -405,7 +408,7 @@ class CommentController extends Controller
);
} else {
$sender = $comment->anon ? 'Anonymous' : $user->username;
$this->tag->messageTaggedCommentUsers(
$this->taggedUserRepository->messageTaggedCommentUsers(
'request',
$request->input('content'),
$user,
@@ -428,7 +431,7 @@ class CommentController extends Controller
$user->addProgress(new UserMade800Comments(), 1);
$user->addProgress(new UserMade900Comments(), 1);
return redirect()->route('request', ['id' => $tr->id, 'hash' => '#comments'])
return \redirect()->route('request', ['id' => $tr->id, 'hash' => '#comments'])
->withSuccess('Your Comment Has Been Added!');
}
@@ -446,7 +449,7 @@ class CommentController extends Controller
$user = $request->user();
if ($user->can_comment == 0) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors('Your Comment Rights Have Been Revoked!');
}
@@ -460,28 +463,28 @@ class CommentController extends Controller
];
} else {
$uploader = User::where('id', '=', $torrent->user_id)->first();
$uploader_url = href_profile($uploader);
$uploader_url = \href_profile($uploader);
$thankArray = [
sprintf('Thanks for the upload [url=%s][color=%s][b]%s[/b][/color][/url] :vulcan_tone2:', $uploader_url, $uploader->group->color, $uploader->username),
sprintf('Beautiful upload [url=%s][color=%s][b]%s[/b][/color][/url] :fire:', $uploader_url, $uploader->group->color, $uploader->username),
sprintf('Cheers [url=%s][color=%s][b]%s[/b][/color][/url] for the upload :beers:', $uploader_url, $uploader->group->color, $uploader->username),
\sprintf('Thanks for the upload [url=%s][color=%s][b]%s[/b][/color][/url] :vulcan_tone2:', $uploader_url, $uploader->group->color, $uploader->username),
\sprintf('Beautiful upload [url=%s][color=%s][b]%s[/b][/color][/url] :fire:', $uploader_url, $uploader->group->color, $uploader->username),
\sprintf('Cheers [url=%s][color=%s][b]%s[/b][/color][/url] for the upload :beers:', $uploader_url, $uploader->group->color, $uploader->username),
];
}
$selected = mt_rand(0, (is_countable($thankArray) ? count($thankArray) : 0) - 1);
$selected = \mt_rand(0, (\is_countable($thankArray) ? \count($thankArray) : 0) - 1);
$comment->content = $thankArray[$selected];
$comment->user_id = $user->id;
$comment->torrent_id = $torrent->id;
$v = validator($comment->toArray(), [
$v = \validator($comment->toArray(), [
'content' => 'required',
'user_id' => 'required',
'torrent_id' => 'required',
]);
if ($v->fails()) {
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withErrors($v->errors());
}
$comment->save();
@@ -503,13 +506,13 @@ class CommentController extends Controller
User::find($torrent->user_id)->notify(new NewComment('torrent', $comment));
}
// Auto Shout
$torrent_url = href_torrent($torrent);
$profile_url = href_profile($user);
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has left a comment on Torrent [url=%s]%s[/url]', $profile_url, $user->username, $torrent_url, $torrent->name)
$torrent_url = \href_torrent($torrent);
$profile_url = \href_profile($user);
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has left a comment on Torrent [url=%s]%s[/url]', $profile_url, $user->username, $torrent_url, $torrent->name)
);
return redirect()->route('torrent', ['id' => $torrent->id])
return \redirect()->route('torrent', ['id' => $torrent->id])
->withSuccess('Your Comment Has Been Added!');
}
@@ -526,29 +529,31 @@ class CommentController extends Controller
$user = $request->user();
$comment = Comment::findOrFail($comment_id);
abort_unless($user->group->is_modo || $user->id == $comment->user_id, 403);
\abort_unless($user->group->is_modo || $user->id == $comment->user_id, 403);
$content = $request->input('comment-edit');
$comment->content = $content;
$v = validator($comment->toArray(), [
$v = \validator($comment->toArray(), [
'content' => 'required',
]);
if ($v->fails()) {
return redirect()->back()
return \redirect()->back()
->withErrors($v->errors());
}
$comment->save();
return redirect()->back()->withSuccess('Comment Has Been Edited.');
return \redirect()->back()->withSuccess('Comment Has Been Edited.');
}
/**
* Delete A Comment.
*
* @param \Illuminate\Http\Request $request
* @param $comment_id
* @param $comment_id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
@@ -557,9 +562,9 @@ class CommentController extends Controller
$user = $request->user();
$comment = Comment::findOrFail($comment_id);
abort_unless($user->group->is_modo || $user->id == $comment->user_id, 403);
\abort_unless($user->group->is_modo || $user->id == $comment->user_id, 403);
$comment->delete();
return redirect()->back()->withSuccess('Comment Has Been Deleted.');
return \redirect()->back()->withSuccess('Comment Has Been Deleted.');
}
}

View File

@@ -18,6 +18,9 @@ use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
/**
* @see \Tests\Feature\Http\Controllers\ContactControllerTest
*/
class ContactController extends Controller
{
/**
@@ -27,7 +30,7 @@ class ContactController extends Controller
*/
public function index()
{
return view('contact.index');
return \view('contact.index');
}
/**
@@ -40,12 +43,12 @@ class ContactController extends Controller
public function store(Request $request)
{
// Fetch owner account
$user = User::where('username', config('unit3d.owner-username'))->first();
$user = User::where('username', \config('unit3d.owner-username'))->first();
$input = $request->all();
Mail::to($user->email, $user->username)->send(new Contact($input));
return redirect()->route('home.index')
return \redirect()->route('home.index')
->withSuccess('Your Message Was Successfully Sent');
}
}

0
app/Http/Controllers/Controller.php Executable file → Normal file
View File

View File

@@ -19,6 +19,9 @@ use App\Notifications\NewFollow;
use App\Notifications\NewUnfollow;
use Illuminate\Http\Request;
/**
* @see \Tests\Feature\Http\Controllers\FollowControllerTest
*/
class FollowController extends Controller
{
/**
@@ -34,7 +37,7 @@ class FollowController extends Controller
$user = User::where('username', '=', $username)->firstOrFail();
if ($request->user()->id == $user->id) {
return redirect()->route('users.show', ['username' => $user->username])
return \redirect()->route('users.show', ['username' => $user->username])
->withErrors('Nice try, but sadly you can not follow yourself.');
}
@@ -47,11 +50,11 @@ class FollowController extends Controller
$user->notify(new NewFollow('user', $request->user(), $user, $follow));
}
return redirect()->route('users.show', ['username' => $user->username])
->withSuccess(sprintf('You are now following %s', $user->username));
return \redirect()->route('users.show', ['username' => $user->username])
->withSuccess(\sprintf('You are now following %s', $user->username));
}
return redirect()->route('users.show', ['username' => $user->username])
return \redirect()->route('users.show', ['username' => $user->username])
->withErrors('You are already following this user');
}
@@ -74,11 +77,11 @@ class FollowController extends Controller
$user->notify(new NewUnfollow('user', $request->user(), $user, $follow));
}
return redirect()->route('users.show', ['username' => $user->username])
->withSuccess(sprintf('You are no longer following %s', $user->username));
return \redirect()->route('users.show', ['username' => $user->username])
->withSuccess(\sprintf('You are no longer following %s', $user->username));
}
return redirect()->route('users.show', ['username' => $user->username])
return \redirect()->route('users.show', ['username' => $user->username])
->withErrors('You are not following this user to begin with');
}
}

View File

@@ -17,6 +17,9 @@ use App\Models\Forum;
use App\Models\Post;
use App\Models\Topic;
/**
* @see \Tests\Feature\Http\Controllers\ForumCategoryControllerTest
*/
class ForumCategoryController extends Controller
{
/**
@@ -40,20 +43,20 @@ class ForumCategoryController extends Controller
// Check if this is a category or forum
if ($forum->parent_id != 0) {
return redirect()->route('forums.show', ['id' => $forum->id]);
return \redirect()->route('forums.show', ['id' => $forum->id]);
}
// Check if the user has permission to view the forum
$category = Forum::findOrFail($forum->id);
if ($category->getPermission()->show_forum != true) {
return redirect()->route('forums.index')
return \redirect()->route('forums.index')
->withErrors('You Do Not Have Access To This Category!');
}
// Fetch topics->posts in descending order
$topics = $forum->sub_topics()->latest('pinned')->latest('last_reply_at')->latest()->paginate(25);
return view('forum.category', [
return \view('forum.category', [
'forum' => $forum,
'topics' => $topics,
'category' => $category,

View File

@@ -20,28 +20,31 @@ use App\Repositories\ChatRepository;
use App\Repositories\TaggedUserRepository;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\Staff\ForumControllerTest
*/
class ForumController extends Controller
{
/**
* @var TaggedUserRepository
*/
private $tag;
private $taggedUserRepository;
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* ForumController Constructor.
*
* @param TaggedUserRepository $tag
* @param ChatRepository $chat
* @param \App\Repositories\TaggedUserRepository $taggedUserRepository
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(TaggedUserRepository $tag, ChatRepository $chat)
public function __construct(TaggedUserRepository $taggedUserRepository, ChatRepository $chatRepository)
{
$this->tag = $tag;
$this->chat = $chat;
$this->taggedUserRepository = $taggedUserRepository;
$this->chatRepository = $chatRepository;
}
/**
@@ -58,17 +61,17 @@ class ForumController extends Controller
$user = $request->user();
$pests = $user->group->permissions->where('show_forum', '=', 0)->pluck('forum_id')->toArray();
if (! is_array($pests)) {
if (! \is_array($pests)) {
$pests = [];
}
$topic_neos = $user->subscriptions->where('topic_id', '>', 0)->pluck('topic_id')->toArray();
if (! is_array($topic_neos)) {
if (! \is_array($topic_neos)) {
$topic_neos = [];
}
$forum_neos = $user->subscriptions->where('forum_id', '>', 0)->pluck('forum_id')->toArray();
if (! is_array($forum_neos)) {
if (! \is_array($forum_neos)) {
$forum_neos = [];
}
@@ -129,7 +132,7 @@ class ForumController extends Controller
$category = (int) $request->input('category');
if ($category > 0 && $category < 99_999_999_999) {
$children = Forum::where('parent_id', '=', $category)->get()->toArray();
if (is_array($children)) {
if (\is_array($children)) {
$result->where(function ($query) use ($category, $children) {
$query->where('topics.forum_id', '=', $category)->orWhereIn('topics.forum_id', $children);
});
@@ -139,7 +142,7 @@ class ForumController extends Controller
if ($request->has('body') && $request->input('body') != '') {
if ($request->has('sorting') && $request->input('sorting') != null) {
$sorting = sprintf('posts.%s', $request->input('sorting'));
$sorting = \sprintf('posts.%s', $request->input('sorting'));
$direction = $request->input('direction');
} else {
$sorting = 'posts.id';
@@ -148,7 +151,7 @@ class ForumController extends Controller
$results = $result->orderBy($sorting, $direction)->paginate(25);
} else {
if ($request->has('sorting') && $request->input('sorting') != null) {
$sorting = sprintf('topics.%s', $request->input('sorting'));
$sorting = \sprintf('topics.%s', $request->input('sorting'));
$direction = $request->input('direction');
} else {
$sorting = 'topics.last_reply_at';
@@ -168,7 +171,7 @@ class ForumController extends Controller
$params = $request->all();
return view($logger, [
return \view($logger, [
'categories' => $categories,
'results' => $results,
'user' => $user,
@@ -193,17 +196,17 @@ class ForumController extends Controller
$user = $request->user();
$pests = $user->group->permissions->where('show_forum', '=', 0)->pluck('forum_id')->toArray();
if (! is_array($pests)) {
if (! \is_array($pests)) {
$pests = [];
}
$topic_neos = $user->subscriptions->where('topic_id', '>', '0')->pluck('topic_id')->toArray();
if (! is_array($topic_neos)) {
if (! \is_array($topic_neos)) {
$topic_neos = [];
}
$forum_neos = $user->subscriptions->where('forum_id', '>', '0')->pluck('forum_id')->toArray();
if (! is_array($forum_neos)) {
if (! \is_array($forum_neos)) {
$forum_neos = [];
}
$result = Forum::with('subscription_topics')->selectRaw('forums.id,max(forums.position) as position,max(forums.num_topic) as num_topic,max(forums.num_post) as num_post,max(forums.last_topic_id) as last_topic_id,max(forums.last_topic_name) as last_topic_name,max(forums.last_topic_slug) as last_topic_slug,max(forums.last_post_user_id) as last_post_user_id,max(forums.last_post_user_username) as last_post_user_username,max(forums.name) as name,max(forums.slug) as slug,max(forums.description) as description,max(forums.parent_id) as parent_id,max(forums.created_at),max(forums.updated_at),max(topics.id) as topic_id,max(topics.created_at) as topic_created_at')->leftJoin('topics', 'forums.id', '=', 'topics.forum_id')->whereNotIn('topics.forum_id', $pests)->where(function ($query) use ($topic_neos, $forum_neos) {
@@ -222,7 +225,7 @@ class ForumController extends Controller
$params = $request->all();
return view('forum.subscriptions', [
return \view('forum.subscriptions', [
'results' => $results,
'user' => $user,
'name' => $request->input('name'),
@@ -248,7 +251,7 @@ class ForumController extends Controller
$user = $request->user();
$pests = $user->group->permissions->where('show_forum', '=', 0)->pluck('forum_id')->toArray();
if (! is_array($pests)) {
if (! \is_array($pests)) {
$pests = [];
}
@@ -261,7 +264,7 @@ class ForumController extends Controller
// Total Topics Count
$num_topics = Topic::count();
return view('forum.latest_topics', [
return \view('forum.latest_topics', [
'results' => $results,
'user' => $user,
'num_posts' => $num_posts,
@@ -282,7 +285,7 @@ class ForumController extends Controller
$user = $request->user();
$pests = $user->group->permissions->where('show_forum', '=', 0)->pluck('forum_id')->toArray();
if (! is_array($pests)) {
if (! \is_array($pests)) {
$pests = [];
}
@@ -295,7 +298,7 @@ class ForumController extends Controller
// Total Topics Count
$num_topics = Topic::count();
return view('forum.latest_posts', [
return \view('forum.latest_posts', [
'results' => $results,
'user' => $user,
'num_posts' => $num_posts,
@@ -320,7 +323,7 @@ class ForumController extends Controller
// Total Topics Count
$num_topics = Topic::count();
return view('forum.index', [
return \view('forum.index', [
'categories' => $categories,
'num_posts' => $num_posts,
'num_forums' => $num_forums,
@@ -349,20 +352,20 @@ class ForumController extends Controller
// Check if this is a category or forum
if ($forum->parent_id == 0) {
return redirect()->route('forums.categories.show', ['id' => $forum->id]);
return \redirect()->route('forums.categories.show', ['id' => $forum->id]);
}
// Check if the user has permission to view the forum
$category = Forum::findOrFail($forum->parent_id);
if ($category->getPermission()->show_forum != true) {
return redirect()->route('forums.index')
return \redirect()->route('forums.index')
->withErrors('You Do Not Have Access To This Forum!');
}
// Fetch topics->posts in descending order
$topics = $forum->topics()->latest('pinned')->latest('last_reply_at')->latest()->paginate(25);
return view('forum.display', [
return \view('forum.display', [
'forum' => $forum,
'topics' => $topics,
'category' => $category,

View File

@@ -20,21 +20,24 @@ use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
/**
* @see \Tests\Todo\Feature\Http\Controllers\GraveyardControllerTest
*/
class GraveyardController extends Controller
{
/**
* @var TorrentFacetedRepository
*/
private $faceted;
private $torrentFacetedRepository;
/**
* GraveyardController Constructor.
*
* @param TorrentFacetedRepository $faceted
* @param \App\Repositories\TorrentFacetedRepository $torrentFacetedRepository
*/
public function __construct(TorrentFacetedRepository $faceted)
public function __construct(TorrentFacetedRepository $torrentFacetedRepository)
{
$this->faceted = $faceted;
$this->torrentFacetedRepository = $torrentFacetedRepository;
}
/**
@@ -49,10 +52,10 @@ class GraveyardController extends Controller
$current = Carbon::now();
$user = $request->user();
$torrents = Torrent::with('category', 'type')->where('created_at', '<', $current->copy()->subDays(30)->toDateTimeString())->paginate(25);
$repository = $this->faceted;
$repository = $this->torrentFacetedRepository;
$deadcount = Torrent::where('seeders', '=', 0)->where('created_at', '<', $current->copy()->subDays(30)->toDateTimeString())->count();
return view('graveyard.index', [
return \view('graveyard.index', [
'user' => $user,
'torrents' => $torrents,
'repository' => $repository,
@@ -76,14 +79,14 @@ class GraveyardController extends Controller
$user = $request->user();
$search = $request->input('search');
$imdb_id = Str::startsWith($request->get('imdb'), 'tt') ? $request->get('imdb') : 'tt'.$request->get('imdb');
$imdb = str_replace('tt', '', $imdb_id);
$imdb = \str_replace('tt', '', $imdb_id);
$tvdb = $request->input('tvdb');
$tmdb = $request->input('tmdb');
$mal = $request->input('mal');
$categories = $request->input('categories');
$types = $request->input('types');
$terms = explode(' ', $search);
$terms = \explode(' ', $search);
$search = '';
foreach ($terms as $term) {
$search .= '%'.$term.'%';
@@ -96,7 +99,7 @@ class GraveyardController extends Controller
}
if ($request->has('imdb') && $request->input('imdb') != null) {
$torrent->where('imdb', '=', str_replace('tt', '', $imdb));
$torrent->where('imdb', '=', \str_replace('tt', '', $imdb));
}
if ($request->has('tvdb') && $request->input('tvdb') != null) {
@@ -132,7 +135,7 @@ class GraveyardController extends Controller
$torrents = $torrent->paginate(25);
}
return view('graveyard.results', [
return \view('graveyard.results', [
'user' => $user,
'torrents' => $torrents,
])->render();
@@ -153,33 +156,33 @@ class GraveyardController extends Controller
$resurrected = Graveyard::where('torrent_id', '=', $torrent->id)->first();
if ($resurrected) {
return redirect()->route('graveyard.index')
return \redirect()->route('graveyard.index')
->withErrors('Torrent Resurrection Failed! This torrent is already pending a resurrection.');
}
if ($user->id === $torrent->user_id) {
return redirect()->route('graveyard.index')
return \redirect()->route('graveyard.index')
->withErrors('Torrent Resurrection Failed! You cannot resurrect your own uploads.');
}
$resurrection = new Graveyard();
$resurrection->user_id = $user->id;
$resurrection->torrent_id = $torrent->id;
$resurrection->seedtime = $request->input('seedtime');
$graveyard = new Graveyard();
$graveyard->user_id = $user->id;
$graveyard->torrent_id = $torrent->id;
$graveyard->seedtime = $request->input('seedtime');
$v = validator($resurrection->toArray(), [
$v = \validator($graveyard->toArray(), [
'user_id' => 'required',
'torrent_id' => 'required',
'seedtime' => 'required',
]);
if ($v->fails()) {
return redirect()->route('graveyard.index')
return \redirect()->route('graveyard.index')
->withErrors($v->errors());
}
$resurrection->save();
$graveyard->save();
return redirect()->route('graveyard.index')
return \redirect()->route('graveyard.index')
->withSuccess('Torrent Resurrection Complete! You will be rewarded automatically once seedtime requirements are met.');
}
@@ -189,6 +192,8 @@ class GraveyardController extends Controller
* @param \Illuminate\Http\Request $request
* @param int $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request, $id)
@@ -196,10 +201,10 @@ class GraveyardController extends Controller
$user = $request->user();
$resurrection = Graveyard::findOrFail($id);
abort_unless($user->group->is_modo || $user->id === $resurrection->user_id, 403);
\abort_unless($user->group->is_modo || $user->id === $resurrection->user_id, 403);
$resurrection->delete();
return redirect()->route('graveyard.index')
return \redirect()->route('graveyard.index')
->withSuccess('Resurrection Successfully Canceled!');
}
}

35
app/Http/Controllers/HomeController.php Executable file → Normal file
View File

@@ -29,6 +29,9 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* @see \Tests\Todo\Feature\Http\Controllers\Staff\HomeControllerTest
*/
class HomeController extends Controller
{
/**
@@ -50,7 +53,7 @@ class HomeController extends Controller
$user = $request->user();
// Latest Articles/News Block
$articles = cache()->remember('latest_article', $expiresAt, fn () => Article::latest()->take(1)->get());
$articles = \cache()->remember('latest_article', $expiresAt, fn () => Article::latest()->take(1)->get());
foreach ($articles as $article) {
$article->newNews = ($user->updated_at->subDays(3)->getTimestamp() < $article->created_at->getTimestamp()) ? 1 : 0;
}
@@ -58,25 +61,25 @@ class HomeController extends Controller
// Latest Torrents Block
$personal_freeleech = PersonalFreeleech::where('user_id', '=', $user->id)->first();
$newest = cache()->remember('newest_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
$newest = \cache()->remember('newest_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
->withCount(['thanks', 'comments'])
->latest()
->take(5)
->get());
$seeded = cache()->remember('seeded_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
$seeded = \cache()->remember('seeded_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
->withCount(['thanks', 'comments'])
->latest('seeders')
->take(5)
->get());
$leeched = cache()->remember('leeched_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
$leeched = \cache()->remember('leeched_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
->withCount(['thanks', 'comments'])
->latest('leechers')
->take(5)
->get());
$dying = cache()->remember('dying_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
$dying = \cache()->remember('dying_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
->withCount(['thanks', 'comments'])
->where('seeders', '=', 1)
->where('times_completed', '>=', 1)
@@ -84,7 +87,7 @@ class HomeController extends Controller
->take(5)
->get());
$dead = cache()->remember('dead_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
$dead = \cache()->remember('dead_torrents', $expiresAt, fn () => Torrent::with(['user', 'category', 'type'])
->withCount(['thanks', 'comments'])
->where('seeders', '=', 0)
->latest('leechers')
@@ -92,38 +95,38 @@ class HomeController extends Controller
->get());
// Latest Topics Block
$topics = cache()->remember('latest_topics', $expiresAt, fn () => Topic::with('forum')->latest()->take(5)->get());
$topics = \cache()->remember('latest_topics', $expiresAt, fn () => Topic::with('forum')->latest()->take(5)->get());
// Latest Posts Block
$posts = cache()->remember('latest_posts', $expiresAt, fn () => Post::with('topic', 'user')->latest()->take(5)->get());
$posts = \cache()->remember('latest_posts', $expiresAt, fn () => Post::with('topic', 'user')->latest()->take(5)->get());
// Online Block
$users = cache()->remember('online_users', $expiresAt, fn () => User::with('group', 'privacy')
$users = \cache()->remember('online_users', $expiresAt, fn () => User::with('group', 'privacy')
->withCount([
'warnings' => function (Builder $query) {
$query->whereNotNull('torrent')->where('active', '1');
},
])
->where('last_action', '>', now()->subMinutes(5))
->where('last_action', '>', \now()->subMinutes(5))
->get());
$groups = cache()->remember('user-groups', $expiresAt, fn () => Group::select(['name', 'color', 'effect', 'icon'])->oldest('position')->get());
$groups = \cache()->remember('user-groups', $expiresAt, fn () => Group::select(['name', 'color', 'effect', 'icon'])->oldest('position')->get());
// Featured Torrents Block
$featured = cache()->remember('latest_featured', $expiresAt, fn () => FeaturedTorrent::with('torrent')->get());
$featured = \cache()->remember('latest_featured', $expiresAt, fn () => FeaturedTorrent::with('torrent')->get());
// Latest Poll Block
$poll = cache()->remember('latest_poll', $expiresAt, fn () => Poll::latest()->first());
$poll = \cache()->remember('latest_poll', $expiresAt, fn () => Poll::latest()->first());
// Top Uploaders Block
$uploaders = cache()->remember('top_uploaders', $expiresAt, fn () => Torrent::with('user')
$uploaders = \cache()->remember('top_uploaders', $expiresAt, fn () => Torrent::with('user')
->select(DB::raw('user_id, count(*) as value'))
->groupBy('user_id')
->latest('value')
->take(10)
->get());
$past_uploaders = cache()->remember('month_uploaders', $expiresAt, fn () => Torrent::with('user')
$past_uploaders = \cache()->remember('month_uploaders', $expiresAt, fn () => Torrent::with('user')
->where('created_at', '>', $current->copy()->subDays(30)->toDateTimeString())
->select(DB::raw('user_id, count(*) as value'))
->groupBy('user_id')
@@ -134,7 +137,7 @@ class HomeController extends Controller
$freeleech_tokens = FreeleechToken::where('user_id', $user->id)->get();
$bookmarks = Bookmark::where('user_id', $user->id)->get();
return view('home.index', [
return \view('home.index', [
'user' => $user,
'personal_freeleech' => $personal_freeleech,
'users' => $users,

View File

@@ -17,6 +17,9 @@ use App\Models\Album;
use App\Models\Image;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\ImageControllerTest
*/
class ImageController extends Controller
{
/**
@@ -30,7 +33,7 @@ class ImageController extends Controller
{
$album = Album::find($id);
return view('album.image', ['album' => $album]);
return \view('album.image', ['album' => $album]);
}
/**
@@ -49,14 +52,14 @@ class ImageController extends Controller
$image->type = $request->input('type');
$file = $request->file('image');
$random_name = uniqid();
$destinationPath = public_path('/files/img/');
$extension = $file->getClientOriginalExtension();
$filename = 'album-image_'.$random_name.'.'.$extension;
$random_name = \uniqid();
$destinationPath = \public_path('/files/img/');
$clientOriginalExtension = $file->getClientOriginalExtension();
$filename = 'album-image_'.$random_name.'.'.$clientOriginalExtension;
$uploadSuccess = $request->file('image')->move($destinationPath, $filename);
$image->image = $filename;
$v = validator($image->toArray(), [
$v = \validator($image->toArray(), [
'album_id' => 'required|numeric|exists:albums,id',
'user_id' => 'required',
'description' => 'required',
@@ -65,12 +68,12 @@ class ImageController extends Controller
]);
if ($v->fails()) {
return redirect()->route('images.create', ['id' => $request->input('album_id')])
return \redirect()->route('images.create', ['id' => $request->input('album_id')])
->withErrors($v->errors());
}
$image->save();
return redirect()->route('albums.show', ['id' => $request->input('album_id')])
return \redirect()->route('albums.show', ['id' => $request->input('album_id')])
->withSuccess('Your image has successfully published!');
}
@@ -86,15 +89,15 @@ class ImageController extends Controller
$image = Image::findOrFail($id);
$filename = $image->image;
if (! file_exists(getcwd().'/files/img/'.$filename)) {
return redirect()->route('show_album', ['id' => $image->album_id])
if (! \file_exists(\getcwd().'/files/img/'.$filename)) {
return \redirect()->route('show_album', ['id' => $image->album_id])
->withErrors('Image File Not Found! Please Report This To Staff!');
}
$image->downloads++;
$image->save();
return response()->download(getcwd().'/files/img/'.$filename);
return \response()->download(\getcwd().'/files/img/'.$filename);
}
/**
@@ -103,6 +106,8 @@ class ImageController extends Controller
* @param \Illuminate\Http\Request $request
* @param \App\Models\Image $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request, $id)
@@ -110,10 +115,10 @@ class ImageController extends Controller
$user = $request->user();
$image = Image::findOrFail($id);
abort_unless($user->group->is_modo || $user->id === $image->user_id, 403);
\abort_unless($user->group->is_modo || $user->id === $image->user_id, 403);
$image->delete();
return redirect()->route('albums.show', ['id' => $image->album_id])
return \redirect()->route('albums.show', ['id' => $image->album_id])
->withSuccess('Image has successfully been deleted');
}
}

View File

@@ -21,6 +21,9 @@ use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Ramsey\Uuid\Uuid;
/**
* @see \Tests\Todo\Feature\Http\Controllers\InviteControllerTest
*/
class InviteController extends Controller
{
/**
@@ -35,11 +38,11 @@ class InviteController extends Controller
{
$user = $request->user();
$owner = User::where('username', '=', $username)->firstOrFail();
abort_unless($user->group->is_modo || $user->id === $owner->id, 403);
\abort_unless($user->group->is_modo || $user->id === $owner->id, 403);
$invites = Invite::with(['sender', 'receiver'])->where('user_id', '=', $owner->id)->latest()->paginate(25);
return view('user.invites', ['owner' => $owner, 'invites' => $invites, 'route' => 'invite']);
return \view('user.invites', ['owner' => $owner, 'invites' => $invites, 'route' => 'invite']);
}
/**
@@ -53,20 +56,20 @@ class InviteController extends Controller
{
$user = $request->user();
if (config('other.invite-only') == false) {
return redirect()->route('home.index')
if (\config('other.invite-only') == false) {
return \redirect()->route('home.index')
->withErrors('Invitations Are Disabled Due To Open Registration!');
}
if ($user->can_invite == 0) {
return redirect()->route('home.index')
return \redirect()->route('home.index')
->withErrors('Your Invite Rights Have Been Revoked!');
}
if (config('other.invites_restriced') == true && ! in_array($user->group->name, config('other.invite_groups'))) {
return redirect()->route('home.index')
if (\config('other.invites_restriced') == true && ! \in_array($user->group->name, \config('other.invite_groups'))) {
return \redirect()->route('home.index')
->withErrors('Invites are currently disabled for your group.');
}
return view('user.invite', ['user' => $user, 'route' => 'invite']);
return \view('user.invite', ['user' => $user, 'route' => 'invite']);
}
/**
@@ -80,23 +83,23 @@ class InviteController extends Controller
*/
public function store(Request $request)
{
$current = new Carbon();
$carbon = new Carbon();
$user = $request->user();
if (config('other.invites_restriced') == true && ! in_array($user->group->name, config('other.invite_groups'))) {
return redirect()->route('home.index')
if (\config('other.invites_restriced') == true && ! \in_array($user->group->name, \config('other.invite_groups'))) {
return \redirect()->route('home.index')
->withErrors('Invites are currently disabled for your group.');
}
if ($user->invites <= 0) {
return redirect()->route('invites.create')
return \redirect()->route('invites.create')
->withErrors('You do not have enough invites!');
}
$exist = Invite::where('email', '=', $request->input('email'))->first();
if ($exist) {
return redirect()->route('invites.create')
return \redirect()->route('invites.create')
->withErrors('The email address your trying to send a invite to has already been sent one.');
}
@@ -105,23 +108,23 @@ class InviteController extends Controller
$invite->user_id = $user->id;
$invite->email = $request->input('email');
$invite->code = $code;
$invite->expires_on = $current->copy()->addDays(config('other.invite_expire'));
$invite->expires_on = $carbon->copy()->addDays(\config('other.invite_expire'));
$invite->custom = $request->input('message');
if (config('email-blacklist.enabled')) {
$v = validator($invite->toArray(), [
if (\config('email-blacklist.enabled')) {
$v = \validator($invite->toArray(), [
'email' => 'required|string|email|max:70|blacklist|unique:users',
'custom' => 'required',
]);
} else {
$v = validator($invite->toArray(), [
$v = \validator($invite->toArray(), [
'email' => 'required|string|email|max:70|unique:users',
'custom' => 'required',
]);
}
if ($v->fails()) {
return redirect()->route('invites.create')
return \redirect()->route('invites.create')
->withErrors($v->errors());
}
Mail::to($request->input('email'))->send(new InviteUser($invite));
@@ -129,7 +132,7 @@ class InviteController extends Controller
$user->invites--;
$user->save();
return redirect()->route('invites.create')
return \redirect()->route('invites.create')
->withSuccess('Invite was sent successfully!');
}
@@ -146,16 +149,16 @@ class InviteController extends Controller
$user = $request->user();
$invite = Invite::findOrFail($id);
abort_unless($invite->user_id === $user->id, 403);
\abort_unless($invite->user_id === $user->id, 403);
if ($invite->accepted_by !== null) {
return redirect()->route('invites.index', ['username' => $user->username])
return \redirect()->route('invites.index', ['username' => $user->username])
->withErrors('The invite you are trying to resend has already been used.');
}
Mail::to($invite->email)->send(new InviteUser($invite));
return redirect()->route('invites.index', ['username' => $user->username])
return \redirect()->route('invites.index', ['username' => $user->username])
->withSuccess('Invite was resent successfully!');
}
}

View File

@@ -1,86 +0,0 @@
<?php
/**
* NOTICE OF LICENSE.
*
* UNIT3D Community Edition is open-sourced software licensed under the GNU Affero General Public License v3.0
* The details is bundled with this project in the file LICENSE.txt.
*
* @project UNIT3D Community Edition
*
* @author HDVinnie <hdinnovations@protonmail.com>
* @license https://www.gnu.org/licenses/agpl-3.0.en.html/ GNU Affero General Public License v3.0
*/
namespace App\Http\Controllers;
use App\Models\Language;
use Illuminate\Http\Request;
class LanguageController extends Controller
{
/**
* Set locale if it's allowed.
*
* @param string $locale
* @param \Illuminate\Http\Request $request
**/
private function setLocale($locale, $request)
{
// Check if is allowed and set default locale if not
if (! Language::allowed($locale)) {
$locale = config('app.locale');
}
if (auth()->check()) {
auth()->user()->setAttribute('locale', $locale)->save();
} else {
$request->session()->put('locale', $locale);
}
}
/**
* Set locale and return home url.
*
* @param string $locale
* @param \Illuminate\Http\Request $request
*
* @return string
**/
public function home($locale, Request $request)
{
$this->setLocale($locale, $request);
$url = config('language.url') ? url('/'.$locale) : url('/');
return redirect($url)
->withSuccess('Language Changed!');
}
/**
* Set locale and return back.
*
* @param string $locale
* @param \Illuminate\Http\Request $request
*
* @return string
**/
public function back($locale, Request $request)
{
$this->setLocale($locale, $request);
$session = $request->session();
if (config('language.url')) {
$previous_url = substr(str_replace(env('APP_URL'), '', $session->previousUrl()), 7);
if (strlen($previous_url) === 3) {
$previous_url = substr($previous_url, 3);
} else {
$previous_url = substr($previous_url, strrpos($previous_url, '/') + 1);
}
$url = rtrim(env('APP_URL'), '/').'/'.$locale.'/'.ltrim($previous_url, '/');
$session->setPreviousUrl($url);
}
return redirect($session->previousUrl())
->withSuccess('Language Changed!');
}
}

View File

@@ -17,6 +17,9 @@ use App\Models\Like;
use App\Models\Post;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\LikeControllerTest
*/
class LikeController extends Controller
{
/**
@@ -30,18 +33,18 @@ class LikeController extends Controller
public function store(Request $request, $postId)
{
$post = Post::findOrFail($postId);
$postUrl = sprintf('forums/topics/%s?page=%s#post-%s', $post->topic->id, $post->getPageNumber(), $postId);
$postUrl = \sprintf('forums/topics/%s?page=%s#post-%s', $post->topic->id, $post->getPageNumber(), $postId);
$user = $request->user();
$like = $user->likes()->where('post_id', '=', $post->id)->where('like', '=', 1)->first();
$dislike = $user->likes()->where('post_id', '=', $post->id)->where('dislike', '=', 1)->first();
if ($like || $dislike) {
return redirect()->to($postUrl)
return \redirect()->to($postUrl)
->withErrors('You have already liked/disliked this post!');
}
if ($user->id == $post->user_id) {
return redirect()->to($postUrl)
return \redirect()->to($postUrl)
->withErrors('You cannot like your own post!');
}
$new = new Like();
@@ -50,7 +53,7 @@ class LikeController extends Controller
$new->like = 1;
$new->save();
return redirect()->to($postUrl)
return \redirect()->to($postUrl)
->withSuccess('Like Successfully Applied!');
}
@@ -65,18 +68,18 @@ class LikeController extends Controller
public function destroy(Request $request, $postId)
{
$post = Post::findOrFail($postId);
$postUrl = sprintf('forums/topics/%s?page=%s#post-%s', $post->topic->id, $post->getPageNumber(), $postId);
$postUrl = \sprintf('forums/topics/%s?page=%s#post-%s', $post->topic->id, $post->getPageNumber(), $postId);
$user = $request->user();
$like = $user->likes()->where('post_id', '=', $post->id)->where('like', '=', 1)->first();
$dislike = $user->likes()->where('post_id', '=', $post->id)->where('dislike', '=', 1)->first();
if ($like || $dislike) {
return redirect()->to($postUrl)
return \redirect()->to($postUrl)
->withErrors('You have already liked/disliked this post!');
}
if ($user->id == $post->user_id) {
return redirect()->to($postUrl)
return \redirect()->to($postUrl)
->withErrors('You cannot dislike your own post!');
}
$new = new Like();
@@ -85,7 +88,7 @@ class LikeController extends Controller
$new->dislike = 1;
$new->save();
return redirect()->to($postUrl)
return \redirect()->to($postUrl)
->withSuccess('Dislike Successfully Applied!');
}
}

View File

@@ -17,6 +17,9 @@ use App\Models\Notification;
use Carbon\Carbon;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\NotificationControllerTest
*/
class NotificationController extends Controller
{
/**
@@ -30,7 +33,7 @@ class NotificationController extends Controller
{
$notifications = $request->user()->notifications()->paginate(25);
return view('notification.index', ['notifications' => $notifications]);
return \view('notification.index', ['notifications' => $notifications]);
}
/**
@@ -126,7 +129,7 @@ class NotificationController extends Controller
$notifications = $notification->paginate(25);
return view('notification.results', [
return \view('notification.results', [
'user' => $user,
'notifications' => $notifications,
])->render();
@@ -145,7 +148,7 @@ class NotificationController extends Controller
$notification = $request->user()->notifications()->findOrFail($id);
$notification->markAsRead();
return redirect()->to($notification->data['url'])
return \redirect()->to($notification->data['url'])
->withSuccess('Notification Marked As Read!');
}
@@ -162,18 +165,18 @@ class NotificationController extends Controller
$notification = $request->user()->notifications()->where('id', '=', $id)->first();
if (! $notification) {
return redirect()->route('notifications.index')
return \redirect()->route('notifications.index')
->withErrors('Notification Does Not Exist!');
}
if ($notification->read_at != null) {
return redirect()->route('notifications.index')
return \redirect()->route('notifications.index')
->withErrors('Notification Already Marked As Read!');
}
$notification->markAsRead();
return redirect()->route('notifications.index')
return \redirect()->route('notifications.index')
->withSuccess('Notification Marked As Read!');
}
@@ -188,10 +191,10 @@ class NotificationController extends Controller
*/
public function updateAll(Request $request)
{
$current = new Carbon();
$request->user()->unreadNotifications()->update(['read_at' => $current]);
$carbon = new Carbon();
$request->user()->unreadNotifications()->update(['read_at' => $carbon]);
return redirect()->route('notifications.index')
return \redirect()->route('notifications.index')
->withSuccess('All Notifications Marked As Read!');
}
@@ -207,7 +210,7 @@ class NotificationController extends Controller
{
$request->user()->notifications()->findOrFail($id)->delete();
return redirect()->route('notifications.index')
return \redirect()->route('notifications.index')
->withSuccess('Notification Deleted!');
}
@@ -222,7 +225,7 @@ class NotificationController extends Controller
{
$request->user()->notifications()->delete();
return redirect()->route('notifications.index')
return \redirect()->route('notifications.index')
->withSuccess('All Notifications Deleted!');
}
}

19
app/Http/Controllers/PageController.php Executable file → Normal file
View File

@@ -16,6 +16,9 @@ namespace App\Http\Controllers;
use App\Models\Page;
use Illuminate\Support\Facades\DB;
/**
* @see \Tests\Todo\Feature\Http\Controllers\PageControllerTest
*/
class PageController extends Controller
{
/**
@@ -27,7 +30,7 @@ class PageController extends Controller
{
$pages = Page::all();
return view('page.index', ['pages' => $pages]);
return \view('page.index', ['pages' => $pages]);
}
/**
@@ -41,7 +44,7 @@ class PageController extends Controller
{
$page = Page::findOrFail($id);
return view('page.page', ['page' => $page]);
return \view('page.page', ['page' => $page]);
}
/**
@@ -53,7 +56,7 @@ class PageController extends Controller
{
$staff = DB::table('users')->leftJoin('groups', 'users.group_id', '=', 'groups.id')->select(['users.id', 'users.title', 'users.username', 'groups.name', 'groups.color', 'groups.icon'])->where('groups.is_admin', 1)->orWhere('groups.is_modo', 1)->get();
return view('page.staff', ['staff' => $staff]);
return \view('page.staff', ['staff' => $staff]);
}
/**
@@ -65,7 +68,7 @@ class PageController extends Controller
{
$internal = DB::table('users')->leftJoin('groups', 'users.group_id', '=', 'groups.id')->select(['users.id', 'users.title', 'users.username', 'groups.name', 'groups.color', 'groups.icon'])->where('groups.is_internal', 1)->get();
return view('page.internal', ['internal' => $internal]);
return \view('page.internal', ['internal' => $internal]);
}
/**
@@ -75,10 +78,10 @@ class PageController extends Controller
*/
public function blacklist()
{
$clients = config('client-blacklist.clients', []);
$browsers = config('client-blacklist.browsers', []);
$clients = \config('client-blacklist.clients', []);
$browsers = \config('client-blacklist.browsers', []);
return view('page.blacklist', ['clients' => $clients, 'browsers' => $browsers]);
return \view('page.blacklist', ['clients' => $clients, 'browsers' => $browsers]);
}
/**
@@ -88,6 +91,6 @@ class PageController extends Controller
*/
public function about()
{
return view('page.aboutus');
return \view('page.aboutus');
}
}

View File

@@ -19,23 +19,26 @@ use App\Models\Torrent;
use App\Repositories\ChatRepository;
use App\Services\MovieScrapper;
use Illuminate\Http\Request;
use Image;
use Intervention\Image\Facades\Image;
/**
* @see \Tests\Todo\Feature\Http\Controllers\PlaylistControllerTest
*/
class PlaylistController extends Controller
{
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* PlaylistController Constructor.
*
* @param ChatRepository $chat
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(ChatRepository $chat)
public function __construct(ChatRepository $chatRepository)
{
$this->chat = $chat;
$this->chatRepository = $chatRepository;
}
/**
@@ -47,7 +50,7 @@ class PlaylistController extends Controller
{
$playlists = Playlist::with('user')->withCount('torrents')->where('is_private', '=', 0)->orderBy('name', 'ASC')->paginate(24);
return view('playlist.index', ['playlists' => $playlists]);
return \view('playlist.index', ['playlists' => $playlists]);
}
/**
@@ -57,7 +60,7 @@ class PlaylistController extends Controller
*/
public function create()
{
return view('playlist.create');
return \view('playlist.create');
}
/**
@@ -69,7 +72,7 @@ class PlaylistController extends Controller
*/
public function store(Request $request)
{
$user = auth()->user();
$user = \auth()->user();
$playlist = new Playlist();
$playlist->user_id = $user->id;
@@ -79,8 +82,8 @@ class PlaylistController extends Controller
if ($request->hasFile('cover_image') && $request->file('cover_image')->getError() === 0) {
$image = $request->file('cover_image');
$filename = 'playlist-cover_'.uniqid().'.'.$image->getClientOriginalExtension();
$path = public_path('/files/img/'.$filename);
$filename = 'playlist-cover_'.\uniqid().'.'.$image->getClientOriginalExtension();
$path = \public_path('/files/img/'.$filename);
Image::make($image->getRealPath())->fit(400, 225)->encode('png', 100)->save($path);
$playlist->cover_image = $filename;
}
@@ -88,7 +91,7 @@ class PlaylistController extends Controller
$playlist->position = $request->input('position');
$playlist->is_private = $request->input('is_private');
$v = validator($playlist->toArray(), [
$v = \validator($playlist->toArray(), [
'user_id' => 'required',
'name' => 'required',
'description' => 'required',
@@ -96,20 +99,20 @@ class PlaylistController extends Controller
]);
if ($v->fails()) {
return redirect()->route('playlists.create')
return \redirect()->route('playlists.create')
->withInput()
->withErrors($v->errors());
}
$playlist->save();
// Announce To Shoutbox
$appurl = config('app.url');
$appurl = \config('app.url');
if ($playlist->is_private != 1) {
$this->chat->systemMessage(
sprintf('User [url=%s/', $appurl).$user->username.'.'.$user->id.']'.$user->username.sprintf('[/url] has created a new playlist [url=%s/playlists/', $appurl).$playlist->id.']'.$playlist->name.'[/url] check it out now! :slight_smile:'
$this->chatRepository->systemMessage(
\sprintf('User [url=%s/', $appurl).$user->username.'.'.$user->id.']'.$user->username.\sprintf('[/url] has created a new playlist [url=%s/playlists/', $appurl).$playlist->id.']'.$playlist->name.'[/url] check it out now! :slight_smile:'
);
}
return redirect()->route('playlists.show', ['id' => $playlist->id])
return \redirect()->route('playlists.show', ['id' => $playlist->id])
->withSuccess('Your Playlist Was Created Successfully!');
}
@@ -133,23 +136,23 @@ class PlaylistController extends Controller
$torrent = Torrent::where('id', '=', $random->torrent_id)->firstOrFail();
}
if (isset($random) && isset($torrent)) {
$client = new MovieScrapper(config('api-keys.tmdb'), config('api-keys.tvdb'), config('api-keys.omdb'));
$movieScrapper = new MovieScrapper(\config('api-keys.tmdb'), \config('api-keys.tvdb'), \config('api-keys.omdb'));
if ($torrent->category_id == 2) {
if ($torrent->tmdb || $torrent->tmdb != 0) {
$meta = $client->scrape('tv', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('tv', null, $torrent->tmdb);
} else {
$meta = $client->scrape('tv', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('tv', 'tt'.$torrent->imdb);
}
} elseif ($torrent->tmdb || $torrent->tmdb != 0) {
$meta = $client->scrape('movie', null, $torrent->tmdb);
$meta = $movieScrapper->scrape('movie', null, $torrent->tmdb);
} else {
$meta = $client->scrape('movie', 'tt'.$torrent->imdb);
$meta = $movieScrapper->scrape('movie', 'tt'.$torrent->imdb);
}
}
$torrents = PlaylistTorrent::with(['torrent'])->where('playlist_id', '=', $playlist->id)->paginate(26);
return view('playlist.show', ['playlist' => $playlist, 'meta' => $meta, 'torrents' => $torrents]);
return \view('playlist.show', ['playlist' => $playlist, 'meta' => $meta, 'torrents' => $torrents]);
}
/**
@@ -161,12 +164,12 @@ class PlaylistController extends Controller
*/
public function edit($id)
{
$user = auth()->user();
$user = \auth()->user();
$playlist = Playlist::findOrFail($id);
abort_unless($user->id == $playlist->user_id || $user->group->is_modo, 403);
\abort_unless($user->id == $playlist->user_id || $user->group->is_modo, 403);
return view('playlist.edit', ['playlist' => $playlist]);
return \view('playlist.edit', ['playlist' => $playlist]);
}
/**
@@ -179,10 +182,10 @@ class PlaylistController extends Controller
*/
public function update(Request $request, $id)
{
$user = auth()->user();
$user = \auth()->user();
$playlist = Playlist::findOrFail($id);
abort_unless($user->id == $playlist->user_id || $user->group->is_modo, 403);
\abort_unless($user->id == $playlist->user_id || $user->group->is_modo, 403);
$playlist->name = $request->input('name');
$playlist->description = $request->input('description');
@@ -190,8 +193,8 @@ class PlaylistController extends Controller
if ($request->hasFile('cover_image') && $request->file('cover_image')->getError() === 0) {
$image = $request->file('cover_image');
$filename = 'playlist-cover_'.uniqid().'.'.$image->getClientOriginalExtension();
$path = public_path('/files/img/'.$filename);
$filename = 'playlist-cover_'.\uniqid().'.'.$image->getClientOriginalExtension();
$path = \public_path('/files/img/'.$filename);
Image::make($image->getRealPath())->fit(400, 225)->encode('png', 100)->save($path);
$playlist->cover_image = $filename;
}
@@ -199,20 +202,20 @@ class PlaylistController extends Controller
$playlist->position = $request->input('position');
$playlist->is_private = $request->input('is_private');
$v = validator($playlist->toArray(), [
$v = \validator($playlist->toArray(), [
'name' => 'required',
'description' => 'required',
'is_private' => 'required',
]);
if ($v->fails()) {
return redirect()->route('playlists.edit', ['id' => $playlist->id])
return \redirect()->route('playlists.edit', ['id' => $playlist->id])
->withInput()
->withErrors($v->errors());
}
$playlist->save();
return redirect()->route('playlists.show', ['id' => $playlist->id])
return \redirect()->route('playlists.show', ['id' => $playlist->id])
->withSuccess('Your Playlist Has Successfully Been Updated!');
}
@@ -221,18 +224,20 @@ class PlaylistController extends Controller
*
* @param \App\Playlist $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
$user = auth()->user();
$user = \auth()->user();
$playlist = Playlist::findOrFail($id);
abort_unless($user->id == $playlist->user_id || $user->group->is_modo, 403);
\abort_unless($user->id == $playlist->user_id || $user->group->is_modo, 403);
$playlist->delete();
return redirect()->route('playlists.index')
return \redirect()->route('playlists.index')
->withSuccess('Playlist Deleted!');
}
}

View File

@@ -17,6 +17,9 @@ use App\Models\Playlist;
use App\Models\PlaylistTorrent;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\PlaylistTorrentControllerTest
*/
class PlaylistTorrentController extends Controller
{
/**
@@ -28,27 +31,27 @@ class PlaylistTorrentController extends Controller
*/
public function store(Request $request)
{
$user = auth()->user();
$user = \auth()->user();
$playlist = Playlist::findOrFail($request->input('playlist_id'));
abort_unless($user->id === $playlist->user_id, 403);
\abort_unless($user->id === $playlist->user_id, 403);
$playlist_torrent = new PlaylistTorrent();
$playlist_torrent->playlist_id = $playlist->id;
$playlist_torrent->torrent_id = $request->input('torrent_id');
$playlistTorrent = new PlaylistTorrent();
$playlistTorrent->playlist_id = $playlist->id;
$playlistTorrent->torrent_id = $request->input('torrent_id');
$v = validator($playlist_torrent->toArray(), [
$v = \validator($playlistTorrent->toArray(), [
'playlist_id' => 'required|numeric|exists:playlists,id|unique:playlist_torrents,playlist_id,NULL,NULL,torrent_id,'.$request->input('torrent_id'),
'torrent_id' => 'required|numeric|exists:torrents,id|unique:playlist_torrents,torrent_id,NULL,NULL,playlist_id,'.$request->input('playlist_id'),
]);
if ($v->fails()) {
return redirect()->route('playlists.show', ['id' => $playlist->id])
return \redirect()->route('playlists.show', ['id' => $playlist->id])
->withErrors($v->errors());
}
$playlist_torrent->save();
$playlistTorrent->save();
return redirect()->route('playlists.show', ['id' => $playlist->id])
return \redirect()->route('playlists.show', ['id' => $playlist->id])
->withSuccess('Torrent Has Successfully Been Attached To Your Playlist.');
}
@@ -57,17 +60,19 @@ class PlaylistTorrentController extends Controller
*
* @param int $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
$user = auth()->user();
$user = \auth()->user();
$playlist_torrent = PlaylistTorrent::findOrFail($id);
abort_unless($user->group->is_modo || $user->id === $playlist_torrent->playlist->user_id, 403);
\abort_unless($user->group->is_modo || $user->id === $playlist_torrent->playlist->user_id, 403);
$playlist_torrent->delete();
return redirect()->route('playlists.show', ['id' => $playlist_torrent->playlist->id])
return \redirect()->route('playlists.show', ['id' => $playlist_torrent->playlist->id])
->withSuccess('Torrent Has Successfully Been Detached From Your Playlist.');
}
}

View File

@@ -20,6 +20,9 @@ use App\Models\Voter;
use App\Repositories\ChatRepository;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\Staff\PollControllerTest
*/
class PollController extends Controller
{
/**
@@ -46,7 +49,7 @@ class PollController extends Controller
{
$polls = Poll::latest()->paginate(15);
return view('poll.latest', ['polls' => $polls]);
return \view('poll.latest', ['polls' => $polls]);
}
/**
@@ -64,11 +67,11 @@ class PollController extends Controller
$user_has_voted = $poll->voters->where('user_id', '=', $user->id)->isNotEmpty();
if ($user_has_voted) {
return redirect()->route('poll_results', ['id' => $poll->id])
return \redirect()->route('poll_results', ['id' => $poll->id])
->withInfo('You have already vote on this poll. Here are the results.');
}
return view('poll.show', ['poll' => $poll]);
return \view('poll.show', ['poll' => $poll]);
}
/**
@@ -86,7 +89,7 @@ class PollController extends Controller
->where('poll_id', '=', $poll->id)
->exists();
if ($voted) {
return redirect()->route('poll_results', ['id' => $poll->id])
return \redirect()->route('poll_results', ['id' => $poll->id])
->withErrors('Bro have already vote on this poll. Your vote has not been counted.');
}
@@ -101,14 +104,14 @@ class PollController extends Controller
$vote->user_id = $user->id;
$vote->save();
$poll_url = href_poll($poll);
$profile_url = href_profile($user);
$poll_url = \href_poll($poll);
$profile_url = \href_profile($user);
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has voted on poll [url=%s]%s[/url]', $profile_url, $user->username, $poll_url, $poll->title)
\sprintf('[url=%s]%s[/url] has voted on poll [url=%s]%s[/url]', $profile_url, $user->username, $poll_url, $poll->title)
);
return redirect()->route('poll_results', ['id' => $poll->id])
return \redirect()->route('poll_results', ['id' => $poll->id])
->withSuccess('Your vote has been counted.');
}
@@ -127,6 +130,6 @@ class PollController extends Controller
'total_votes' => $poll->totalVotes(),
];
return view('poll.result', $map);
return \view('poll.result', $map);
}
}

View File

@@ -31,28 +31,31 @@ use App\Repositories\ChatRepository;
use App\Repositories\TaggedUserRepository;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\PostControllerTest
*/
class PostController extends Controller
{
/**
* @var TaggedUserRepository
*/
private $tag;
private $taggedUserRepository;
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* ForumController Constructor.
*
* @param TaggedUserRepository $tag
* @param ChatRepository $chat
* @param \App\Repositories\TaggedUserRepository $taggedUserRepository
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(TaggedUserRepository $tag, ChatRepository $chat)
public function __construct(TaggedUserRepository $taggedUserRepository, ChatRepository $chatRepository)
{
$this->tag = $tag;
$this->chat = $chat;
$this->taggedUserRepository = $taggedUserRepository;
$this->chatRepository = $chatRepository;
}
/**
@@ -72,7 +75,7 @@ class PostController extends Controller
// The user has the right to create a post here?
if (! $category->getPermission()->reply_topic || ($topic->state == 'close' && ! $request->user()->group->is_modo)) {
return redirect()->route('forums.index')
return \redirect()->route('forums.index')
->withErrors('You Cannot Reply To This Topic!');
}
@@ -81,29 +84,29 @@ class PostController extends Controller
$post->user_id = $user->id;
$post->topic_id = $topic->id;
$v = validator($post->toArray(), [
$v = \validator($post->toArray(), [
'content' => 'required|min:1',
'user_id' => 'required',
'topic_id' => 'required',
]);
if ($v->fails()) {
return redirect()->route('forum_topic', ['id' => $topic->id])
return \redirect()->route('forum_topic', ['id' => $topic->id])
->withErrors($v->errors());
}
$post->save();
$appurl = config('app.url');
$href = sprintf('%s/forums/topics/%s?page=%s#post-%s', $appurl, $topic->id, $post->getPageNumber(), $post->id);
$message = sprintf('%s has tagged you in a forum post. You can view it [url=%s] HERE [/url]', $user->username, $href);
if ($this->tag->hasTags($request->input('content'))) {
if ($this->tag->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = collect([]);
$appurl = \config('app.url');
$href = \sprintf('%s/forums/topics/%s?page=%s#post-%s', $appurl, $topic->id, $post->getPageNumber(), $post->id);
$message = \sprintf('%s has tagged you in a forum post. You can view it [url=%s] HERE [/url]', $user->username, $href);
if ($this->taggedUserRepository->hasTags($request->input('content'))) {
if ($this->taggedUserRepository->contains($request->input('content'), '@here') && $user->group->is_modo) {
$users = \collect([]);
$topic->posts()->get()->each(function ($p) use ($users) {
$users->push($p->user);
});
$this->tag->messagePostUsers(
$this->taggedUserRepository->messagePostUsers(
'forum',
$users,
$user,
@@ -111,7 +114,7 @@ class PostController extends Controller
$post
);
} else {
$this->tag->messageTaggedPostUsers(
$this->taggedUserRepository->messageTaggedPostUsers(
'forum',
$request->input('content'),
$user,
@@ -142,15 +145,15 @@ class PostController extends Controller
// Save
$forum->save();
// Post To Chatbox
$appurl = config('app.url');
$postUrl = sprintf('%s/forums/topics/%s?page=%s#post-%s', $appurl, $topic->id, $post->getPageNumber(), $post->id);
$realUrl = sprintf('/forums/topics/%s?page=%s#post-%s', $topic->id, $post->getPageNumber(), $post->id);
$profileUrl = sprintf('%s/users/%s', $appurl, $user->username);
$appurl = \config('app.url');
$postUrl = \sprintf('%s/forums/topics/%s?page=%s#post-%s', $appurl, $topic->id, $post->getPageNumber(), $post->id);
$realUrl = \sprintf('/forums/topics/%s?page=%s#post-%s', $topic->id, $post->getPageNumber(), $post->id);
$profileUrl = \sprintf('%s/users/%s', $appurl, $user->username);
if (config('other.staff-forum-notify') && ($forum->id == config('other.staff-forum-id') || $forum->parent_id == config('other.staff-forum-id'))) {
if (\config('other.staff-forum-notify') && ($forum->id == \config('other.staff-forum-id') || $forum->parent_id == \config('other.staff-forum-id'))) {
$topic->notifyStaffers($user, $topic, $post);
} else {
$this->chat->systemMessage(sprintf('[url=%s]%s[/url] has left a reply on topic [url=%s]%s[/url]', $profileUrl, $user->username, $postUrl, $topic->name));
$this->chatRepository->systemMessage(\sprintf('[url=%s]%s[/url] has left a reply on topic [url=%s]%s[/url]', $profileUrl, $user->username, $postUrl, $topic->name));
// Notify All Subscribers Of New Reply
if ($topic->first_user_poster_id != $user->id) {
$topic->notifyStarter($user, $topic, $post);
@@ -171,7 +174,7 @@ class PostController extends Controller
$user->addProgress(new UserMade800Posts(), 1);
$user->addProgress(new UserMade900Posts(), 1);
return redirect()->to($realUrl)
return \redirect()->to($realUrl)
->withSuccess('Post Successfully Posted');
}
@@ -190,7 +193,7 @@ class PostController extends Controller
$category = $forum->getCategory();
$post = Post::findOrFail($postId);
return view('forum.post_edit', [
return \view('forum.post_edit', [
'topic' => $topic,
'forum' => $forum,
'post' => $post,
@@ -210,13 +213,13 @@ class PostController extends Controller
{
$user = $request->user();
$post = Post::findOrFail($postId);
$postUrl = sprintf('forums/topics/%s?page=%s#post-%s', $post->topic->id, $post->getPageNumber(), $postId);
$postUrl = \sprintf('forums/topics/%s?page=%s#post-%s', $post->topic->id, $post->getPageNumber(), $postId);
abort_unless($user->group->is_modo || $user->id === $post->user_id, 403);
\abort_unless($user->group->is_modo || $user->id === $post->user_id, 403);
$post->content = $request->input('content');
$post->save();
return redirect()->to($postUrl)
return \redirect()->to($postUrl)
->withSuccess('Post Successfully Edited!');
}
@@ -235,10 +238,10 @@ class PostController extends Controller
$user = $request->user();
$post = Post::with('topic')->findOrFail($postId);
abort_unless($user->group->is_modo || $user->id === $post->user_id, 403);
\abort_unless($user->group->is_modo || $user->id === $post->user_id, 403);
$post->delete();
return redirect()->route('forum_topic', ['id' => $post->topic->id])
return \redirect()->route('forum_topic', ['id' => $post->topic->id])
->withSuccess('This Post Is Now Deleted!');
}
}

View File

@@ -17,6 +17,9 @@ use App\Models\PrivateMessage;
use App\Models\User;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\PrivateMessageControllerTest
*/
class PrivateMessageController extends Controller
{
/**
@@ -33,7 +36,7 @@ class PrivateMessageController extends Controller
['subject', 'like', '%'.$request->input('subject').'%'],
])->latest()->paginate(20);
return view('pm.inbox', ['pms' => $pms, 'user' => $user]);
return \view('pm.inbox', ['pms' => $pms, 'user' => $user]);
}
/**
@@ -50,7 +53,7 @@ class PrivateMessageController extends Controller
['subject', 'like', '%'.$request->input('subject').'%'],
])->latest()->paginate(20);
return view('pm.outbox', ['pms' => $pms, 'user' => $user]);
return \view('pm.outbox', ['pms' => $pms, 'user' => $user]);
}
/**
@@ -65,7 +68,7 @@ class PrivateMessageController extends Controller
$user = $request->user();
$pms = PrivateMessage::where('receiver_id', '=', $user->id)->latest()->paginate(25);
return view('pm.inbox', ['pms' => $pms, 'user' => $user]);
return \view('pm.inbox', ['pms' => $pms, 'user' => $user]);
}
/**
@@ -80,7 +83,7 @@ class PrivateMessageController extends Controller
$user = $request->user();
$pms = PrivateMessage::where('sender_id', '=', $user->id)->latest()->paginate(20);
return view('pm.outbox', ['pms' => $pms, 'user' => $user]);
return \view('pm.outbox', ['pms' => $pms, 'user' => $user]);
}
/**
@@ -102,10 +105,10 @@ class PrivateMessageController extends Controller
$pm->save();
}
return view('pm.message', ['pm' => $pm, 'user' => $user]);
return \view('pm.message', ['pm' => $pm, 'user' => $user]);
}
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withErrors('What Are You Trying To Do Here!');
}
@@ -122,7 +125,7 @@ class PrivateMessageController extends Controller
{
$user = $request->user();
return view('pm.send', ['user' => $user, 'receiver_id' => $receiver_id, 'username' => $username]);
return \view('pm.send', ['user' => $user, 'receiver_id' => $receiver_id, 'username' => $username]);
}
/**
@@ -144,18 +147,18 @@ class PrivateMessageController extends Controller
if ($request->has('receiver_id')) {
$recipient = User::where('username', '=', $request->input('receiver_id'))->firstOrFail();
} else {
return redirect()->route('create', ['username' => $request->user()->username, 'id' => $request->user()->id])
return \redirect()->route('create', ['username' => $request->user()->username, 'id' => $request->user()->id])
->withErrors($v->errors());
}
$pm = new PrivateMessage();
$pm->sender_id = $user->id;
$pm->receiver_id = $recipient->id;
$pm->subject = $request->input('subject');
$pm->message = $request->input('message');
$pm->read = 0;
$privateMessage = new PrivateMessage();
$privateMessage->sender_id = $user->id;
$privateMessage->receiver_id = $recipient->id;
$privateMessage->subject = $request->input('subject');
$privateMessage->message = $request->input('message');
$privateMessage->read = 0;
$v = validator($pm->toArray(), [
$v = \validator($privateMessage->toArray(), [
'sender_id' => 'required',
'receiver_id' => 'required',
'subject' => 'required',
@@ -165,20 +168,20 @@ class PrivateMessageController extends Controller
if ($v->fails()) {
if ($dest == 'profile') {
return redirect()->route('users.show', ['username' => $recipient->username])
return \redirect()->route('users.show', ['username' => $recipient->username])
->withErrors($v->errors());
}
return redirect()->route('create', ['username' => $request->user()->username, 'id' => $request->user()->id])
return \redirect()->route('create', ['username' => $request->user()->username, 'id' => $request->user()->id])
->withErrors($v->errors());
}
$pm->save();
$privateMessage->save();
if ($dest == 'profile') {
return redirect()->route('users.show', ['username' => $recipient->username])
return \redirect()->route('users.show', ['username' => $recipient->username])
->withSuccess('Your PM Was Sent Successfully!');
}
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withSuccess('Your PM Was Sent Successfully!');
}
@@ -196,15 +199,15 @@ class PrivateMessageController extends Controller
$message = PrivateMessage::where('id', '=', $id)->firstOrFail();
$pm = new PrivateMessage();
$pm->sender_id = $user->id;
$pm->receiver_id = $message->sender_id == $user->id ? $message->receiver_id : $message->sender_id;
$pm->subject = $message->subject;
$pm->message = $request->input('message');
$pm->related_to = $message->id;
$pm->read = 0;
$privateMessage = new PrivateMessage();
$privateMessage->sender_id = $user->id;
$privateMessage->receiver_id = $message->sender_id == $user->id ? $message->receiver_id : $message->sender_id;
$privateMessage->subject = $message->subject;
$privateMessage->message = $request->input('message');
$privateMessage->related_to = $message->id;
$privateMessage->read = 0;
$v = validator($pm->toArray(), [
$v = \validator($privateMessage->toArray(), [
'sender_id' => 'required',
'receiver_id' => 'required',
'subject' => 'required',
@@ -214,12 +217,12 @@ class PrivateMessageController extends Controller
]);
if ($v->fails()) {
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withErrors($v->errors());
}
$pm->save();
$privateMessage->save();
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withSuccess('Your PM Was Sent Successfully!');
}
@@ -229,6 +232,8 @@ class PrivateMessageController extends Controller
* @param \Illuminate\Http\Request $request
* @param \App\Models\PrivateMessage $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function deletePrivateMessage(Request $request, $id)
@@ -245,14 +250,14 @@ class PrivateMessageController extends Controller
$pm->delete();
if ($dest == 'outbox') {
return redirect()->route('outbox')->withSuccess('PM Was Deleted Successfully!');
return \redirect()->route('outbox')->withSuccess('PM Was Deleted Successfully!');
}
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withSuccess('PM Was Deleted Successfully!');
}
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withErrors('What Are You Trying To Do Here!');
}
@@ -268,7 +273,7 @@ class PrivateMessageController extends Controller
$user = $request->user();
$pms = PrivateMessage::where('receiver_id', '=', $user->id)->delete();
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withSuccess('PM Was Deleted Successfully!');
}
@@ -288,7 +293,7 @@ class PrivateMessageController extends Controller
$pm->save();
}
return redirect()->route('inbox')
return \redirect()->route('inbox')
->withSuccess('Your Messages Have All Been Marked As Read!');
}
}

View File

@@ -19,6 +19,9 @@ use App\Models\TorrentRequest;
use App\Models\User;
use Illuminate\Http\Request;
/**
* @see \Tests\Todo\Feature\Http\Controllers\ReportControllerTest
*/
class ReportController extends Controller
{
/**
@@ -50,12 +53,12 @@ class ReportController extends Controller
$reported_by = $request->user();
$reported_user = $torrentRequest->user;
$v = validator($request->all(), [
$v = \validator($request->all(), [
'message' => 'required',
]);
if ($v->fails()) {
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withErrors($v->errors());
}
$this->report->create([
@@ -69,7 +72,7 @@ class ReportController extends Controller
'solved' => 0,
]);
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withSuccess('Your report has been successfully sent');
}
@@ -87,12 +90,12 @@ class ReportController extends Controller
$reported_by = $request->user();
$reported_user = $torrent->user;
$v = validator($request->all(), [
$v = \validator($request->all(), [
'message' => 'required',
]);
if ($v->fails()) {
return redirect()->route('torrent', ['id' => $id])
return \redirect()->route('torrent', ['id' => $id])
->withErrors($v->errors());
}
$this->report->create([
@@ -106,7 +109,7 @@ class ReportController extends Controller
'solved' => 0,
]);
return redirect()->route('torrent', ['id' => $id])
return \redirect()->route('torrent', ['id' => $id])
->withSuccess('Your report has been successfully sent');
}
@@ -123,12 +126,12 @@ class ReportController extends Controller
$reported_user = User::where('username', '=', $username)->firstOrFail();
$reported_by = $request->user();
$v = validator($request->all(), [
$v = \validator($request->all(), [
'message' => 'required',
]);
if ($v->fails()) {
return redirect()->route('users.show', ['username' => $username])
return \redirect()->route('users.show', ['username' => $username])
->withErrors($v->errors());
}
$this->report->create([
@@ -142,7 +145,7 @@ class ReportController extends Controller
'solved' => 0,
]);
return redirect()->route('users.show', ['username' => $username])
return \redirect()->route('users.show', ['username' => $username])
->withSuccess('Your report has been successfully sent');
}
}

View File

@@ -19,6 +19,7 @@ use App\Achievements\UserFilled50Requests;
use App\Achievements\UserFilled75Requests;
use App\Models\BonTransactions;
use App\Models\Category;
use App\Models\Resolution;
use App\Models\Torrent;
use App\Models\TorrentRequest;
use App\Models\TorrentRequestBounty;
@@ -39,28 +40,31 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use MarcReichel\IGDBLaravel\Models\Game;
/**
* @see \Tests\Todo\Feature\Http\Controllers\RequestControllerTest
*/
class RequestController extends Controller
{
/**
* @var RequestFacetedRepository
*/
private $faceted;
private $requestFacetedRepository;
/**
* @var ChatRepository
*/
private $chat;
private $chatRepository;
/**
* RequestController Constructor.
*
* @param RequestFacetedRepository $faceted
* @param ChatRepository $chat
* @param \App\Repositories\RequestFacetedRepository $requestFacetedRepository
* @param \App\Repositories\ChatRepository $chatRepository
*/
public function __construct(RequestFacetedRepository $faceted, ChatRepository $chat)
public function __construct(RequestFacetedRepository $requestFacetedRepository, ChatRepository $chatRepository)
{
$this->faceted = $faceted;
$this->chat = $chat;
$this->requestFacetedRepository = $requestFacetedRepository;
$this->chatRepository = $chatRepository;
}
/**
@@ -86,9 +90,9 @@ class RequestController extends Controller
->first();
$torrentRequests = TorrentRequest::with(['user', 'category', 'type'])->paginate(25);
$repository = $this->faceted;
$repository = $this->requestFacetedRepository;
return view('requests.requests', [
return \view('requests.requests', [
'torrentRequests' => $torrentRequests,
'repository' => $repository,
'user' => $user,
@@ -112,16 +116,17 @@ class RequestController extends Controller
$user = $request->user();
$search = $request->input('search');
$imdb_id = Str::startsWith($request->get('imdb'), 'tt') ? $request->get('imdb') : 'tt'.$request->get('imdb');
$imdb = str_replace('tt', '', $imdb_id);
$imdb = \str_replace('tt', '', $imdb_id);
$tvdb = $request->input('tvdb');
$tmdb = $request->input('tmdb');
$mal = $request->input('mal');
$igdb = $request->input('igdb');
$categories = $request->input('categories');
$types = $request->input('types');
$resolutions = $request->input('resolutions');
$myrequests = $request->input('myrequests');
$terms = explode(' ', $search);
$terms = \explode(' ', $search);
$search = '';
foreach ($terms as $term) {
$search .= '%'.$term.'%';
@@ -134,7 +139,7 @@ class RequestController extends Controller
}
if ($request->has('imdb') && $request->input('imdb') != null) {
$torrentRequest->where('imdb', '=', str_replace('tt', '', $imdb));
$torrentRequest->where('imdb', '=', \str_replace('tt', '', $imdb));
}
if ($request->has('tvdb') && $request->input('tvdb') != null) {
@@ -161,6 +166,10 @@ class RequestController extends Controller
$torrentRequest->whereIn('type_id', $types);
}
if ($request->has('resolutions') && $request->input('resolutions') != null) {
$torrentRequest->whereIn('resolution_id', $resolutions);
}
if ($request->has('unfilled') && $request->input('unfilled') != null) {
$torrentRequest->where('filled_hash', '=', null);
}
@@ -208,7 +217,7 @@ class RequestController extends Controller
$torrentRequests = $torrentRequest->paginate(25);
}
return view('requests.results', [
return \view('requests.results', [
'user' => $user,
'torrentRequests' => $torrentRequests,
])->render();
@@ -235,27 +244,27 @@ class RequestController extends Controller
$comments = $torrentRequest->comments()->latest('created_at')->paginate(6);
$carbon = Carbon::now()->addDay();
$client = new \App\Services\MovieScrapper(config('api-keys.tmdb'), config('api-keys.tvdb'), config('api-keys.omdb'));
$movieScrapper = new \App\Services\MovieScrapper(\config('api-keys.tmdb'), \config('api-keys.tvdb'), \config('api-keys.omdb'));
$meta = null;
if ($torrentRequest->category->tv_meta) {
if ($torrentRequest->tmdb || $torrentRequest->tmdb != 0) {
$meta = $client->scrape('tv', null, $torrentRequest->tmdb);
$meta = $movieScrapper->scrape('tv', null, $torrentRequest->tmdb);
} else {
$meta = $client->scrape('tv', 'tt'.$torrentRequest->imdb);
$meta = $movieScrapper->scrape('tv', 'tt'.$torrentRequest->imdb);
}
}
if ($torrentRequest->category->movie_meta) {
if ($torrentRequest->tmdb || $torrentRequest->tmdb != 0) {
$meta = $client->scrape('movie', null, $torrentRequest->tmdb);
$meta = $movieScrapper->scrape('movie', null, $torrentRequest->tmdb);
} else {
$meta = $client->scrape('movie', 'tt'.$torrentRequest->imdb);
$meta = $movieScrapper->scrape('movie', 'tt'.$torrentRequest->imdb);
}
}
if ($torrentRequest->category->game_meta) {
$meta = Game::with(['cover' => ['url', 'image_id'], 'artworks' => ['url', 'image_id'], 'genres' => ['name']])->find($torrentRequest->igdb);
}
return view('requests.request', [
return \view('requests.request', [
'torrentRequest' => $torrentRequest,
'voters' => $voters, 'user' => $user,
'comments' => $comments,
@@ -279,13 +288,14 @@ class RequestController extends Controller
{
$user = $request->user();
return view('requests.add_request', [
'categories' => Category::all()->sortBy('position'),
'types' => Type::all()->sortBy('position'),
'user' => $user,
'title' => $title,
'imdb' => str_replace('tt', '', $imdb),
'tmdb' => $tmdb,
return \view('requests.add_request', [
'categories' => Category::all()->sortBy('position'),
'types' => Type::all()->sortBy('position'),
'resolutions' => Resolution::all()->sortBy('position'),
'user' => $user,
'title' => $title,
'imdb' => \str_replace('tt', '', $imdb),
'tmdb' => $tmdb,
]);
}
@@ -301,70 +311,72 @@ class RequestController extends Controller
$user = $request->user();
$category = Category::findOrFail($request->input('category_id'));
$tr = new TorrentRequest();
$tr->name = $request->input('name');
$tr->description = $request->input('description');
$tr->category_id = $category->id;
$tr->user_id = $user->id;
$tr->imdb = $request->input('imdb');
$tr->tvdb = $request->input('tvdb');
$tr->tmdb = $request->input('tmdb');
$tr->mal = $request->input('mal');
$tr->igdb = $request->input('igdb');
$tr->type_id = $request->input('type_id');
$tr->bounty = $request->input('bounty');
$tr->votes = 1;
$tr->anon = $request->input('anon');
$torrentRequest = new TorrentRequest();
$torrentRequest->name = $request->input('name');
$torrentRequest->description = $request->input('description');
$torrentRequest->category_id = $category->id;
$torrentRequest->user_id = $user->id;
$torrentRequest->imdb = $request->input('imdb');
$torrentRequest->tvdb = $request->input('tvdb');
$torrentRequest->tmdb = $request->input('tmdb');
$torrentRequest->mal = $request->input('mal');
$torrentRequest->igdb = $request->input('igdb');
$torrentRequest->type_id = $request->input('type_id');
$torrentRequest->resolution_id = $request->input('resolution_id');
$torrentRequest->bounty = $request->input('bounty');
$torrentRequest->votes = 1;
$torrentRequest->anon = $request->input('anon');
$v = validator($tr->toArray(), [
'name' => 'required|max:180',
'imdb' => 'required|numeric',
'tvdb' => 'required|numeric',
'tmdb' => 'required|numeric',
'mal' => 'required|numeric',
'igdb' => 'required|numeric',
'category_id' => 'required|exists:categories,id',
'type_id' => 'required|exists:types,id',
'description' => 'required|string',
'bounty' => sprintf('required|numeric|min:0|max:%s', $user->seedbonus),
'anon' => 'required',
$v = \validator($torrentRequest->toArray(), [
'name' => 'required|max:180',
'imdb' => 'required|numeric',
'tvdb' => 'required|numeric',
'tmdb' => 'required|numeric',
'mal' => 'required|numeric',
'igdb' => 'required|numeric',
'category_id' => 'required|exists:categories,id',
'type_id' => 'required|exists:types,id',
'resolution_id' => 'nullable|exists:resolutions,id',
'description' => 'required|string',
'bounty' => \sprintf('required|numeric|min:0|max:%s', $user->seedbonus),
'anon' => 'required',
]);
if ($v->fails()) {
return redirect()->route('requests')
return \redirect()->route('requests')
->withErrors($v->errors())->withInput();
}
$tr->save();
$requestsBounty = new TorrentRequestBounty();
$requestsBounty->user_id = $user->id;
$requestsBounty->seedbonus = $request->input('bounty');
$requestsBounty->requests_id = $tr->id;
$requestsBounty->anon = $request->input('anon');
$requestsBounty->save();
$torrentRequest->save();
$torrentRequestBounty = new TorrentRequestBounty();
$torrentRequestBounty->user_id = $user->id;
$torrentRequestBounty->seedbonus = $request->input('bounty');
$torrentRequestBounty->requests_id = $torrentRequest->id;
$torrentRequestBounty->anon = $request->input('anon');
$torrentRequestBounty->save();
$BonTransactions = new BonTransactions();
$BonTransactions->itemID = 0;
$BonTransactions->name = 'request';
$BonTransactions->cost = $request->input('bounty');
$BonTransactions->sender = $user->id;
$BonTransactions->receiver = 0;
$BonTransactions->comment = sprintf('new request - %s', $request->input('name'));
$BonTransactions->comment = \sprintf('new request - %s', $request->input('name'));
$BonTransactions->save();
$user->seedbonus -= $request->input('bounty');
$user->save();
$tr_url = href_request($tr);
$profile_url = href_profile($user);
$tr_url = \href_request($torrentRequest);
$profile_url = \href_profile($user);
// Auto Shout
if ($tr->anon == 0) {
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has created a new request [url=%s]%s[/url]', $profile_url, $user->username, $tr_url, $tr->name)
if ($torrentRequest->anon == 0) {
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has created a new request [url=%s]%s[/url]', $profile_url, $user->username, $tr_url, $torrentRequest->name)
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user has created a new request [url=%s]%s[/url]', $tr_url, $tr->name)
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has created a new request [url=%s]%s[/url]', $tr_url, $torrentRequest->name)
);
}
return redirect()->route('requests')
return \redirect()->route('requests')
->withSuccess('Request Added.');
}
@@ -381,9 +393,10 @@ class RequestController extends Controller
$user = $request->user();
$torrentRequest = TorrentRequest::findOrFail($id);
return view('requests.edit_request', [
return \view('requests.edit_request', [
'categories' => Category::all()->sortBy('position'),
'types' => Type::all()->sortBy('position'),
'resolutions' => Resolution::all()->sortBy('position'),
'user' => $user,
'torrentRequest' => $torrentRequest, ]);
}
@@ -400,7 +413,7 @@ class RequestController extends Controller
{
$user = $request->user();
$torrentRequest = TorrentRequest::findOrFail($id);
abort_unless($user->group->is_modo || $user->id === $torrentRequest->user_id, 403);
\abort_unless($user->group->is_modo || $user->id === $torrentRequest->user_id, 403);
// Find the right category
$name = $request->input('name');
@@ -411,6 +424,7 @@ class RequestController extends Controller
$igdb = $request->input('igdb');
$category = $request->input('category_id');
$type = $request->input('type_id');
$resolution = $request->input('resolution_id');
$description = $request->input('description');
$anon = $request->input('anon');
@@ -422,29 +436,31 @@ class RequestController extends Controller
$torrentRequest->igdb = $igdb;
$torrentRequest->category_id = $category;
$torrentRequest->type_id = $type;
$torrentRequest->resolution_id = $resolution;
$torrentRequest->description = $description;
$torrentRequest->anon = $anon;
$v = validator($torrentRequest->toArray(), [
'name' => 'required|max:180',
'imdb' => 'required|numeric',
'tvdb' => 'required|numeric',
'tmdb' => 'required|numeric',
'mal' => 'required|numeric',
'igdb' => 'required|numeric',
'category_id' => 'required|exists:categories,id',
'type_id' => 'required|exists:types,id',
'description' => 'required|string',
'anon' => 'required',
$v = \validator($torrentRequest->toArray(), [
'name' => 'required|max:180',
'imdb' => 'required|numeric',
'tvdb' => 'required|numeric',
'tmdb' => 'required|numeric',
'mal' => 'required|numeric',
'igdb' => 'required|numeric',
'category_id' => 'required|exists:categories,id',
'type_id' => 'required|exists:types,id',
'resolution_id' => 'nullable|exists:resolutions,id',
'description' => 'required|string',
'anon' => 'required',
]);
if ($v->fails()) {
return redirect()->route('requests')
return \redirect()->route('requests')
->withErrors($v->errors());
}
$torrentRequest->save();
return redirect()->route('requests', ['id' => $torrentRequest->id])
return \redirect()->route('requests', ['id' => $torrentRequest->id])
->withSuccess('Request Edited Successfully.');
}
@@ -465,41 +481,41 @@ class RequestController extends Controller
$tr->bounty += $request->input('bonus_value');
$tr->created_at = Carbon::now();
$v = validator($request->all(), [
'bonus_value' => sprintf('required|numeric|min:100|max:%s', $user->seedbonus),
$v = \validator($request->all(), [
'bonus_value' => \sprintf('required|numeric|min:100|max:%s', $user->seedbonus),
]);
if ($v->fails()) {
return redirect()->route('request', ['id' => $tr->id])
return \redirect()->route('request', ['id' => $tr->id])
->withErrors($v->errors());
}
$tr->save();
$requestsBounty = new TorrentRequestBounty();
$requestsBounty->user_id = $user->id;
$requestsBounty->seedbonus = $request->input('bonus_value');
$requestsBounty->requests_id = $tr->id;
$requestsBounty->anon = $request->input('anon');
$requestsBounty->save();
$torrentRequestBounty = new TorrentRequestBounty();
$torrentRequestBounty->user_id = $user->id;
$torrentRequestBounty->seedbonus = $request->input('bonus_value');
$torrentRequestBounty->requests_id = $tr->id;
$torrentRequestBounty->anon = $request->input('anon');
$torrentRequestBounty->save();
$BonTransactions = new BonTransactions();
$BonTransactions->itemID = 0;
$BonTransactions->name = 'request';
$BonTransactions->cost = $request->input('bonus_value');
$BonTransactions->sender = $user->id;
$BonTransactions->receiver = 0;
$BonTransactions->comment = sprintf('adding bonus to %s', $tr->name);
$BonTransactions->comment = \sprintf('adding bonus to %s', $tr->name);
$BonTransactions->save();
$user->seedbonus -= $request->input('bonus_value');
$user->save();
$tr_url = href_request($tr);
$profile_url = href_profile($user);
$tr_url = \href_request($tr);
$profile_url = \href_profile($user);
// Auto Shout
if ($requestsBounty->anon == 0) {
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has added %s BON bounty to request [url=%s]%s[/url]', $profile_url, $user->username, $request->input('bonus_value'), $tr_url, $tr->name)
if ($torrentRequestBounty->anon == 0) {
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has added %s BON bounty to request [url=%s]%s[/url]', $profile_url, $user->username, $request->input('bonus_value'), $tr_url, $tr->name)
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user added %s BON bounty to request [url=%s]%s[/url]', $request->input('bonus_value'), $tr_url, $tr->name)
$this->chatRepository->systemMessage(
\sprintf('An anonymous user added %s BON bounty to request [url=%s]%s[/url]', $request->input('bonus_value'), $tr_url, $tr->name)
);
}
$sender = $request->input('anon') == 1 ? 'Anonymous' : $user->username;
@@ -508,7 +524,7 @@ class RequestController extends Controller
$requester->notify(new NewRequestBounty('torrent', $sender, $request->input('bonus_value'), $tr));
}
return redirect()->route('request', ['id' => $request->input('request_id')])
return \redirect()->route('request', ['id' => $request->input('request_id')])
->withSuccess('Your bonus has been successfully added.');
}
@@ -530,7 +546,7 @@ class RequestController extends Controller
$torrentRequest->filled_when = Carbon::now();
$torrentRequest->filled_anon = $request->input('filled_anon');
$v = validator($request->all(), [
$v = \validator($request->all(), [
'request_id' => 'required|exists:requests,id',
'info_hash' => 'required|exists:torrents,info_hash',
'filled_anon' => 'required',
@@ -538,24 +554,24 @@ class RequestController extends Controller
$torrent = Torrent::where('info_hash', '=', $torrentRequest->filled_hash)->first();
if ($torrent && ! $torrent->isApproved()) {
return redirect()->route('request', ['id' => $request->input('request_id')])
return \redirect()->route('request', ['id' => $request->input('request_id')])
->withErrors('The torrent info_hash you are trying to use is valid in our database but is still pending moderation. Please wait for your torrent to be approved and then try again.');
}
if ($v->fails()) {
return redirect()->route('request', ['id' => $request->input('request_id')])
return \redirect()->route('request', ['id' => $request->input('request_id')])
->withErrors($v->errors());
}
$torrentRequest->save();
// Send Private Message
$appurl = config('app.url');
$appurl = \config('app.url');
$sender = $request->input('filled_anon') == 1 ? 'Anonymous' : $user->username;
$requester = $torrentRequest->user;
if ($requester->acceptsNotification($request->user(), $requester, 'request', 'show_request_fill')) {
$requester->notify(new NewRequestFill('torrent', $sender, $torrentRequest));
}
return redirect()->route('request', ['id' => $request->input('request_id')])
return \redirect()->route('request', ['id' => $request->input('request_id')])
->withSuccess('Your request fill is pending approval by the Requester.');
}
@@ -575,7 +591,7 @@ class RequestController extends Controller
if ($user->id == $tr->user_id || $request->user()->group->is_modo) {
if ($tr->approved_by != null) {
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withErrors('Seems this request was already approved');
}
$tr->approved_by = $user->id;
@@ -592,7 +608,7 @@ class RequestController extends Controller
$BonTransactions->cost = $fill_amount;
$BonTransactions->sender = 0;
$BonTransactions->receiver = $fill_user->id;
$BonTransactions->comment = sprintf('%s has filled %s and has been awarded %s BONUS.', $fill_user->username, $tr->name, $fill_amount);
$BonTransactions->comment = \sprintf('%s has filled %s and has been awarded %s BONUS.', $fill_user->username, $tr->name, $fill_amount);
$BonTransactions->save();
$fill_user->seedbonus += $fill_amount;
@@ -604,17 +620,17 @@ class RequestController extends Controller
$fill_user->addProgress(new UserFilled75Requests(), 1);
$fill_user->addProgress(new UserFilled100Requests(), 1);
$tr_url = href_request($tr);
$profile_url = href_profile($fill_user);
$tr_url = \href_request($tr);
$profile_url = \href_profile($fill_user);
// Auto Shout
if ($tr->filled_anon == 0) {
$this->chat->systemMessage(
sprintf('[url=%s]%s[/url] has filled request, [url=%s]%s[/url]', $profile_url, $fill_user->username, $tr_url, $tr->name)
$this->chatRepository->systemMessage(
\sprintf('[url=%s]%s[/url] has filled request, [url=%s]%s[/url]', $profile_url, $fill_user->username, $tr_url, $tr->name)
);
} else {
$this->chat->systemMessage(
sprintf('An anonymous user has filled request, [url=%s]%s[/url]', $tr_url, $tr->name)
$this->chatRepository->systemMessage(
\sprintf('An anonymous user has filled request, [url=%s]%s[/url]', $tr_url, $tr->name)
);
}
@@ -624,15 +640,15 @@ class RequestController extends Controller
}
if ($tr->filled_anon == 0) {
return redirect()->route('request', ['id' => $id])
->withSuccess(sprintf('You have approved %s and the bounty has been awarded to %s', $tr->name, $fill_user->username));
return \redirect()->route('request', ['id' => $id])
->withSuccess(\sprintf('You have approved %s and the bounty has been awarded to %s', $tr->name, $fill_user->username));
}
return redirect()->route('request', ['id' => $id])
->withSuccess(sprintf('You have approved %s and the bounty has been awarded to a anonymous user', $tr->name));
return \redirect()->route('request', ['id' => $id])
->withSuccess(\sprintf('You have approved %s and the bounty has been awarded to a anonymous user', $tr->name));
}
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withErrors("You don't have access to approve this request");
}
@@ -647,12 +663,12 @@ class RequestController extends Controller
public function rejectRequest(Request $request, $id)
{
$user = $request->user();
$appurl = config('app.url');
$appurl = \config('app.url');
$torrentRequest = TorrentRequest::findOrFail($id);
if ($user->id == $torrentRequest->user_id) {
if ($torrentRequest->approved_by != null) {
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withErrors('Seems this request was already rejected');
}
@@ -666,11 +682,11 @@ class RequestController extends Controller
$torrentRequest->filled_hash = null;
$torrentRequest->save();
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withSuccess('This request has been reset.');
}
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withSuccess("You don't have access to approve this request");
}
@@ -680,6 +696,8 @@ class RequestController extends Controller
* @param \Illuminate\Http\Request $request
* @param \App\Models\TorrentRequest $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function deleteRequest(Request $request, $id)
@@ -691,11 +709,11 @@ class RequestController extends Controller
$name = $torrentRequest->name;
$torrentRequest->delete();
return redirect()->route('requests')
->withSuccess(sprintf('You have deleted %s', $name));
return \redirect()->route('requests')
->withSuccess(\sprintf('You have deleted %s', $name));
}
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withErrors("You don't have access to delete this request.");
}
@@ -713,11 +731,11 @@ class RequestController extends Controller
$torrentRequest = TorrentRequest::with('user')->findOrFail($id);
if ($torrentRequest->claimed == null) {
$requestClaim = new TorrentRequestClaim();
$requestClaim->request_id = $id;
$requestClaim->username = $user->username;
$requestClaim->anon = $request->input('anon');
$requestClaim->save();
$torrentRequestClaim = new TorrentRequestClaim();
$torrentRequestClaim->request_id = $id;
$torrentRequestClaim->username = $user->username;
$torrentRequestClaim->anon = $request->input('anon');
$torrentRequestClaim->save();
$torrentRequest->claimed = 1;
$torrentRequest->save();
@@ -729,11 +747,11 @@ class RequestController extends Controller
$requester->notify(new NewRequestClaim('torrent', $sender, $torrentRequest));
}
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withSuccess('Request Successfully Claimed');
}
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withErrors('Someone else has already claimed this request buddy.');
}
@@ -743,6 +761,8 @@ class RequestController extends Controller
* @param \Illuminate\Http\Request $request
* @param \App\Models\TorrentRequest $id
*
* @throws \Exception
*
* @return \Illuminate\Http\RedirectResponse
*/
public function unclaimRequest(Request $request, $id)
@@ -751,7 +771,7 @@ class RequestController extends Controller
$torrentRequest = TorrentRequest::findOrFail($id);
$claimer = TorrentRequestClaim::where('request_id', '=', $id)->first();
abort_unless($user->group->is_modo || $user->username == $claimer->username, 403);
\abort_unless($user->group->is_modo || $user->username == $claimer->username, 403);
if ($torrentRequest->claimed == 1) {
$requestClaim = TorrentRequestClaim::where('request_id', '=', $id)->firstOrFail();
@@ -768,11 +788,11 @@ class RequestController extends Controller
$requester->notify(new NewRequestUnclaim('torrent', $sender, $torrentRequest));
}
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withSuccess('Request Successfully Un-Claimed');
}
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withErrors('Nothing To Unclaim.');
}
@@ -787,7 +807,7 @@ class RequestController extends Controller
public function resetRequest(Request $request, $id)
{
$user = $request->user();
abort_unless($user->group->is_modo, 403);
\abort_unless($user->group->is_modo, 403);
$torrentRequest = TorrentRequest::findOrFail($id);
$torrentRequest->filled_by = null;
@@ -797,7 +817,7 @@ class RequestController extends Controller
$torrentRequest->approved_when = null;
$torrentRequest->save();
return redirect()->route('request', ['id' => $id])
return \redirect()->route('request', ['id' => $id])
->withSuccess('The request has been reset!');
}
}

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