chore: code refactor via rector

This commit is contained in:
idevakk
2025-11-14 02:01:01 -08:00
parent 90ab79b3a2
commit ae795880ed
148 changed files with 1520 additions and 1486 deletions

View File

@@ -35,13 +35,9 @@ trait ColorPicker
'Z' => ['dark' => 'dark:bg-teal-500', 'light' => 'bg-teal-800'], 'Z' => ['dark' => 'dark:bg-teal-500', 'light' => 'bg-teal-800'],
]; ];
$letter = strtoupper($letter); $letter = strtoupper((string) $letter);
if (isset($colorReferences[$letter])) { return $colorReferences[$letter] ?? ['dark' => 'dark:bg-gray-500', 'light' => 'bg-gray-800'];
return $colorReferences[$letter];
}
return ['dark' => 'dark:bg-gray-500', 'light' => 'bg-gray-800'];
} }
} }

View File

@@ -2,6 +2,10 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use BackedEnum;
use UnitEnum;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use App\Models\ActivationKey; use App\Models\ActivationKey;
use App\Models\Plan; use App\Models\Plan;
use Filament\Actions\BulkAction; use Filament\Actions\BulkAction;
@@ -19,17 +23,16 @@ use Filament\Tables\Filters\SelectFilter;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Response; use Response;
use Str;
class GenerateActivationKeys extends Page implements HasForms, HasTable class GenerateActivationKeys extends Page implements HasForms, HasTable
{ {
use InteractsWithForms, InteractsWithTable; use InteractsWithForms, InteractsWithTable;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-key'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-key';
protected string $view = 'filament.pages.generate-activation-keys'; protected string $view = 'filament.pages.generate-activation-keys';
protected static string|\UnitEnum|null $navigationGroup = 'Admin'; protected static string|UnitEnum|null $navigationGroup = 'Admin';
protected static ?string $title = 'Activation Keys'; protected static ?string $title = 'Activation Keys';
@@ -59,13 +62,13 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable
]; ];
} }
public function generate() public function generate(): void
{ {
$data = $this->form->getState(); $data = $this->form->getState();
$plan = Plan::findOrFail($data['plan_id']); $plan = Plan::query()->findOrFail($data['plan_id']);
for ($i = 0; $i < $data['quantity']; $i++) { for ($i = 0; $i < $data['quantity']; $i++) {
ActivationKey::create([ ActivationKey::query()->create([
'price_id' => $plan->pricing_id, 'price_id' => $plan->pricing_id,
'activation_key' => strtoupper('Z'.Str::random(16)), 'activation_key' => strtoupper('Z'.Str::random(16)),
'is_activated' => false, 'is_activated' => false,
@@ -99,8 +102,8 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable
TextColumn::make('billing_interval') TextColumn::make('billing_interval')
->label('Interval') ->label('Interval')
->getStateUsing(function ($record) { ->getStateUsing(function ($record): string {
$isMonthly = Plan::where('pricing_id', $record->price_id)->value('monthly_billing'); $isMonthly = Plan::query()->where('pricing_id', $record->price_id)->value('monthly_billing');
return $isMonthly ? 'Monthly' : 'Yearly'; return $isMonthly ? 'Monthly' : 'Yearly';
}), }),
@@ -121,7 +124,7 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable
SelectFilter::make('price_id') SelectFilter::make('price_id')
->label('Plan') ->label('Plan')
->options( ->options(
Plan::pluck('name', 'pricing_id') Plan::query()->pluck('name', 'pricing_id')
), ),
]; ];
} }
@@ -130,13 +133,13 @@ class GenerateActivationKeys extends Page implements HasForms, HasTable
{ {
return [ return [
BulkAction::make('Download Keys') BulkAction::make('Download Keys')
->action(fn (Collection $records) => $this->downloadKeys($records)) ->action(fn (Collection $records): BinaryFileResponse => $this->downloadKeys($records))
->deselectRecordsAfterCompletion() ->deselectRecordsAfterCompletion()
->requiresConfirmation(), ->requiresConfirmation(),
]; ];
} }
public function downloadKeys(Collection $records) public function downloadKeys(Collection $records): BinaryFileResponse
{ {
$text = $records->pluck('activation_key')->implode("\n"); $text = $records->pluck('activation_key')->implode("\n");

View File

@@ -2,9 +2,11 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use BackedEnum;
use UnitEnum;
use Illuminate\Support\Facades\Artisan;
use App\Models\Setting; use App\Models\Setting;
use App\Models\ZEmail; use App\Models\ZEmail;
use Artisan;
use Exception; use Exception;
use Filament\Forms\Components\Checkbox; use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\KeyValue; use Filament\Forms\Components\KeyValue;
@@ -25,17 +27,17 @@ class Settings extends Page implements HasForms
public ?array $data = []; public ?array $data = [];
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-cog-6-tooth'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-cog-6-tooth';
protected string $view = 'filament.pages.settings'; protected string $view = 'filament.pages.settings';
protected static string|\UnitEnum|null $navigationGroup = 'Web Master'; protected static string|UnitEnum|null $navigationGroup = 'Web Master';
public function mount(): void public function mount(): void
{ {
$user = auth()->user(); $user = auth()->user();
$auth_email = $user->email; $auth_email = $user->email;
$setting = Setting::where('app_admin', $auth_email)->first(); $setting = Setting::query()->where('app_admin', $auth_email)->first();
if ($setting) { if ($setting) {
$imapSettings = $setting->imap_settings ?? []; $imapSettings = $setting->imap_settings ?? [];
@@ -50,7 +52,7 @@ class Settings extends Page implements HasForms
]); ]);
$this->applyDefaults($configurationSettings, [ $this->applyDefaults($configurationSettings, [
'cron_password' => fn () => $this->generateRandomString(20), 'cron_password' => fn (): string => $this->generateRandomString(20),
'date_format' => 'd M Y h:i A', 'date_format' => 'd M Y h:i A',
'after_last_email_delete' => 'redirect_to_homepage', 'after_last_email_delete' => 'redirect_to_homepage',
]); ]);
@@ -68,9 +70,7 @@ class Settings extends Page implements HasForms
foreach ($transformMap as $key => $subKey) { foreach ($transformMap as $key => $subKey) {
if (isset($configurationSettings[$key])) { if (isset($configurationSettings[$key])) {
$configurationSettings[$key] = array_map(function ($value) use ($subKey) { $configurationSettings[$key] = array_map(fn($value): array => [$subKey => $value], $configurationSettings[$key]);
return [$subKey => $value];
}, $configurationSettings[$key]);
} }
} }
$this->form->fill([ $this->form->fill([
@@ -376,12 +376,11 @@ class Settings extends Page implements HasForms
$data = $this->form->getState(); $data = $this->form->getState();
if (! $this->testIMAP($data['imap_settings'])) { if (! $this->testIMAP($data['imap_settings'])) {
return; return;
} else { }
Notification::make() Notification::make()
->title('IMAP Connection Successful') ->title('IMAP Connection Successful')
->success() ->success()
->send(); ->send();
}
foreach ([ foreach ([
'protocol' => 'imap', 'protocol' => 'imap',
'default_account' => 'default', 'default_account' => 'default',
@@ -410,7 +409,7 @@ class Settings extends Page implements HasForms
} }
} }
$setting = Setting::where('id', 1)->first(); $setting = Setting::query()->where('id', 1)->first();
$user = auth()->user(); $user = auth()->user();
$auth_email = $user->email; $auth_email = $user->email;
@@ -447,7 +446,7 @@ class Settings extends Page implements HasForms
'configuration_settings' => $data['configuration_settings'], 'configuration_settings' => $data['configuration_settings'],
'ads_settings' => $data['ads_settings'], 'ads_settings' => $data['ads_settings'],
]; ];
$create_res = Setting::create(array_merge($data)); $create_res = Setting::query()->create(array_merge($data));
if ($create_res) { if ($create_res) {
Notification::make() Notification::make()
@@ -464,13 +463,13 @@ class Settings extends Page implements HasForms
} }
} }
private function generateRandomString($length = 10): string private function generateRandomString(int $length = 10): string
{ {
$characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters); $charactersLength = strlen($characters);
$randomString = ''; $randomString = '';
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)]; $randomString .= $characters[random_int(0, $charactersLength - 1)];
} }
return $randomString; return $randomString;

View File

@@ -2,6 +2,8 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use BackedEnum;
use UnitEnum;
use App\Filament\Resources\BlogResource\Pages\CreateBlog; use App\Filament\Resources\BlogResource\Pages\CreateBlog;
use App\Filament\Resources\BlogResource\Pages\EditBlog; use App\Filament\Resources\BlogResource\Pages\EditBlog;
use App\Filament\Resources\BlogResource\Pages\ListBlogs; use App\Filament\Resources\BlogResource\Pages\ListBlogs;
@@ -33,13 +35,13 @@ class BlogResource extends Resource
{ {
protected static ?string $model = Blog::class; protected static ?string $model = Blog::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-m-newspaper'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-m-newspaper';
protected static string|\UnitEnum|null $navigationGroup = 'Content'; protected static string|UnitEnum|null $navigationGroup = 'Content';
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {
$categories = Category::pluck('name', 'id')->toArray(); Category::query()->pluck('name', 'id')->toArray();
return $schema return $schema
->components([ ->components([
@@ -50,7 +52,7 @@ class BlogResource extends Resource
->required() ->required()
->live(1) ->live(1)
->columnSpanFull() ->columnSpanFull()
->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state))), ->afterStateUpdated(fn (Set $set, ?string $state): mixed => $set('slug', Str::slug($state))),
TextInput::make('slug') TextInput::make('slug')
->required() ->required()
@@ -132,7 +134,7 @@ class BlogResource extends Resource
Action::make('togglePublished') Action::make('togglePublished')
->label('Toggle Published') ->label('Toggle Published')
->icon('heroicon-o-eye') ->icon('heroicon-o-eye')
->action(function (Blog $record) { ->action(function (Blog $record): void {
$record->update(['is_published' => ! $record->is_published]); $record->update(['is_published' => ! $record->is_published]);
}), }),
]) ])

View File

@@ -2,6 +2,8 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use BackedEnum;
use UnitEnum;
use App\Filament\Resources\CategoryResource\Pages\CreateCategory; use App\Filament\Resources\CategoryResource\Pages\CreateCategory;
use App\Filament\Resources\CategoryResource\Pages\EditCategory; use App\Filament\Resources\CategoryResource\Pages\EditCategory;
use App\Filament\Resources\CategoryResource\Pages\ListCategories; use App\Filament\Resources\CategoryResource\Pages\ListCategories;
@@ -26,9 +28,9 @@ class CategoryResource extends Resource
{ {
protected static ?string $model = Category::class; protected static ?string $model = Category::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-ticket'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-ticket';
protected static string|\UnitEnum|null $navigationGroup = 'Content'; protected static string|UnitEnum|null $navigationGroup = 'Content';
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {
@@ -37,7 +39,7 @@ class CategoryResource extends Resource
TextInput::make('name') TextInput::make('name')
->required() ->required()
->live(1) ->live(1)
->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state))), ->afterStateUpdated(fn (Set $set, ?string $state): mixed => $set('slug', Str::slug($state))),
TextInput::make('slug')->required(), TextInput::make('slug')->required(),
Select::make('is_active') Select::make('is_active')
->options([ ->options([
@@ -58,9 +60,7 @@ class CategoryResource extends Resource
TextColumn::make('slug'), TextColumn::make('slug'),
TextColumn::make('blogs_count') TextColumn::make('blogs_count')
->label('Blogs') ->label('Blogs')
->getStateUsing(function (Category $record): int { ->getStateUsing(fn(Category $record): int => $record->blogs()->count()),
return $record->blogs()->count();
}),
IconColumn::make('is_active')->label('Active')->boolean(), IconColumn::make('is_active')->label('Active')->boolean(),
]) ])
->filters([ ->filters([
@@ -73,7 +73,7 @@ class CategoryResource extends Resource
Action::make('toggleStatus') Action::make('toggleStatus')
->label('Toggle Status') ->label('Toggle Status')
->icon('heroicon-o-power') ->icon('heroicon-o-power')
->action(function (Category $record) { ->action(function (Category $record): void {
$record->update(['is_active' => ! $record->is_active]); $record->update(['is_active' => ! $record->is_active]);
}), }),
]) ])

View File

@@ -2,6 +2,8 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use BackedEnum;
use UnitEnum;
use App\Filament\Resources\MenuResource\Pages\CreateMenu; use App\Filament\Resources\MenuResource\Pages\CreateMenu;
use App\Filament\Resources\MenuResource\Pages\EditMenu; use App\Filament\Resources\MenuResource\Pages\EditMenu;
use App\Filament\Resources\MenuResource\Pages\ListMenus; use App\Filament\Resources\MenuResource\Pages\ListMenus;
@@ -24,13 +26,13 @@ class MenuResource extends Resource
{ {
protected static ?string $model = Menu::class; protected static ?string $model = Menu::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-bars-3-bottom-left'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bars-3-bottom-left';
protected static string|\UnitEnum|null $navigationGroup = 'Content'; protected static string|UnitEnum|null $navigationGroup = 'Content';
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {
$menus = Menu::Pluck('name', 'id')->toArray(); $menus = Menu::query()->Pluck('name', 'id')->toArray();
return $schema return $schema
->components([ ->components([

View File

@@ -2,6 +2,8 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use BackedEnum;
use UnitEnum;
use App\Filament\Resources\PageResource\Pages\CreatePage; use App\Filament\Resources\PageResource\Pages\CreatePage;
use App\Filament\Resources\PageResource\Pages\EditPage; use App\Filament\Resources\PageResource\Pages\EditPage;
use App\Filament\Resources\PageResource\Pages\ListPages; use App\Filament\Resources\PageResource\Pages\ListPages;
@@ -32,13 +34,13 @@ class PageResource extends Resource
{ {
protected static ?string $model = Page::class; protected static ?string $model = Page::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-document'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document';
protected static string|\UnitEnum|null $navigationGroup = 'Content'; protected static string|UnitEnum|null $navigationGroup = 'Content';
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {
$pages = Page::Pluck('title', 'id')->toArray(); $pages = Page::query()->Pluck('title', 'id')->toArray();
return $schema return $schema
->components([ ->components([
@@ -50,7 +52,7 @@ class PageResource extends Resource
->required() ->required()
->live(1) ->live(1)
->columnSpanFull() ->columnSpanFull()
->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state))), ->afterStateUpdated(fn (Set $set, ?string $state): mixed => $set('slug', Str::slug($state))),
TextInput::make('slug')->required()->columnSpan(3), TextInput::make('slug')->required()->columnSpan(3),
Select::make('is_published') Select::make('is_published')
->options([ ->options([
@@ -114,7 +116,7 @@ class PageResource extends Resource
Action::make('togglePublished') Action::make('togglePublished')
->label('Toggle Published') ->label('Toggle Published')
->icon('heroicon-o-eye') ->icon('heroicon-o-eye')
->action(function (Page $record) { ->action(function (Page $record): void {
$record->update(['is_published' => ! $record->is_published]); $record->update(['is_published' => ! $record->is_published]);
}), }),
]) ])

View File

@@ -2,6 +2,8 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use BackedEnum;
use UnitEnum;
use App\Filament\Resources\PlanResource\Pages\CreatePlan; use App\Filament\Resources\PlanResource\Pages\CreatePlan;
use App\Filament\Resources\PlanResource\Pages\EditPlan; use App\Filament\Resources\PlanResource\Pages\EditPlan;
use App\Filament\Resources\PlanResource\Pages\ListPlans; use App\Filament\Resources\PlanResource\Pages\ListPlans;
@@ -26,9 +28,9 @@ class PlanResource extends Resource
{ {
protected static ?string $model = Plan::class; protected static ?string $model = Plan::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-rectangle-stack'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-rectangle-stack';
protected static string|\UnitEnum|null $navigationGroup = 'Web Master'; protected static string|UnitEnum|null $navigationGroup = 'Web Master';
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {

View File

@@ -2,6 +2,8 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use BackedEnum;
use UnitEnum;
use App\Filament\Resources\TicketResource\Pages\CreateTicket; use App\Filament\Resources\TicketResource\Pages\CreateTicket;
use App\Filament\Resources\TicketResource\Pages\EditTicket; use App\Filament\Resources\TicketResource\Pages\EditTicket;
use App\Filament\Resources\TicketResource\Pages\ListTickets; use App\Filament\Resources\TicketResource\Pages\ListTickets;
@@ -23,7 +25,6 @@ use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Schemas\Schema; use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Columns\BadgeColumn; use Filament\Tables\Columns\BadgeColumn;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter; use Filament\Tables\Filters\Filter;
@@ -37,9 +38,9 @@ class TicketResource extends Resource
{ {
protected static ?string $model = Ticket::class; protected static ?string $model = Ticket::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-ticket'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-ticket';
protected static string|\UnitEnum|null $navigationGroup = 'Support'; protected static string|UnitEnum|null $navigationGroup = 'Support';
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {
@@ -91,9 +92,9 @@ class TicketResource extends Resource
->searchable(), ->searchable(),
BadgeColumn::make('status') BadgeColumn::make('status')
->colors([ ->colors([
'success' => fn ($state) => $state === 'open', 'success' => fn ($state): bool => $state === 'open',
'warning' => fn ($state) => $state === 'pending', 'warning' => fn ($state): bool => $state === 'pending',
'danger' => fn ($state) => $state === 'closed', 'danger' => fn ($state): bool => $state === 'closed',
]) ])
->sortable(), ->sortable(),
TextColumn::make('created_at') TextColumn::make('created_at')
@@ -119,11 +120,9 @@ class TicketResource extends Resource
DatePicker::make('created_from')->label('Created From'), DatePicker::make('created_from')->label('Created From'),
DatePicker::make('created_until')->label('Created Until'), DatePicker::make('created_until')->label('Created Until'),
]) ])
->query(function ($query, array $data) { ->query(fn($query, array $data) => $query
return $query
->when($data['created_from'], fn ($query, $date) => $query->whereDate('created_at', '>=', $date)) ->when($data['created_from'], fn ($query, $date) => $query->whereDate('created_at', '>=', $date))
->when($data['created_until'], fn ($query, $date) => $query->whereDate('created_at', '<=', $date)); ->when($data['created_until'], fn ($query, $date) => $query->whereDate('created_at', '<=', $date))),
}),
]) ])
// ->actions([ // ->actions([
// Tables\Actions\EditAction::make(), // Tables\Actions\EditAction::make(),
@@ -135,8 +134,7 @@ class TicketResource extends Resource
Action::make('view') Action::make('view')
->label('View & Respond') ->label('View & Respond')
->icon('heroicon-o-eye') ->icon('heroicon-o-eye')
->schema(function (Ticket $ticket): array { ->schema(fn(Ticket $ticket): array => [
return [
TextArea::make('response') TextArea::make('response')
->label('Your Response') ->label('Your Response')
->required() ->required()
@@ -152,9 +150,8 @@ class TicketResource extends Resource
]) ])
->default($ticket->status === 'open' ? 'pending' : $ticket->status) ->default($ticket->status === 'open' ? 'pending' : $ticket->status)
->required(), ->required(),
]; ])
}) ->modalContent(function (Ticket $ticket): HtmlString {
->modalContent(function (Ticket $ticket) {
$html = '<div class="space-y-3 mb-3 text-sm">'; $html = '<div class="space-y-3 mb-3 text-sm">';
// Ticket Subject & Message // Ticket Subject & Message
@@ -185,8 +182,8 @@ class TicketResource extends Resource
return new HtmlString($html); return new HtmlString($html);
}) })
->action(function (array $data, Ticket $ticket) { ->action(function (array $data, Ticket $ticket): void {
TicketResponse::create([ TicketResponse::query()->create([
'ticket_id' => $ticket->id, 'ticket_id' => $ticket->id,
'user_id' => auth()->id(), 'user_id' => auth()->id(),
'response' => $data['response'], 'response' => $data['response'],
@@ -214,7 +211,7 @@ class TicketResource extends Resource
->color('danger') ->color('danger')
->requiresConfirmation() ->requiresConfirmation()
->visible(fn (Ticket $ticket): bool => $ticket->status !== 'closed') ->visible(fn (Ticket $ticket): bool => $ticket->status !== 'closed')
->action(function (Ticket $ticket) { ->action(function (Ticket $ticket): void {
$ticket->update(['status' => 'closed']); $ticket->update(['status' => 'closed']);
}), }),
Action::make('reopen') Action::make('reopen')
@@ -222,7 +219,7 @@ class TicketResource extends Resource
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('success') ->color('success')
->visible(fn (Ticket $ticket): bool => $ticket->status === 'closed') ->visible(fn (Ticket $ticket): bool => $ticket->status === 'closed')
->action(function (Ticket $ticket) { ->action(function (Ticket $ticket): void {
$ticket->update(['status' => 'open']); $ticket->update(['status' => 'open']);
}), }),
]) ])
@@ -235,7 +232,7 @@ class TicketResource extends Resource
->icon('heroicon-o-envelope') ->icon('heroicon-o-envelope')
->requiresConfirmation() ->requiresConfirmation()
->deselectRecordsAfterCompletion() ->deselectRecordsAfterCompletion()
->action(function (Collection $records) { ->action(function (Collection $records): void {
foreach ($records as $ticket) { foreach ($records as $ticket) {
$responses = $ticket->responses() $responses = $ticket->responses()
->with('user') ->with('user')

View File

@@ -2,13 +2,15 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use BackedEnum;
use UnitEnum;
use Illuminate\Support\Facades\DB;
use App\Filament\Resources\UserResource\Pages\CreateUser; use App\Filament\Resources\UserResource\Pages\CreateUser;
use App\Filament\Resources\UserResource\Pages\EditUser; use App\Filament\Resources\UserResource\Pages\EditUser;
use App\Filament\Resources\UserResource\Pages\ListUsers; use App\Filament\Resources\UserResource\Pages\ListUsers;
use App\Filament\Resources\UserResource\RelationManagers\LogsRelationManager; use App\Filament\Resources\UserResource\RelationManagers\LogsRelationManager;
use App\Filament\Resources\UserResource\RelationManagers\UsageLogsRelationManager; use App\Filament\Resources\UserResource\RelationManagers\UsageLogsRelationManager;
use App\Models\User; use App\Models\User;
use DB;
use Exception; use Exception;
use Filament\Actions\BulkAction; use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup; use Filament\Actions\BulkActionGroup;
@@ -31,9 +33,9 @@ class UserResource extends Resource
{ {
protected static ?string $model = User::class; protected static ?string $model = User::class;
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-users'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-users';
protected static string|\UnitEnum|null $navigationGroup = 'Admin'; protected static string|UnitEnum|null $navigationGroup = 'Admin';
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {
@@ -50,7 +52,7 @@ class UserResource extends Resource
TextInput::make('email_verified_at') TextInput::make('email_verified_at')
->label('Email Verification Status') ->label('Email Verification Status')
->disabled() ->disabled()
->formatStateUsing(fn ($record) => $record->email_verified_at ?? '' ->formatStateUsing(fn ($record): string => $record->email_verified_at ?? ''
? 'Verified at '.$record->email_verified_at->toDateTimeString() ? 'Verified at '.$record->email_verified_at->toDateTimeString()
: 'Not Verified') : 'Not Verified')
->helperText('Shows whether the user has verified their email address.'), ->helperText('Shows whether the user has verified their email address.'),
@@ -96,22 +98,20 @@ class UserResource extends Resource
->falseIcon('heroicon-o-x-circle') ->falseIcon('heroicon-o-x-circle')
->trueColor('success') ->trueColor('success')
->falseColor('danger') ->falseColor('danger')
->getStateUsing(fn ($record) => ! is_null($record->email_verified_at)) ->getStateUsing(fn ($record): bool => ! is_null($record->email_verified_at))
->sortable(), ->sortable(),
BadgeColumn::make('level') BadgeColumn::make('level')
->label('User Level') ->label('User Level')
->getStateUsing(function ($record) { ->getStateUsing(fn($record): string => match ($record->level) {
return match ($record->level) {
0 => 'Normal User', 0 => 'Normal User',
1 => 'Banned', 1 => 'Banned',
9 => 'Super Admin', 9 => 'Super Admin',
default => 'Unknown', // In case some invalid level exists default => 'Unknown', // In case some invalid level exists
};
}) })
->colors([ ->colors([
'success' => fn ($state) => $state === 'Normal User', 'success' => fn ($state): bool => $state === 'Normal User',
'danger' => fn ($state) => $state === 'Banned', 'danger' => fn ($state): bool => $state === 'Banned',
'warning' => fn ($state) => $state === 'Super Admin', 'warning' => fn ($state): bool => $state === 'Super Admin',
]) ])
->sortable(), ->sortable(),
TextColumn::make('stripe_id')->label('Stripe ID')->copyable(), TextColumn::make('stripe_id')->label('Stripe ID')->copyable(),
@@ -126,14 +126,14 @@ class UserResource extends Resource
'subscribed' => 'Has Active Subscription', 'subscribed' => 'Has Active Subscription',
'not_subscribed' => 'No Active Subscription', 'not_subscribed' => 'No Active Subscription',
]) ])
->query(function ($query, array $data) { ->query(function ($query, array $data): void {
if ($data['value'] === 'subscribed') { if ($data['value'] === 'subscribed') {
$query->whereHas('subscriptions', function ($query) { $query->whereHas('subscriptions', function ($query): void {
$query->where('stripe_status', 'active') $query->where('stripe_status', 'active')
->orWhere('stripe_status', 'trialing'); ->orWhere('stripe_status', 'trialing');
}); });
} elseif ($data['value'] === 'not_subscribed') { } elseif ($data['value'] === 'not_subscribed') {
$query->whereDoesntHave('subscriptions', function ($query) { $query->whereDoesntHave('subscriptions', function ($query): void {
$query->where('stripe_status', 'active') $query->where('stripe_status', 'active')
->orWhere('stripe_status', 'trialing'); ->orWhere('stripe_status', 'trialing');
}); });
@@ -145,7 +145,7 @@ class UserResource extends Resource
'verified' => 'Verified', 'verified' => 'Verified',
'not_verified' => 'Not Verified', 'not_verified' => 'Not Verified',
]) ])
->query(function ($query, array $data) { ->query(function ($query, array $data): void {
if ($data['value'] === 'verified') { if ($data['value'] === 'verified') {
$query->whereNotNull('email_verified_at'); $query->whereNotNull('email_verified_at');
} elseif ($data['value'] === 'not_verified') { } elseif ($data['value'] === 'not_verified') {
@@ -161,12 +161,10 @@ class UserResource extends Resource
DeleteBulkAction::make(), DeleteBulkAction::make(),
BulkAction::make('updateLevel') BulkAction::make('updateLevel')
->label('Update User Level') ->label('Update User Level')
->action(function (Collection $records, array $data) { ->action(function (Collection $records, array $data): void {
$newLevel = $data['new_level']; $newLevel = $data['new_level'];
if ($newLevel === 9) { throw_if($newLevel === 9, Exception::class, 'User level cannot be 9 or higher.');
throw new Exception('User level cannot be 9 or higher.');
}
DB::table('users') DB::table('users')
->whereIn('id', $records->pluck('id')) ->whereIn('id', $records->pluck('id'))

View File

@@ -75,7 +75,7 @@ class EditUser extends EditRecord
fclose($csv); fclose($csv);
return Response::streamDownload( return Response::streamDownload(
function () use ($csvContent) { function () use ($csvContent): void {
echo $csvContent; echo $csvContent;
}, },
"user_{$record->id}_report_".now()->format('Ymd_His').'.csv', "user_{$record->id}_report_".now()->format('Ymd_His').'.csv',

View File

@@ -4,7 +4,6 @@ namespace App\Filament\Resources\UserResource\RelationManagers;
use Filament\Actions\BulkActionGroup; use Filament\Actions\BulkActionGroup;
use Filament\Resources\RelationManagers\RelationManager; use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table; use Filament\Tables\Table;

View File

@@ -4,7 +4,6 @@ namespace App\Filament\Resources\UserResource\RelationManagers;
use Filament\Actions\BulkActionGroup; use Filament\Actions\BulkActionGroup;
use Filament\Resources\RelationManagers\RelationManager; use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table; use Filament\Tables\Table;

View File

@@ -2,13 +2,13 @@
namespace App\Filament\Widgets; namespace App\Filament\Widgets;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use App\Models\Log; use App\Models\Log;
use App\Models\Meta; use App\Models\Meta;
use App\Models\PremiumEmail; use App\Models\PremiumEmail;
use App\Models\Ticket; use App\Models\Ticket;
use App\Models\User; use App\Models\User;
use Carbon\Carbon;
use DB;
use Filament\Widgets\StatsOverviewWidget as BaseWidget; use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat; use Filament\Widgets\StatsOverviewWidget\Stat;
@@ -26,39 +26,39 @@ class StatsOverview extends BaseWidget
->descriptionIcon($this->getComparisonIcon($this->getCustomerCount(), $this->getCustomerCount('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getCustomerCount(), $this->getCustomerCount('yesterday')))
->color($this->getComparisonColor($this->getCustomerCount(), $this->getCustomerCount('yesterday'))), ->color($this->getComparisonColor($this->getCustomerCount(), $this->getCustomerCount('yesterday'))),
Stat::make('Paid Users', $this->getUserPaid()) Stat::make('Paid Users', $this->getUserPaid())
->description($this->getComparisonDescription($this->getUserPaid(), $this->getUserPaid('yesterday'))) ->description($this->getComparisonDescription($this->getUserPaid(), $this->getUserPaid()))
->descriptionIcon($this->getComparisonIcon($this->getUserPaid(), $this->getUserPaid('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getUserPaid(), $this->getUserPaid()))
->color($this->getComparisonColor($this->getUserPaid(), $this->getUserPaid('yesterday'))), ->color($this->getComparisonColor($this->getUserPaid(), $this->getUserPaid())),
Stat::make('Logs Count', $this->getLogsCount()) Stat::make('Logs Count', $this->getLogsCount())
->description($this->getComparisonDescription($this->getLogsCount(), $this->getLogsCount('yesterday'))) ->description($this->getComparisonDescription($this->getLogsCount(), $this->getLogsCount('yesterday')))
->descriptionIcon($this->getComparisonIcon($this->getLogsCount(), $this->getLogsCount('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getLogsCount(), $this->getLogsCount('yesterday')))
->color($this->getComparisonColor($this->getLogsCount(), $this->getLogsCount('yesterday'))), ->color($this->getComparisonColor($this->getLogsCount(), $this->getLogsCount('yesterday'))),
Stat::make('Total Mailbox', $this->getTotalMailbox()) Stat::make('Total Mailbox', $this->getTotalMailbox())
->description($this->getComparisonDescription($this->getTotalMailbox(), $this->getTotalMailbox('yesterday'))) ->description($this->getComparisonDescription($this->getTotalMailbox(), $this->getTotalMailbox()))
->descriptionIcon($this->getComparisonIcon($this->getTotalMailbox(), $this->getTotalMailbox('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getTotalMailbox(), $this->getTotalMailbox()))
->color($this->getComparisonColor($this->getTotalMailbox(), $this->getTotalMailbox('yesterday'))), ->color($this->getComparisonColor($this->getTotalMailbox(), $this->getTotalMailbox())),
Stat::make('Emails Received', $this->getTotalEmailsReceived()) Stat::make('Emails Received', $this->getTotalEmailsReceived())
->description($this->getComparisonDescription($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived('yesterday'))) ->description($this->getComparisonDescription($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived()))
->descriptionIcon($this->getComparisonIcon($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived()))
->color($this->getComparisonColor($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived('yesterday'))), ->color($this->getComparisonColor($this->getTotalEmailsReceived(), $this->getTotalEmailsReceived())),
Stat::make('Emails Stored', $this->getStoreEmailsCount()) Stat::make('Emails Stored', $this->getStoreEmailsCount())
->description($this->getComparisonDescription($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday'))) ->description($this->getComparisonDescription($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday')))
->descriptionIcon($this->getComparisonIcon($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday')))
->color($this->getComparisonColor($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday'))), ->color($this->getComparisonColor($this->getStoreEmailsCount(), $this->getStoreEmailsCount('yesterday'))),
Stat::make('Open Tickets', $this->getOpenTicketsCount()) Stat::make('Open Tickets', $this->getOpenTicketsCount())
->description($this->getComparisonDescription($this->getOpenTicketsCount(), $this->getOpenTicketsCount('yesterday'))) ->description($this->getComparisonDescription($this->getOpenTicketsCount(), $this->getOpenTicketsCount()))
->descriptionIcon($this->getComparisonIcon($this->getOpenTicketsCount(), $this->getOpenTicketsCount('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getOpenTicketsCount(), $this->getOpenTicketsCount()))
->color($this->getComparisonColor($this->getOpenTicketsCount(), $this->getOpenTicketsCount('yesterday'))), ->color($this->getComparisonColor($this->getOpenTicketsCount(), $this->getOpenTicketsCount())),
Stat::make('Closed Tickets', $this->getClosedTicketsCount()) Stat::make('Closed Tickets', $this->getClosedTicketsCount())
->description($this->getComparisonDescription($this->getClosedTicketsCount(), $this->getClosedTicketsCount('yesterday'))) ->description($this->getComparisonDescription($this->getClosedTicketsCount(), $this->getClosedTicketsCount()))
->descriptionIcon($this->getComparisonIcon($this->getClosedTicketsCount(), $this->getClosedTicketsCount('yesterday'))) ->descriptionIcon($this->getComparisonIcon($this->getClosedTicketsCount(), $this->getClosedTicketsCount()))
->color($this->getComparisonColor($this->getClosedTicketsCount(), $this->getClosedTicketsCount('yesterday'))), ->color($this->getComparisonColor($this->getClosedTicketsCount(), $this->getClosedTicketsCount())),
]; ];
} }
private function getComparisonDescription(int $today, int $yesterday): string private function getComparisonDescription(int $today, int $yesterday): string
{ {
if ($today == $yesterday) { if ($today === $yesterday) {
return 'No change'; return 'No change';
} }
@@ -76,7 +76,7 @@ class StatsOverview extends BaseWidget
private function getComparisonIcon(int $today, int $yesterday): ?string private function getComparisonIcon(int $today, int $yesterday): ?string
{ {
if ($today == $yesterday) { if ($today === $yesterday) {
return null; return null;
} }
@@ -85,7 +85,7 @@ class StatsOverview extends BaseWidget
private function getComparisonColor(int $today, int $yesterday): string private function getComparisonColor(int $today, int $yesterday): string
{ {
if ($today == $yesterday) { if ($today === $yesterday) {
return 'gray'; return 'gray';
} }
@@ -95,13 +95,13 @@ class StatsOverview extends BaseWidget
private function getUser(string $period = 'today'): int private function getUser(string $period = 'today'): int
{ {
if ($period === 'yesterday') { if ($period === 'yesterday') {
return User::where('created_at', '<', Carbon::today('UTC')->startOfDay())->count(); return User::query()->where('created_at', '<', Date::today('UTC')->startOfDay())->count();
} }
return User::count(); return User::query()->count();
} }
private function getUserPaid(string $period = 'today'): int private function getUserPaid(): int
{ {
return DB::table('subscriptions') return DB::table('subscriptions')
->where('stripe_status', 'active') ->where('stripe_status', 'active')
@@ -112,49 +112,49 @@ class StatsOverview extends BaseWidget
private function getLogsCount(string $period = 'today'): int private function getLogsCount(string $period = 'today'): int
{ {
if ($period === 'yesterday') { if ($period === 'yesterday') {
return Log::where('created_at', '<', Carbon::today('UTC')->startOfDay())->count(); return Log::query()->where('created_at', '<', Date::today('UTC')->startOfDay())->count();
} }
return Log::count(); return Log::query()->count();
} }
private function getTotalMailbox(string $period = 'today'): int private function getTotalMailbox(): int
{ {
return Meta::select('value')->where('key', 'email_ids_created')->first()->value ?? 0; return Meta::query()->select('value')->where('key', 'email_ids_created')->first()->value ?? 0;
} }
private function getTotalEmailsReceived(string $period = 'today'): int private function getTotalEmailsReceived(): int
{ {
return Meta::select('value')->where('key', 'messages_received')->first()->value ?? 0; return Meta::query()->select('value')->where('key', 'messages_received')->first()->value ?? 0;
} }
private function getCustomerCount(string $period = 'today'): int private function getCustomerCount(string $period = 'today'): int
{ {
if ($period === 'yesterday') { if ($period === 'yesterday') {
return User::whereNotNull('stripe_id') return User::query()->whereNotNull('stripe_id')
->where('created_at', '<', Carbon::today('UTC')->startOfDay()) ->where('created_at', '<', Date::today('UTC')->startOfDay())
->count(); ->count();
} }
return User::whereNotNull('stripe_id')->count(); return User::query()->whereNotNull('stripe_id')->count();
} }
private function getStoreEmailsCount(string $period = 'today'): int private function getStoreEmailsCount(string $period = 'today'): int
{ {
if ($period === 'yesterday') { if ($period === 'yesterday') {
return PremiumEmail::where('created_at', '<', Carbon::today('UTC')->startOfDay())->count(); return PremiumEmail::query()->where('created_at', '<', Date::today('UTC')->startOfDay())->count();
} }
return PremiumEmail::count(); return PremiumEmail::query()->count();
} }
private function getOpenTicketsCount(string $period = 'today'): int private function getOpenTicketsCount(): int
{ {
return Ticket::whereIn('status', ['open', 'pending'])->count(); return Ticket::query()->whereIn('status', ['open', 'pending'])->count();
} }
private function getClosedTicketsCount(string $period = 'today'): int private function getClosedTicketsCount(): int
{ {
return Ticket::whereIn('status', ['closed'])->count(); return Ticket::query()->whereIn('status', ['closed'])->count();
} }
} }

View File

@@ -2,9 +2,11 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Session;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Models\Premium; use App\Models\Premium;
use App\Models\ZEmail; use App\Models\ZEmail;
use Session;
class AppController extends Controller class AppController extends Controller
{ {
@@ -15,67 +17,66 @@ class AppController extends Controller
'email' => 'required|email', 'email' => 'required|email',
])->validate(); ])->validate();
if (json_decode(config('app.settings.configuration_settings'))->enable_create_from_url) { if (json_decode((string) config('app.settings.configuration_settings'))->enable_create_from_url) {
ZEmail::createCustomEmailFull($email); ZEmail::createCustomEmailFull($email);
} }
return redirect()->route('mailbox'); return to_route('mailbox');
} }
if (! ZEmail::getEmail()) { if (! ZEmail::getEmail()) {
return redirect()->route('home'); return to_route('home');
} }
if (json_decode(config('app.settings.configuration_settings'))->disable_mailbox_slug) { if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) {
return redirect()->route('home'); return to_route('home');
} }
return $this->app(); return $this->app();
} }
public function app() public function app(): Redirector|RedirectResponse
{ {
return redirect()->route('home'); return to_route('home');
} }
public function switch($email) public function switch($email): Redirector|RedirectResponse
{ {
ZEmail::setEmail($email); ZEmail::setEmail($email);
if (json_decode(config('app.settings.configuration_settings'))->disable_mailbox_slug) { if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) {
return redirect()->route('home'); return to_route('home');
} }
return redirect()->route('mailbox'); return to_route('mailbox');
} }
public function delete($email = null) public function delete($email = null): Redirector|RedirectResponse
{ {
if ($email) { if ($email) {
$emails = ZEmail::getEmails(); $emails = ZEmail::getEmails();
ZEmail::removeEmail($email); ZEmail::removeEmail($email);
return redirect()->route('mailbox'); return to_route('mailbox');
} else {
return redirect()->route('home');
} }
return to_route('home');
} }
public function switchP($email) public function switchP($email): Redirector|RedirectResponse
{ {
if (Session::get('isInboxTypePremium')) { if (\Illuminate\Support\Facades\Session::get('isInboxTypePremium')) {
Premium::setEmailP($email); Premium::setEmailP($email);
} else { } else {
ZEmail::setEmail($email); ZEmail::setEmail($email);
} }
if (json_decode(config('app.settings.configuration_settings'))->disable_mailbox_slug) { if (json_decode((string) config('app.settings.configuration_settings'))->disable_mailbox_slug) {
return redirect()->route('dashboard'); return to_route('dashboard');
} }
return redirect()->route('dashboard.premium'); return to_route('dashboard.premium');
} }
public function deleteP($email = null) public function deleteP($email = null): Redirector|RedirectResponse
{ {
if ($email) { if ($email) {
if (Session::get('isInboxTypePremium')) { if (\Illuminate\Support\Facades\Session::get('isInboxTypePremium')) {
$emails = Premium::getEmails(); $emails = Premium::getEmails();
Premium::removeEmail($email); Premium::removeEmail($email);
} else { } else {
@@ -83,10 +84,9 @@ class AppController extends Controller
ZEmail::removeEmail($email); ZEmail::removeEmail($email);
} }
return redirect()->route('dashboard.premium'); return to_route('dashboard.premium');
} else {
return redirect()->route('dashboard');
} }
return to_route('dashboard');
} }
public function locale($locale) public function locale($locale)
@@ -94,38 +94,8 @@ class AppController extends Controller
if (in_array($locale, config('app.locales'))) { if (in_array($locale, config('app.locales'))) {
session(['locale' => $locale]); session(['locale' => $locale]);
return redirect()->back(); return back();
} }
abort(400); abort(400);
} }
private function getStringBetween($string, $start, $end)
{
$string = ' '.$string;
$ini = strpos($string, $start);
if ($ini == 0) {
return '';
}
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
private function setHeaders($page)
{
$header = $page->header;
foreach ($page->meta ? unserialize($page->meta) : [] as $meta) {
if ($meta['name'] == 'canonical') {
$header .= '<link rel="canonical" href="'.$meta['content'].'" />';
} elseif (str_contains($meta['name'], 'og:')) {
$header .= '<meta property="'.$meta['name'].'" content="'.$meta['content'].'" />';
} else {
$header .= '<meta name="'.$meta['name'].'" content="'.$meta['content'].'" />';
}
}
$page->header = $header;
return $page;
}
} }

View File

@@ -2,17 +2,19 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Date;
use App\NotifyMe; use App\NotifyMe;
use Carbon\Carbon;
use Exception; use Exception;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Log;
class WebhookController extends Controller class WebhookController extends Controller
{ {
use NotifyMe; use NotifyMe;
public function oxapay(Request $request) public function oxapay(Request $request): ResponseFactory|Response
{ {
// Get the request data // Get the request data
$postData = $request->getContent(); $postData = $request->getContent();
@@ -32,7 +34,7 @@ class WebhookController extends Controller
// Validate HMAC signature // Validate HMAC signature
$hmacHeader = $request->header('HMAC'); $hmacHeader = $request->header('HMAC');
$calculatedHmac = hash_hmac('sha512', $postData, $apiSecretKey); $calculatedHmac = hash_hmac('sha512', $postData, (string) $apiSecretKey);
if (hash_equals($calculatedHmac, $hmacHeader)) { if (hash_equals($calculatedHmac, $hmacHeader)) {
// HMAC signature is valid // HMAC signature is valid
@@ -44,7 +46,7 @@ class WebhookController extends Controller
$currency = $data['currency'] ?? 'Unknown'; $currency = $data['currency'] ?? 'Unknown';
$trackId = $data['track_id'] ?? 'Unknown'; $trackId = $data['track_id'] ?? 'Unknown';
$orderId = $data['order_id'] ?? 'N/A'; $orderId = $data['order_id'] ?? 'N/A';
$date = isset($data['date']) ? Carbon::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString(); $date = isset($data['date']) ? Date::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString();
Log::info('Received Oxapay invoice payment callback', [ Log::info('Received Oxapay invoice payment callback', [
'track_id' => $trackId, 'track_id' => $trackId,
@@ -71,7 +73,7 @@ class WebhookController extends Controller
$address = $data['address'] ?? 'Unknown'; $address = $data['address'] ?? 'Unknown';
$txHash = $data['tx_hash'] ?? 'Unknown'; $txHash = $data['tx_hash'] ?? 'Unknown';
$description = $data['description'] ?? 'N/A'; $description = $data['description'] ?? 'N/A';
$date = isset($data['date']) ? Carbon::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString(); $date = isset($data['date']) ? Date::createFromTimestamp($data['date'])->toDateTimeString() : now()->toDateTimeString();
Log::info('Received Oxapay payout callback', [ Log::info('Received Oxapay payout callback', [
'track_id' => $trackId, 'track_id' => $trackId,

View File

@@ -32,9 +32,7 @@ class CheckPageSlug
return response()->file($publicPath); return response()->file($publicPath);
} }
if (is_dir($publicPath)) { abort_if(is_dir($publicPath), 404);
abort(404);
}
return $next($request); return $next($request);
} }

View File

@@ -2,7 +2,7 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use Auth; use Illuminate\Support\Facades\Auth;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;

View File

@@ -17,11 +17,11 @@ class Locale
public function handle(Request $request, Closure $next): Response public function handle(Request $request, Closure $next): Response
{ {
try { try {
$locale = explode('-', explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0])[0]; $locale = explode('-', explode(',', (string) \Illuminate\Support\Facades\Request::server('HTTP_ACCEPT_LANGUAGE'))[0])[0];
if (in_array($locale, config('app.locales'))) { if (in_array($locale, config('app.locales'))) {
session(['browser-locale' => $locale]); session(['browser-locale' => $locale]);
} }
} catch (Exception $e) { } catch (Exception) {
} }
app()->setLocale(session('locale', session('browser-locale', config('app.settings.language', config('app.locale', 'en'))))); app()->setLocale(session('locale', session('browser-locale', config('app.settings.language', config('app.locale', 'en')))));

View File

@@ -2,6 +2,8 @@
namespace App\Livewire\Actions; namespace App\Livewire\Actions;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Session;
@@ -10,7 +12,7 @@ class Logout
/** /**
* Log the current user out of the application. * Log the current user out of the application.
*/ */
public function __invoke() public function __invoke(): Redirector|RedirectResponse
{ {
Auth::guard('web')->logout(); Auth::guard('web')->logout();

View File

@@ -2,9 +2,11 @@
namespace App\Livewire; namespace App\Livewire;
use Illuminate\Support\Facades\Session;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use App\Models\ZEmail; use App\Models\ZEmail;
use Livewire\Component; use Livewire\Component;
use Session;
class AddOn extends Component class AddOn extends Component
{ {
@@ -27,11 +29,12 @@ class AddOn extends Component
$email = ZEmail::getEmail(); $email = ZEmail::getEmail();
$messages = ZEmail::getMessages($email); $messages = ZEmail::getMessages($email);
if (count($messages['data']) > 0) { if (count($messages['data']) > 0) {
return redirect()->route('mailbox'); return to_route('mailbox');
} }
return null;
} }
public function mount() public function mount(): void
{ {
$this->faqs = json_decode(file_get_contents(public_path('addOnFAQs.json')), true) ?? []; $this->faqs = json_decode(file_get_contents(public_path('addOnFAQs.json')), true) ?? [];
$route = request()->route()->getName(); $route = request()->route()->getName();
@@ -45,16 +48,14 @@ class AddOn extends Component
$this->faqSchema = [ $this->faqSchema = [
'@context' => 'https://schema.org', '@context' => 'https://schema.org',
'@type' => 'FAQPage', '@type' => 'FAQPage',
'mainEntity' => collect($this->faqs)->map(function ($faq) { 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [
return [
'@type' => 'Question', '@type' => 'Question',
'name' => $faq['title'], 'name' => $faq['title'],
'acceptedAnswer' => [ 'acceptedAnswer' => [
'@type' => 'Answer', '@type' => 'Answer',
'text' => $faq['content'], 'text' => $faq['content'],
], ],
]; ])->all(),
})->toArray(),
]; ];
} elseif ($route == 'disposable-gmail') { } elseif ($route == 'disposable-gmail') {
$this->title = 'Disposable Gmail Email | Free Temporary Gmail Inbox Online'; $this->title = 'Disposable Gmail Email | Free Temporary Gmail Inbox Online';
@@ -65,16 +66,14 @@ class AddOn extends Component
$this->faqSchema = [ $this->faqSchema = [
'@context' => 'https://schema.org', '@context' => 'https://schema.org',
'@type' => 'FAQPage', '@type' => 'FAQPage',
'mainEntity' => collect($this->faqs)->map(function ($faq) { 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [
return [
'@type' => 'Question', '@type' => 'Question',
'name' => $faq['title'], 'name' => $faq['title'],
'acceptedAnswer' => [ 'acceptedAnswer' => [
'@type' => 'Answer', '@type' => 'Answer',
'text' => $faq['content'], 'text' => $faq['content'],
], ],
]; ])->all(),
})->toArray(),
]; ];
} elseif ($route == 'disposable-outlook') { } elseif ($route == 'disposable-outlook') {
@@ -86,16 +85,14 @@ class AddOn extends Component
$this->faqSchema = [ $this->faqSchema = [
'@context' => 'https://schema.org', '@context' => 'https://schema.org',
'@type' => 'FAQPage', '@type' => 'FAQPage',
'mainEntity' => collect($this->faqs)->map(function ($faq) { 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [
return [
'@type' => 'Question', '@type' => 'Question',
'name' => $faq['title'], 'name' => $faq['title'],
'acceptedAnswer' => [ 'acceptedAnswer' => [
'@type' => 'Answer', '@type' => 'Answer',
'text' => $faq['content'], 'text' => $faq['content'],
], ],
]; ])->all(),
})->toArray(),
]; ];
} elseif ($route == 'disposable-yahoo') { } elseif ($route == 'disposable-yahoo') {
$this->title = 'Disposable Yahoo Mail | Free Temporary Yahoo Inbox'; $this->title = 'Disposable Yahoo Mail | Free Temporary Yahoo Inbox';
@@ -106,16 +103,14 @@ class AddOn extends Component
$this->faqSchema = [ $this->faqSchema = [
'@context' => 'https://schema.org', '@context' => 'https://schema.org',
'@type' => 'FAQPage', '@type' => 'FAQPage',
'mainEntity' => collect($this->faqs)->map(function ($faq) { 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [
return [
'@type' => 'Question', '@type' => 'Question',
'name' => $faq['title'], 'name' => $faq['title'],
'acceptedAnswer' => [ 'acceptedAnswer' => [
'@type' => 'Answer', '@type' => 'Answer',
'text' => $faq['content'], 'text' => $faq['content'],
], ],
]; ])->all(),
})->toArray(),
]; ];
} elseif ($route == 'gmailnator') { } elseif ($route == 'gmailnator') {
$this->title = 'Gmailnator - Free Temporary Gmail Email Address Generator'; $this->title = 'Gmailnator - Free Temporary Gmail Email Address Generator';
@@ -126,16 +121,14 @@ class AddOn extends Component
$this->faqSchema = [ $this->faqSchema = [
'@context' => 'https://schema.org', '@context' => 'https://schema.org',
'@type' => 'FAQPage', '@type' => 'FAQPage',
'mainEntity' => collect($this->faqs)->map(function ($faq) { 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [
return [
'@type' => 'Question', '@type' => 'Question',
'name' => $faq['title'], 'name' => $faq['title'],
'acceptedAnswer' => [ 'acceptedAnswer' => [
'@type' => 'Answer', '@type' => 'Answer',
'text' => $faq['content'], 'text' => $faq['content'],
], ],
]; ])->all(),
})->toArray(),
]; ];
} elseif ($route == 'emailnator') { } elseif ($route == 'emailnator') {
$this->title = 'Emailnator - Free Disposable Temporary Email Service'; $this->title = 'Emailnator - Free Disposable Temporary Email Service';
@@ -146,16 +139,14 @@ class AddOn extends Component
$this->faqSchema = [ $this->faqSchema = [
'@context' => 'https://schema.org', '@context' => 'https://schema.org',
'@type' => 'FAQPage', '@type' => 'FAQPage',
'mainEntity' => collect($this->faqs)->map(function ($faq) { 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [
return [
'@type' => 'Question', '@type' => 'Question',
'name' => $faq['title'], 'name' => $faq['title'],
'acceptedAnswer' => [ 'acceptedAnswer' => [
'@type' => 'Answer', '@type' => 'Answer',
'text' => $faq['content'], 'text' => $faq['content'],
], ],
]; ])->all(),
})->toArray(),
]; ];
} elseif ($route == 'temp-gmail') { } elseif ($route == 'temp-gmail') {
$this->title = 'Temp Gmail | Free Temporary Gmail Inbox for Instant Use'; $this->title = 'Temp Gmail | Free Temporary Gmail Inbox for Instant Use';
@@ -166,22 +157,20 @@ class AddOn extends Component
$this->faqSchema = [ $this->faqSchema = [
'@context' => 'https://schema.org', '@context' => 'https://schema.org',
'@type' => 'FAQPage', '@type' => 'FAQPage',
'mainEntity' => collect($this->faqs)->map(function ($faq) { 'mainEntity' => collect($this->faqs)->map(fn(array $faq): array => [
return [
'@type' => 'Question', '@type' => 'Question',
'name' => $faq['title'], 'name' => $faq['title'],
'acceptedAnswer' => [ 'acceptedAnswer' => [
'@type' => 'Answer', '@type' => 'Answer',
'text' => $faq['content'], 'text' => $faq['content'],
], ],
]; ])->all(),
})->toArray(),
]; ];
} }
} }
public function render() public function render(): Factory|View
{ {
return view('livewire.add-on'); return view('livewire.add-on');
} }

View File

@@ -34,7 +34,7 @@ class Register extends Component
$validated['password'] = Hash::make($validated['password']); $validated['password'] = Hash::make($validated['password']);
event(new Registered(($user = User::create($validated)))); event(new Registered(($user = User::query()->create($validated))));
Auth::login($user); Auth::login($user);

View File

@@ -50,7 +50,7 @@ class ResetPassword extends Component
// database. Otherwise we will parse the error and return the response. // database. Otherwise we will parse the error and return the response.
$status = Password::reset( $status = Password::reset(
$this->only('email', 'password', 'password_confirmation', 'token'), $this->only('email', 'password', 'password_confirmation', 'token'),
function ($user) { function ($user): void {
$user->forceFill([ $user->forceFill([
'password' => Hash::make($this->password), 'password' => Hash::make($this->password),
'remember_token' => Str::random(60), 'remember_token' => Str::random(60),

View File

@@ -11,10 +11,10 @@ class Blog extends Component
public $category; public $category;
public function mount($slug) public function mount($slug): void
{ {
$this->postDetail = \App\Models\Blog::where('slug', $slug)->firstOrFail(); $this->postDetail = \App\Models\Blog::query()->where('slug', $slug)->firstOrFail();
$this->category = Category::where('id', $this->postDetail->category_id)->first(); $this->category = Category::query()->where('id', $this->postDetail->category_id)->first();
} }
public function render() public function render()

View File

@@ -2,8 +2,8 @@
namespace App\Livewire\Dashboard; namespace App\Livewire\Dashboard;
use Illuminate\Support\Facades\Session;
use Livewire\Component; use Livewire\Component;
use Session;
class Bulk extends Component class Bulk extends Component
{ {
@@ -11,15 +11,13 @@ class Bulk extends Component
public $bulkCount = 1; public $bulkCount = 1;
private $isSubscribed = false; public function mount(): void
public function mount()
{ {
$subscriptionCheck = auth()->user()->subscribedToProduct(config('app.plans')[0]['product_id']); $subscriptionCheck = auth()->user()->subscribedToProduct(config('app.plans')[0]['product_id']);
Session::put('isSubscribed', $subscriptionCheck); Session::put('isSubscribed', $subscriptionCheck);
} }
public function generateBulk() public function generateBulk(): void
{ {
$this->validate([ $this->validate([
'bulkCount' => 'required|integer|min:1|max:500', 'bulkCount' => 'required|integer|min:1|max:500',
@@ -44,7 +42,7 @@ class Bulk extends Component
$filename = 'bulk_emails_'.now()->format('Ymd_His').'.txt'; $filename = 'bulk_emails_'.now()->format('Ymd_His').'.txt';
$content = implode(PHP_EOL, $this->bulkEmails); $content = implode(PHP_EOL, $this->bulkEmails);
return response()->streamDownload(function () use ($content) { return response()->streamDownload(function () use ($content): void {
echo $content; echo $content;
}, $filename); }, $filename);
} }
@@ -54,11 +52,11 @@ class Bulk extends Component
$domain = $this->getRandomDomain(); $domain = $this->getRandomDomain();
if ($domain == 'gmail.com' || $domain == 'googlemail.com') { if ($domain == 'gmail.com' || $domain == 'googlemail.com') {
$uname = $this->getRandomGmailUser(); $uname = $this->getRandomGmailUser();
$uname_len = strlen($uname); $uname_len = strlen((string) $uname);
$len_power = $uname_len - 1; $len_power = $uname_len - 1;
$combination = pow(2, $len_power); $combination = 2 ** $len_power;
$rand_comb = mt_rand(1, $combination); $rand_comb = mt_rand(1, $combination);
$formatted = implode(' ', str_split($uname)); $formatted = implode(' ', str_split((string) $uname));
$uname_exp = explode(' ', $formatted); $uname_exp = explode(' ', $formatted);
$bin = intval(''); $bin = intval('');
@@ -70,7 +68,7 @@ class Bulk extends Component
$email = ''; $email = '';
for ($i = 0; $i < $len_power; $i++) { for ($i = 0; $i < $len_power; $i++) {
$email .= $uname_exp[$i]; $email .= $uname_exp[$i];
if ($bin[$i]) { if ($bin[$i] !== '' && $bin[$i] !== '0') {
$email .= '.'; $email .= '.';
} }
} }
@@ -83,15 +81,14 @@ class Bulk extends Component
} }
return $email; return $email;
} else {
return $this->generateRandomUsername().'@'.$domain;
} }
return $this->generateRandomUsername().'@'.$domain;
} }
private function generateRandomUsername(): string private function generateRandomUsername(): string
{ {
$start = json_decode(config('app.settings.configuration_settings'))->random_username_length_min ?? 0; $start = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_min ?? 0;
$end = json_decode(config('app.settings.configuration_settings'))->random_username_length_max ?? 0; $end = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_max ?? 0;
if ($start == 0 && $end == 0) { if ($start == 0 && $end == 0) {
return $this->generatePronounceableWord(); return $this->generatePronounceableWord();
} }
@@ -101,25 +98,25 @@ class Bulk extends Component
private function generatedRandomBetweenLength($start, $end): string private function generatedRandomBetweenLength($start, $end): string
{ {
$length = rand($start, $end); $length = random_int($start, $end);
return $this->generateRandomString($length); return $this->generateRandomString($length);
} }
private function getRandomDomain() private function getRandomDomain()
{ {
$domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
$count = count($domains); $count = count($domains);
return $count > 0 ? $domains[rand(1, $count) - 1] : ''; return $count > 0 ? $domains[random_int(1, $count) - 1] : '';
} }
private function getRandomGmailUser() private function getRandomGmailUser()
{ {
$gmailusername = json_decode(config('app.settings.configuration_settings'))->premium_gmailUsernames ?? []; $gmailusername = json_decode((string) config('app.settings.configuration_settings'))->premium_gmailUsernames ?? [];
$count = count($gmailusername); $count = count($gmailusername);
return $count > 0 ? $gmailusername[rand(1, $count) - 1] : ''; return $count > 0 ? $gmailusername[random_int(1, $count) - 1] : '';
} }
private function generatePronounceableWord(): string private function generatePronounceableWord(): string
@@ -129,21 +126,21 @@ class Bulk extends Component
$a = $c.$v; // both $a = $c.$v; // both
$random = ''; $random = '';
for ($j = 0; $j < 2; $j++) { for ($j = 0; $j < 2; $j++) {
$random .= $c[rand(0, strlen($c) - 1)]; $random .= $c[random_int(0, strlen($c) - 1)];
$random .= $v[rand(0, strlen($v) - 1)]; $random .= $v[random_int(0, strlen($v) - 1)];
$random .= $a[rand(0, strlen($a) - 1)]; $random .= $a[random_int(0, strlen($a) - 1)];
} }
return $random; return $random;
} }
private function generateRandomString($length = 10): string private function generateRandomString(int $length = 10): string
{ {
$characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters); $charactersLength = strlen($characters);
$randomString = ''; $randomString = '';
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)]; $randomString .= $characters[random_int(0, $charactersLength - 1)];
} }
return $randomString; return $randomString;
@@ -153,8 +150,7 @@ class Bulk extends Component
{ {
if (Session::get('isSubscribed')) { if (Session::get('isSubscribed')) {
return view('livewire.dashboard.bulk')->layout('components.layouts.dashboard'); return view('livewire.dashboard.bulk')->layout('components.layouts.dashboard');
} else { }
return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard');
} }
} }
}

View File

@@ -2,8 +2,8 @@
namespace App\Livewire\Dashboard; namespace App\Livewire\Dashboard;
use Illuminate\Support\Facades\Session;
use Livewire\Component; use Livewire\Component;
use Session;
class BulkGmail extends Component class BulkGmail extends Component
{ {
@@ -13,7 +13,7 @@ class BulkGmail extends Component
public $bulkEmails = []; public $bulkEmails = [];
public function mount() public function mount(): void
{ {
$subscriptionCheck = auth()->user()->subscribedToProduct(config('app.plans')[0]['product_id']); $subscriptionCheck = auth()->user()->subscribedToProduct(config('app.plans')[0]['product_id']);
Session::put('isSubscribed', $subscriptionCheck); Session::put('isSubscribed', $subscriptionCheck);
@@ -34,7 +34,7 @@ class BulkGmail extends Component
$this->bulkEmails = []; $this->bulkEmails = [];
} }
$this->bulkEmails = $this->generateDotVariants(explode('@', $this->email)[0], $this->quantity); $this->bulkEmails = $this->generateDotVariants(explode('@', (string) $this->email)[0], $this->quantity);
} }
public function downloadBulk() public function downloadBulk()
@@ -47,12 +47,15 @@ class BulkGmail extends Component
$filename = 'bulk_gmails_'.now()->format('Ymd_His').'.txt'; $filename = 'bulk_gmails_'.now()->format('Ymd_His').'.txt';
$content = implode(PHP_EOL, $this->bulkEmails); $content = implode(PHP_EOL, $this->bulkEmails);
return response()->streamDownload(function () use ($content) { return response()->streamDownload(function () use ($content): void {
echo $content; echo $content;
}, $filename); }, $filename);
} }
private function generateDotVariants($uname, $quantity) /**
* @return string[]
*/
private function generateDotVariants(string $uname, int $quantity): array
{ {
$length = strlen($uname); $length = strlen($uname);
$positions = range(1, $length - 1); $positions = range(1, $length - 1);
@@ -89,7 +92,7 @@ class BulkGmail extends Component
return [[]]; return [[]];
} }
if (empty($items)) { if ($items === []) {
return []; return [];
} }
@@ -102,19 +105,14 @@ class BulkGmail extends Component
$combinations[] = $c; $combinations[] = $c;
} }
foreach ($this->combinations($tail, $size) as $c) { return $this->combinations($tail, $size);
$combinations[] = $c;
}
return $combinations;
} }
public function render() public function render()
{ {
if (Session::get('isSubscribed')) { if (Session::get('isSubscribed')) {
return view('livewire.dashboard.bulk-gmail')->layout('components.layouts.dashboard'); return view('livewire.dashboard.bulk-gmail')->layout('components.layouts.dashboard');
} else { }
return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard');
} }
} }
}

View File

@@ -2,14 +2,14 @@
namespace App\Livewire\Dashboard; namespace App\Livewire\Dashboard;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\UsageLog; use App\Models\UsageLog;
use Cache;
use Carbon\Carbon;
use DB;
use Exception; use Exception;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Livewire\Component; use Livewire\Component;
use Log;
use Stripe\StripeClient; use Stripe\StripeClient;
class Dashboard extends Component class Dashboard extends Component
@@ -27,13 +27,13 @@ class Dashboard extends Component
public function paymentStatus(Request $request) public function paymentStatus(Request $request)
{ {
$status = $request->route('status'); $status = $request->route('status');
$currentUrl = $request->fullUrl(); $request->fullUrl();
if ($status == 'success') { if ($status == 'success') {
$this->syncSubscription(); $this->syncSubscription();
return to_route('dashboard')->with('status', 'success');
return redirect()->route('dashboard')->with('status', 'success'); }
} elseif ($status == 'cancel') { if ($status == 'cancel') {
return redirect()->route('dashboard')->with('status', 'cancel'); return to_route('dashboard')->with('status', 'cancel');
} }
} }
@@ -63,25 +63,23 @@ class Dashboard extends Component
$canceled_at = $subscriptionData->canceled_at; $canceled_at = $subscriptionData->canceled_at;
$status = $subscriptionData->status; $status = $subscriptionData->status;
if ($cancel_at_period_end) { if ($cancel_at_period_end) {
$final_ends_at = Carbon::createFromTimestamp($cancel_at)->toDateTimeString(); $final_ends_at = Date::createFromTimestamp($cancel_at)->toDateTimeString();
} else { } elseif ($cancel_at === null && $canceled_at !== null && $status === 'canceled' && $cancel_at_period_end === false) {
if ($cancel_at === null && $canceled_at !== null && $status === 'canceled' && $cancel_at_period_end === false) {
// $final_ends_at = Carbon::createFromTimestamp($canceled_at)->toDateTimeString(); // $final_ends_at = Carbon::createFromTimestamp($canceled_at)->toDateTimeString();
$final_ends_at = Carbon::now()->subDays(2)->toDateTimeString(); $final_ends_at = Date::now()->subDays(2)->toDateTimeString();
$redirect = true; $redirect = true;
} elseif ($status === 'active' && $cancel_at !== null) { } elseif ($status === 'active' && $cancel_at !== null) {
$final_ends_at = Carbon::createFromTimestamp($cancel_at)->toDateTimeString(); $final_ends_at = Date::createFromTimestamp($cancel_at)->toDateTimeString();
} else { } else {
$final_ends_at = null; $final_ends_at = null;
} }
}
DB::table('subscriptions') DB::table('subscriptions')
->where('stripe_id', $subscriptionId) ->where('stripe_id', $subscriptionId)
->update([ ->update([
'stripe_status' => $status, 'stripe_status' => $status,
'ends_at' => $final_ends_at, 'ends_at' => $final_ends_at,
'updated_at' => Carbon::now()->toDateTimeString(), 'updated_at' => Date::now()->toDateTimeString(),
]); ]);
} }
} }
@@ -117,11 +115,7 @@ class Dashboard extends Component
$stripe_product = $items->price->product; $stripe_product = $items->price->product;
$ends_at = $items->current_period_end; $ends_at = $items->current_period_end;
$subscriptionItemId = $items->id; $subscriptionItemId = $items->id;
if ($cancel_at_period_end) { $final_ends_at = $cancel_at_period_end ? Date::createFromTimestamp($ends_at)->toDateTimeString() : null;
$final_ends_at = Carbon::createFromTimestamp($ends_at)->toDateTimeString();
} else {
$final_ends_at = null;
}
try { try {
if ($status === 'active') { if ($status === 'active') {
@@ -135,8 +129,8 @@ class Dashboard extends Component
'stripe_price' => $stripe_price, 'stripe_price' => $stripe_price,
'quantity' => $quantity, 'quantity' => $quantity,
'ends_at' => $final_ends_at, 'ends_at' => $final_ends_at,
'created_at' => Carbon::now()->toDateTimeString(), 'created_at' => Date::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString(), 'updated_at' => Date::now()->toDateTimeString(),
]); ]);
$subscriptionsTable = DB::table('subscriptions')->where(['stripe_id' => $subscriptionId])->first(); $subscriptionsTable = DB::table('subscriptions')->where(['stripe_id' => $subscriptionId])->first();
@@ -149,8 +143,8 @@ class Dashboard extends Component
'stripe_product' => $stripe_product, 'stripe_product' => $stripe_product,
'stripe_price' => $stripe_price, 'stripe_price' => $stripe_price,
'quantity' => $quantity, 'quantity' => $quantity,
'created_at' => Carbon::now()->toDateTimeString(), 'created_at' => Date::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString(), 'updated_at' => Date::now()->toDateTimeString(),
]); ]);
} }
} }
@@ -165,7 +159,7 @@ class Dashboard extends Component
public function mount(Request $request) public function mount(Request $request)
{ {
if ($this->checkForSubscriptionStatus()) { if ($this->checkForSubscriptionStatus()) {
return redirect()->route('dashboard'); return to_route('dashboard');
} }
try { try {
$status = $request->session()->get('status'); $status = $request->session()->get('status');
@@ -177,7 +171,7 @@ class Dashboard extends Component
} }
$request->session()->forget('status'); $request->session()->forget('status');
} }
} catch (Exception $exception) { } catch (Exception) {
} }
@@ -207,7 +201,7 @@ class Dashboard extends Component
} }
} }
$usageLog = UsageLog::where('user_id', auth()->user()->id)->first(); $usageLog = UsageLog::query()->where('user_id', auth()->user()->id)->first();
$this->usageLog = [ $this->usageLog = [
'emails_created_count' => $usageLog->emails_created_count ?? 0, 'emails_created_count' => $usageLog->emails_created_count ?? 0,
'emails_received_count' => $usageLog->emails_received_count ?? 0, 'emails_received_count' => $usageLog->emails_received_count ?? 0,

View File

@@ -2,17 +2,19 @@
namespace App\Livewire\Dashboard\Mailbox; namespace App\Livewire\Dashboard\Mailbox;
use Illuminate\Support\Facades\Session;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Date;
use App\ColorPicker; use App\ColorPicker;
use App\Models\Log; use App\Models\Log;
use App\Models\Premium; use App\Models\Premium;
use App\Models\PremiumEmail; use App\Models\PremiumEmail;
use App\Models\UsageLog; use App\Models\UsageLog;
use App\Models\ZEmail; use App\Models\ZEmail;
use Carbon\Carbon;
use Exception; use Exception;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Livewire\Component; use Livewire\Component;
use Session;
class Inbox extends Component class Inbox extends Component
{ {
@@ -63,14 +65,14 @@ class Inbox extends Component
$this->premium = Session::get('isInboxTypePremium', true); $this->premium = Session::get('isInboxTypePremium', true);
if ($this->premium) { if ($this->premium) {
$this->domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; $this->domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
$this->email = Premium::getEmail(); $this->email = Premium::getEmail();
$this->emails = Premium::getEmails(); $this->emails = Premium::getEmails();
$this->initial = false; $this->initial = false;
$this->checkMultipleEmails(); $this->checkMultipleEmails();
$this->validateDomainInEmail(); $this->validateDomainInEmail();
} else { } else {
$this->domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
$this->email = ZEmail::getEmail(); $this->email = ZEmail::getEmail();
$this->emails = ZEmail::getEmails(); $this->emails = ZEmail::getEmails();
$this->initial = false; $this->initial = false;
@@ -97,12 +99,12 @@ class Inbox extends Component
$this->email_limit = $mailboxLimit; $this->email_limit = $mailboxLimit;
} catch (Exception $e) { } catch (Exception $e) {
\Log::error($e->getMessage()); \Illuminate\Support\Facades\Log::error($e->getMessage());
} }
} }
if ($this->premium) { if ($this->premium) {
$mailboxHistory = UsageLog::where(['user_id' => auth()->user()->id])->first(); $mailboxHistory = UsageLog::query()->where(['user_id' => auth()->user()->id])->first();
$this->mailboxHistory = $mailboxHistory->emails_created_history ?? []; $this->mailboxHistory = $mailboxHistory->emails_created_history ?? [];
} else { } else {
$this->mailboxHistory = ZEmail::getEmails() ?? []; $this->mailboxHistory = ZEmail::getEmails() ?? [];
@@ -112,27 +114,23 @@ class Inbox extends Component
private function checkMultipleEmails(): void private function checkMultipleEmails(): void
{ {
if (count($this->emails) == 0) { if (count($this->emails) === 0) {
$this->emails = [$this->email]; $this->emails = [$this->email];
} }
if (count($this->emails) > 1) { $this->list = count($this->emails) > 1;
$this->list = true;
} else {
$this->list = false;
}
} }
public function switchEmail($email) public function switchEmail($email)
{ {
try { try {
if ($email != null) { if ($email != null) {
$data = explode('@', $email); $data = explode('@', (string) $email);
if (isset($data[1])) { if (isset($data[1])) {
$domain = $data[1]; $domain = $data[1];
if ($this->premium) { if ($this->premium) {
$domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
} else { } else {
$domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
} }
if (! in_array($domain, $domains)) { if (! in_array($domain, $domains)) {
return $this->showAlert('error', __('This mailbox can not be recovered.')); return $this->showAlert('error', __('This mailbox can not be recovered.'));
@@ -140,17 +138,17 @@ class Inbox extends Component
} }
} }
} catch (Exception $exception) { } catch (Exception $exception) {
\Log::error($exception->getMessage()); \Illuminate\Support\Facades\Log::error($exception->getMessage());
} }
return redirect()->route('switchP', ['email' => $email]); return to_route('switchP', ['email' => $email]);
} }
public function syncEmail(): void public function syncEmail(): void
{ {
$this->email = Premium::getEmail(); $this->email = Premium::getEmail();
$this->emails = Premium::getEmails(); $this->emails = Premium::getEmails();
if (count($this->emails) == 0) { if (count($this->emails) === 0) {
$this->dispatch('getEmail'); $this->dispatch('getEmail');
} }
$this->checkMultipleEmails(); $this->checkMultipleEmails();
@@ -174,13 +172,13 @@ class Inbox extends Component
return $this->showAlert('error', __('Please enter Username')); return $this->showAlert('error', __('Please enter Username'));
} }
$this->checkDomainInUsername(); $this->checkDomainInUsername();
if (strlen($this->username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($this->username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { if (strlen((string) $this->username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen((string) $this->username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) {
return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_max); return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max);
} }
if (! $this->domain) { if (! $this->domain) {
return $this->showAlert('error', __('Please Select a Domain')); return $this->showAlert('error', __('Please Select a Domain'));
} }
if (in_array($this->username, json_decode(config('app.settings.configuration_settings'))->forbidden_ids)) { if (in_array($this->username, json_decode((string) config('app.settings.configuration_settings'))->forbidden_ids)) {
return $this->showAlert('error', __('Username not allowed')); return $this->showAlert('error', __('Username not allowed'));
} }
if (! $this->checkEmailLimit()) { if (! $this->checkEmailLimit()) {
@@ -195,7 +193,7 @@ class Inbox extends Component
$this->email = ZEmail::createCustomEmail($this->username, $this->domain); $this->email = ZEmail::createCustomEmail($this->username, $this->domain);
} }
return redirect()->route('dashboard.premium'); return to_route('dashboard.premium');
} }
@@ -205,13 +203,9 @@ class Inbox extends Component
if (! $this->checkEmailLimit()) { if (! $this->checkEmailLimit()) {
return $this->showAlert('error', __('You have reached daily limit of maximum ').$this->email_limit.__(' temp mail addresses.')); return $this->showAlert('error', __('You have reached daily limit of maximum ').$this->email_limit.__(' temp mail addresses.'));
} }
if ($this->premium) { $this->email = $this->premium ? Premium::generateRandomEmail() : ZEmail::generateRandomEmail();
$this->email = Premium::generateRandomEmail();
} else {
$this->email = ZEmail::generateRandomEmail();
}
return redirect()->route('dashboard.premium'); return to_route('dashboard.premium');
} }
public function gmail() public function gmail()
@@ -219,13 +213,9 @@ class Inbox extends Component
if (! $this->checkEmailLimit()) { if (! $this->checkEmailLimit()) {
return $this->showAlert('error', __('You have reached daily limit of maximum ').$this->email_limit.__(' temp mail addresses.')); return $this->showAlert('error', __('You have reached daily limit of maximum ').$this->email_limit.__(' temp mail addresses.'));
} }
if ($this->premium) { $this->email = $this->premium ? Premium::generateRandomGmail() : ZEmail::generateRandomGmail();
$this->email = Premium::generateRandomGmail();
} else {
$this->email = ZEmail::generateRandomGmail();
}
return redirect()->route('dashboard.premium'); return to_route('dashboard.premium');
} }
public function outlook() public function outlook()
@@ -239,38 +229,30 @@ class Inbox extends Component
$this->email = ZEmail::generateRandomOutlook(); $this->email = ZEmail::generateRandomOutlook();
} }
return redirect()->route('dashboard.premium'); return to_route('dashboard.premium');
} }
public function deleteEmail() public function deleteEmail(): Redirector|RedirectResponse
{ {
return redirect()->route('deleteP', ['email' => $this->email]); return to_route('deleteP', ['email' => $this->email]);
} }
private function showAlert($type, $message): void private function showAlert(string $type, $message): void
{ {
$this->dispatch('showAlert', ['type' => $type, 'message' => $message]); $this->dispatch('showAlert', ['type' => $type, 'message' => $message]);
} }
private function checkEmailLimit(): bool private function checkEmailLimit(): bool
{ {
$logs = Log::select('ip', 'email')->where('user_id', auth()->user()->id)->where('created_at', '>', Carbon::now()->subDay())->groupBy('email')->groupBy('ip')->get(); $logs = Log::query()->select('ip', 'email')->where('user_id', auth()->user()->id)->where('created_at', '>', Date::now()->subDay())->groupBy('email')->groupBy('ip')->get();
if (count($logs) >= $this->email_limit) { return count($logs) < $this->email_limit;
return false;
}
return true;
} }
private function checkUsedEmail(): bool private function checkUsedEmail(): bool
{ {
if (json_decode(config('app.settings.configuration_settings'))->disable_used_email) { if (json_decode((string) config('app.settings.configuration_settings'))->disable_used_email) {
$check = Log::where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count(); $check = Log::query()->where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count();
if ($check > 0) { return $check <= 0;
return false;
}
return true;
} }
return true; return true;
@@ -278,7 +260,7 @@ class Inbox extends Component
private function checkDomainInUsername(): void private function checkDomainInUsername(): void
{ {
$parts = explode('@', $this->username); $parts = explode('@', (string) $this->username);
if (isset($parts[1])) { if (isset($parts[1])) {
if (in_array($parts[1], $this->domains)) { if (in_array($parts[1], $this->domains)) {
$this->domain = $parts[1]; $this->domain = $parts[1];
@@ -291,13 +273,13 @@ class Inbox extends Component
{ {
try { try {
if ($this->email != null) { if ($this->email != null) {
$data = explode('@', $this->email); $data = explode('@', (string) $this->email);
if (isset($data[1])) { if (isset($data[1])) {
$domain = $data[1]; $domain = $data[1];
if ($this->premium) { if ($this->premium) {
$domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
} else { } else {
$domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
} }
if (! in_array($domain, $domains)) { if (! in_array($domain, $domains)) {
$key = array_search($this->email, $this->emails); $key = array_search($this->email, $this->emails);
@@ -306,16 +288,12 @@ class Inbox extends Component
} else { } else {
ZEmail::removeEmail($this->email); ZEmail::removeEmail($this->email);
} }
if ($key == 0 && count($this->emails) == 1 && json_decode(config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') { to_route('dashboard.premium');
redirect()->route('dashboard.premium');
} else {
redirect()->route('dashboard.premium');
}
} }
} }
} }
} catch (Exception $exception) { } catch (Exception $exception) {
\Log::error($exception->getMessage()); \Illuminate\Support\Facades\Log::error($exception->getMessage());
} }
} }
@@ -330,7 +308,7 @@ class Inbox extends Component
} }
$responses = []; $responses = [];
if ($this->premium) { if ($this->premium) {
if (config('app.beta_feature') || ! json_decode(config('app.settings.imap_settings'))->premium_cc_check) { if (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->premium_cc_check) {
$responses = [ $responses = [
'to' => Premium::getMessages($this->email, 'to', $this->deleted), 'to' => Premium::getMessages($this->email, 'to', $this->deleted),
'cc' => [ 'cc' => [
@@ -344,8 +322,7 @@ class Inbox extends Component
'cc' => Premium::getMessages($this->email, 'cc', $this->deleted), 'cc' => Premium::getMessages($this->email, 'cc', $this->deleted),
]; ];
} }
} else { } elseif (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->cc_check) {
if (config('app.beta_feature') || ! json_decode(config('app.settings.imap_settings'))->cc_check) {
$responses = [ $responses = [
'to' => ZEmail::getMessages($this->email, 'to', $this->deleted), 'to' => ZEmail::getMessages($this->email, 'to', $this->deleted),
'cc' => [ 'cc' => [
@@ -359,14 +336,13 @@ class Inbox extends Component
'cc' => ZEmail::getMessages($this->email, 'cc', $this->deleted), 'cc' => ZEmail::getMessages($this->email, 'cc', $this->deleted),
]; ];
} }
}
$this->deleted = []; $this->deleted = [];
$this->messages = array_merge($responses['to']['data'], $responses['cc']['data']); $this->messages = array_merge($responses['to']['data'], $responses['cc']['data']);
$notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']); $notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']);
if (count($notifications)) { if (count($notifications)) {
if (! $this->overflow && count($this->messages) == $count) { if (! $this->overflow && count($this->messages) === $count) {
$this->overflow = true; $this->overflow = true;
} }
} else { } else {
@@ -397,7 +373,7 @@ class Inbox extends Component
$this->initial = true; $this->initial = true;
} }
public function delete($messageId) public function delete(string $messageId): void
{ {
try { try {
@@ -422,23 +398,23 @@ class Inbox extends Component
} }
public function toggleMode() public function toggleMode(): void
{ {
$this->premium = ! $this->premium; $this->premium = ! $this->premium;
Session::put('isInboxTypePremium', $this->premium); Session::put('isInboxTypePremium', $this->premium);
if ($this->premium) { if ($this->premium) {
$this->domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; $this->domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
$this->email = Premium::getEmail(); $this->email = Premium::getEmail();
$this->emails = Premium::getEmails(); $this->emails = Premium::getEmails();
$this->initial = false; $this->initial = false;
$this->checkMultipleEmails(); $this->checkMultipleEmails();
$this->validateDomainInEmail(); $this->validateDomainInEmail();
$mailboxHistory = UsageLog::where(['user_id' => auth()->user()->id])->first(); $mailboxHistory = UsageLog::query()->where(['user_id' => auth()->user()->id])->first();
$this->mailboxHistory = $mailboxHistory->emails_created_history ?? []; $this->mailboxHistory = $mailboxHistory->emails_created_history ?? [];
$this->messages = []; $this->messages = [];
} else { } else {
$this->domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
$this->email = ZEmail::getEmail(); $this->email = ZEmail::getEmail();
$this->emails = ZEmail::getEmails(); $this->emails = ZEmail::getEmails();
$this->initial = false; $this->initial = false;
@@ -453,17 +429,16 @@ class Inbox extends Component
{ {
if (Session::get('isSubscribed')) { if (Session::get('isSubscribed')) {
return view('livewire.dashboard.mailbox.inbox')->layout('components.layouts.dashboard'); return view('livewire.dashboard.mailbox.inbox')->layout('components.layouts.dashboard');
} else { }
return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard'); return view('livewire.dashboard.not-subscribed')->layout('components.layouts.dashboard');
} }
}
private function rrmdir($dir): void private function rrmdir(string $dir): void
{ {
if (is_dir($dir)) { if (is_dir($dir)) {
$objects = scandir($dir); $objects = scandir($dir);
foreach ($objects as $object) { foreach ($objects as $object) {
if ($object != '.' && $object != '..') { if ($object !== '.' && $object !== '..') {
if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) { if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) {
$this->rrmdir($dir.DIRECTORY_SEPARATOR.$object); $this->rrmdir($dir.DIRECTORY_SEPARATOR.$object);
} else { } else {

View File

@@ -2,11 +2,13 @@
namespace App\Livewire\Dashboard; namespace App\Livewire\Dashboard;
use Illuminate\Support\Facades\Log;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use App\Models\ActivationKey; use App\Models\ActivationKey;
use App\Models\Plan; use App\Models\Plan;
use Exception; use Exception;
use Livewire\Component; use Livewire\Component;
use Log;
class Pricing extends Component class Pricing extends Component
{ {
@@ -34,8 +36,8 @@ class Pricing extends Component
'activation_key.max' => 'The activation key must not exceed 30 characters.', 'activation_key.max' => 'The activation key must not exceed 30 characters.',
]); ]);
$trimmedKey = trim($this->activation_key); $trimmedKey = trim((string) $this->activation_key);
$activation = ActivationKey::where('activation_key', $trimmedKey) $activation = ActivationKey::query()->where('activation_key', $trimmedKey)
->where('is_activated', false) ->where('is_activated', false)
->first(); ->first();
@@ -43,7 +45,7 @@ class Pricing extends Component
if ($activation->price_id !== null) { if ($activation->price_id !== null) {
$result = $this->addSubscription($activation->price_id); $result = $this->addSubscription($activation->price_id);
} }
if ($result === true) { if ($result) {
$activation->is_activated = true; $activation->is_activated = true;
$activation->user_id = auth()->id(); $activation->user_id = auth()->id();
$activation->save(); $activation->save();
@@ -61,7 +63,7 @@ class Pricing extends Component
private function addSubscription($price_id): bool private function addSubscription($price_id): bool
{ {
try { try {
$plan = Plan::where('pricing_id', $price_id)->firstOrFail(); $plan = Plan::query()->where('pricing_id', $price_id)->firstOrFail();
$user = auth()->user(); $user = auth()->user();
$user->createOrGetStripeCustomer(); $user->createOrGetStripeCustomer();
$user->updateStripeCustomer([ $user->updateStripeCustomer([
@@ -76,11 +78,7 @@ class Pricing extends Component
$balance = $user->balance(); $balance = $user->balance();
$user->newSubscription('default', $plan->pricing_id)->create(); $user->newSubscription('default', $plan->pricing_id)->create();
if ($plan->monthly_billing == 1) { $ends_at = $plan->monthly_billing == 1 ? now()->addMonth() : now()->addYear();
$ends_at = now()->addMonth();
} else {
$ends_at = now()->addYear();
}
$user->subscription('default')->cancelAt($ends_at); $user->subscription('default')->cancelAt($ends_at);
return true; return true;
@@ -91,7 +89,7 @@ class Pricing extends Component
} }
} }
public function render() public function render(): Factory|View
{ {
return view('livewire.dashboard.pricing'); return view('livewire.dashboard.pricing');
} }

View File

@@ -2,12 +2,12 @@
namespace App\Livewire\Dashboard; namespace App\Livewire\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Request;
use App\Models\Ticket; use App\Models\Ticket;
use App\Models\TicketResponse; use App\Models\TicketResponse;
use Exception; use Exception;
use Livewire\Component; use Livewire\Component;
use Request;
use Str;
class Support extends Component class Support extends Component
{ {
@@ -25,7 +25,7 @@ class Support extends Component
public $closed = 0; public $closed = 0;
public function store() public function store(): void
{ {
$this->validate([ $this->validate([
'subject' => 'required|string|max:255', 'subject' => 'required|string|max:255',
@@ -33,7 +33,7 @@ class Support extends Component
]); ]);
try { try {
$ticket = Ticket::create([ $ticket = Ticket::query()->create([
'user_id' => auth()->id(), 'user_id' => auth()->id(),
'ticket_id' => strtoupper(Str::random(6)), 'ticket_id' => strtoupper(Str::random(6)),
'subject' => $this->subject, 'subject' => $this->subject,
@@ -47,13 +47,13 @@ class Support extends Component
$this->tickets = Ticket::with('responses') $this->tickets = Ticket::with('responses')
->where('user_id', auth()->id()) ->where('user_id', auth()->id())
->get(); ->get();
} catch (Exception $exception) { } catch (Exception) {
$this->dispatch('showAlert', ['type' => 'error', 'message' => 'Something went wrong!']); $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Something went wrong!']);
} }
} }
public function reply($ticket_id) public function reply($ticket_id): void
{ {
$this->validate([ $this->validate([
'response' => 'required|string', 'response' => 'required|string',
@@ -67,14 +67,14 @@ class Support extends Component
return; return;
} }
$ticket = Ticket::find($ticket_id); $ticket = Ticket::query()->find($ticket_id);
if (! $ticket) { if (! $ticket) {
$this->dispatch('showAlert', ['type' => 'error', 'message' => 'Ticket not found.']); $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Ticket not found.']);
return; return;
} }
TicketResponse::create([ TicketResponse::query()->create([
'ticket_id' => $ticket_id, 'ticket_id' => $ticket_id,
'user_id' => auth()->id(), 'user_id' => auth()->id(),
'response' => $this->response, 'response' => $this->response,
@@ -90,20 +90,20 @@ class Support extends Component
->where('user_id', auth()->id()) ->where('user_id', auth()->id())
->get(); ->get();
} catch (Exception $exception) { } catch (Exception) {
session()->flash('error', 'Something went wrong!'); session()->flash('error', 'Something went wrong!');
} }
} }
public function close($ticket_id) public function close($ticket_id): void
{ {
if (! is_numeric($ticket_id)) { if (! is_numeric($ticket_id)) {
$this->dispatch('showAlert', ['type' => 'error', 'message' => 'Invalid ticket ID.']); $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Invalid ticket ID.']);
return; return;
} }
$ticket = Ticket::find($ticket_id); $ticket = Ticket::query()->find($ticket_id);
if (! $ticket) { if (! $ticket) {
$this->dispatch('showAlert', ['type' => 'error', 'message' => 'Ticket not found.']); $this->dispatch('showAlert', ['type' => 'error', 'message' => 'Ticket not found.']);
@@ -119,7 +119,7 @@ class Support extends Component
$this->dispatch('showAlert', ['type' => 'error', 'message' => 'This ticket has been closed!']); $this->dispatch('showAlert', ['type' => 'error', 'message' => 'This ticket has been closed!']);
} }
public function mount() public function mount(): void
{ {
$this->tickets = Ticket::with('responses') $this->tickets = Ticket::with('responses')
->where('user_id', auth()->id()) ->where('user_id', auth()->id())
@@ -127,15 +127,11 @@ class Support extends Component
$this->updateTicketCounts(); $this->updateTicketCounts();
} }
public function updateTicketCounts() public function updateTicketCounts(): void
{ {
$this->open = $this->tickets->filter(function ($ticket) { $this->open = $this->tickets->filter(fn($ticket): bool => in_array($ticket->status, ['open', 'pending']))->count();
return in_array($ticket->status, ['open', 'pending']);
})->count();
$this->closed = $this->tickets->filter(function ($ticket) { $this->closed = $this->tickets->filter(fn($ticket): bool => $ticket->status === 'closed')->count();
return $ticket->status === 'closed';
})->count();
} }
protected function getClientIp() protected function getClientIp()

View File

@@ -2,9 +2,13 @@
namespace App\Livewire\Frontend; namespace App\Livewire\Frontend;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Date;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use App\Models\Log; use App\Models\Log;
use App\Models\ZEmail; use App\Models\ZEmail;
use Carbon\Carbon;
use Livewire\Component; use Livewire\Component;
class Action extends Component class Action extends Component
@@ -23,9 +27,9 @@ class Action extends Component
public $initial; public $initial;
public function mount() public function mount(): void
{ {
$this->domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; $this->domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
$this->email = ZEmail::getEmail(); $this->email = ZEmail::getEmail();
$this->emails = ZEmail::getEmails(); $this->emails = ZEmail::getEmails();
$this->validateDomainInEmail(); $this->validateDomainInEmail();
@@ -37,17 +41,17 @@ class Action extends Component
return $this->showAlert('error', __('Please enter Username')); return $this->showAlert('error', __('Please enter Username'));
} }
$this->checkDomainInUsername(); $this->checkDomainInUsername();
if (strlen($this->username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($this->username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { if (strlen((string) $this->username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen((string) $this->username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) {
return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode(config('app.settings.configuration_settings'))->custom_username_length_max); return $this->showAlert('error', __('Username length cannot be less than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min.' '.__('and greater than').' '.json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max);
} }
if (! $this->domain) { if (! $this->domain) {
return $this->showAlert('error', __('Please Select a Domain')); return $this->showAlert('error', __('Please Select a Domain'));
} }
if (in_array($this->username, json_decode(config('app.settings.configuration_settings'))->forbidden_ids)) { if (in_array($this->username, json_decode((string) config('app.settings.configuration_settings'))->forbidden_ids)) {
return $this->showAlert('error', __('Username not allowed')); return $this->showAlert('error', __('Username not allowed'));
} }
if (! $this->checkEmailLimit()) { if (! $this->checkEmailLimit()) {
return $this->showAlert('error', __('You have reached daily limit of MAX ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail')); return $this->showAlert('error', __('You have reached daily limit of MAX ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail'));
} }
if (! $this->checkUsedEmail()) { if (! $this->checkUsedEmail()) {
return $this->showAlert('error', __('Sorry! That email is already been used by someone else. Please try a different email address.')); return $this->showAlert('error', __('Sorry! That email is already been used by someone else. Please try a different email address.'));
@@ -55,49 +59,49 @@ class Action extends Component
$this->email = ZEmail::createCustomEmail($this->username, $this->domain); $this->email = ZEmail::createCustomEmail($this->username, $this->domain);
return redirect()->route('mailbox'); return to_route('mailbox');
} }
public function random() public function random()
{ {
if (! $this->checkEmailLimit()) { if (! $this->checkEmailLimit()) {
return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.'));
} }
$this->email = ZEmail::generateRandomEmail(); $this->email = ZEmail::generateRandomEmail();
return redirect()->route('mailbox'); return to_route('mailbox');
} }
public function gmail() public function gmail()
{ {
if (! $this->checkEmailLimit()) { if (! $this->checkEmailLimit()) {
return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.'));
} }
$this->email = ZEmail::generateRandomGmail(); $this->email = ZEmail::generateRandomGmail();
return redirect()->route('mailbox'); return to_route('mailbox');
} }
public function outlook() public function outlook()
{ {
if (! $this->checkEmailLimit()) { if (! $this->checkEmailLimit()) {
return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode(config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.')); return $this->showAlert('error', __('You have reached daily limit of maximum ').json_decode((string) config('app.settings.configuration_settings'))->email_limit.__(' temp mail addresses.'));
} }
$this->email = ZEmail::generateRandomOutlook(); $this->email = ZEmail::generateRandomOutlook();
return redirect()->route('mailbox'); return to_route('mailbox');
} }
public function deleteEmail() public function deleteEmail(): Redirector|RedirectResponse
{ {
return redirect()->route('delete', ['email' => $this->email]); return to_route('delete', ['email' => $this->email]);
} }
private function showAlert($type, $message): void private function showAlert(string $type, $message): void
{ {
$check = json_decode(config('app.settings.configuration_settings'))->email_limit; $check = json_decode((string) config('app.settings.configuration_settings'))->email_limit;
if (strpos($message, $check) !== false) { if (str_contains((string) $message, (string) $check)) {
$this->dispatch('promotePremium'); $this->dispatch('promotePremium');
} }
$this->dispatch('showAlert', ['type' => $type, 'message' => $message]); $this->dispatch('showAlert', ['type' => $type, 'message' => $message]);
@@ -105,31 +109,23 @@ class Action extends Component
private function checkEmailLimit(): bool private function checkEmailLimit(): bool
{ {
$logs = Log::select('ip', 'email')->where('ip', request()->ip())->where('created_at', '>', Carbon::now()->subDay())->groupBy('email')->groupBy('ip')->get(); $logs = Log::query()->select('ip', 'email')->where('ip', request()->ip())->where('created_at', '>', Date::now()->subDay())->groupBy('email')->groupBy('ip')->get();
if (count($logs) >= json_decode(config('app.settings.configuration_settings'))->email_limit) { return count($logs) < json_decode((string) config('app.settings.configuration_settings'))->email_limit;
return false;
}
return true;
} }
private function checkUsedEmail(): bool private function checkUsedEmail(): bool
{ {
if (json_decode(config('app.settings.configuration_settings'))->disable_used_email) { if (json_decode((string) config('app.settings.configuration_settings'))->disable_used_email) {
$check = Log::where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count(); $check = Log::query()->where('email', $this->user.'@'.$this->domain)->where('ip', '<>', request()->ip())->count();
if ($check > 0) { return $check <= 0;
return false;
} }
return true; return true;
} }
return true; private function checkDomainInUsername(): void
}
private function checkDomainInUsername()
{ {
$parts = explode('@', $this->username); $parts = explode('@', (string) $this->username);
if (isset($parts[1])) { if (isset($parts[1])) {
if (in_array($parts[1], $this->domains)) { if (in_array($parts[1], $this->domains)) {
$this->domain = $parts[1]; $this->domain = $parts[1];
@@ -140,23 +136,23 @@ class Action extends Component
private function validateDomainInEmail(): void private function validateDomainInEmail(): void
{ {
$data = explode('@', $this->email); $data = explode('@', (string) $this->email);
if (isset($data[1])) { if (isset($data[1])) {
$domain = $data[1]; $domain = $data[1];
$domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
if (! in_array($domain, $domains)) { if (! in_array($domain, $domains)) {
$key = array_search($this->email, $this->emails); $key = array_search($this->email, $this->emails);
ZEmail::removeEmail($this->email); ZEmail::removeEmail($this->email);
if ($key == 0 && count($this->emails) == 1 && json_decode(config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') { if ($key == 0 && count($this->emails) === 1 && json_decode((string) config('app.settings.configuration_settings'))->after_last_email_delete == 'redirect_to_homepage') {
redirect()->route('home'); to_route('home');
} else { } else {
redirect()->route('mailbox'); to_route('mailbox');
} }
} }
} }
} }
public function render() public function render(): Factory|View
{ {
return view('livewire.frontend.action'); return view('livewire.frontend.action');
} }

View File

@@ -2,6 +2,8 @@
namespace App\Livewire\Frontend; namespace App\Livewire\Frontend;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Models\ZEmail; use App\Models\ZEmail;
use Livewire\Component; use Livewire\Component;
@@ -29,26 +31,22 @@ class Email extends Component
private function checkMultipleEmails(): void private function checkMultipleEmails(): void
{ {
if (count($this->emails) == 0) { if (count($this->emails) === 0) {
$this->emails = [$this->email]; $this->emails = [$this->email];
} }
if (count($this->emails) > 1) { $this->list = count($this->emails) > 1;
$this->list = true;
} else {
$this->list = false;
}
} }
public function switchEmail($email) public function switchEmail($email): Redirector|RedirectResponse
{ {
return redirect()->route('switch', ['email' => $email]); return to_route('switch', ['email' => $email]);
} }
public function syncEmail(): void public function syncEmail(): void
{ {
$this->email = ZEmail::getEmail(); $this->email = ZEmail::getEmail();
$this->emails = ZEmail::getEmails(); $this->emails = ZEmail::getEmails();
if (count($this->emails) == 0) { if (count($this->emails) === 0) {
$this->dispatch('getEmail'); $this->dispatch('getEmail');
} }
$this->checkMultipleEmails(); $this->checkMultipleEmails();

View File

@@ -38,8 +38,9 @@ class Mailbox extends Component
$this->email = ZEmail::getEmail(); $this->email = ZEmail::getEmail();
$this->initial = false; $this->initial = false;
if (! ZEmail::getEmail()) { if (! ZEmail::getEmail()) {
return redirect()->route('home'); return to_route('home');
} }
return null;
} }
public function syncEmail($email): void public function syncEmail($email): void
@@ -57,7 +58,7 @@ class Mailbox extends Component
$this->messages = []; $this->messages = [];
} }
$responses = []; $responses = [];
if (config('app.beta_feature') || ! json_decode(config('app.settings.imap_settings'))->cc_check) { if (config('app.beta_feature') || ! json_decode((string) config('app.settings.imap_settings'))->cc_check) {
$responses = [ $responses = [
'to' => ZEmail::getMessages($this->email, 'to', $this->deleted), 'to' => ZEmail::getMessages($this->email, 'to', $this->deleted),
'cc' => [ 'cc' => [
@@ -77,7 +78,7 @@ class Mailbox extends Component
$notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']); $notifications = array_merge($responses['to']['notifications'], $responses['cc']['notifications']);
if (count($notifications)) { if (count($notifications)) {
if (! $this->overflow && count($this->messages) == $count) { if (! $this->overflow && count($this->messages) === $count) {
$this->overflow = true; $this->overflow = true;
} }
} else { } else {
@@ -99,15 +100,15 @@ class Mailbox extends Component
$this->initial = true; $this->initial = true;
} }
public function delete($messageId) public function delete(string $messageId): void
{ {
try { try {
if (config('app.beta_feature')) { if (config('app.beta_feature')) {
Message::find($messageId)->delete(); Message::query()->find($messageId)->delete();
} }
if (config('app.fetch_from_db')) { if (config('app.fetch_from_db')) {
Email::where(['message_id' => $messageId])->delete(); Email::query()->where(['message_id' => $messageId])->delete();
} }
$this->deleted[] = $messageId; $this->deleted[] = $messageId;
foreach ($this->messages as $key => $message) { foreach ($this->messages as $key => $message) {
@@ -131,12 +132,12 @@ class Mailbox extends Component
return view('livewire.frontend.mailbox')->with(['messages' => $this->messages, 'email' => $this->email, 'initial' => $this->initial, 'error' => $this->error]); return view('livewire.frontend.mailbox')->with(['messages' => $this->messages, 'email' => $this->email, 'initial' => $this->initial, 'error' => $this->error]);
} }
private function rrmdir($dir): void private function rrmdir(string $dir): void
{ {
if (is_dir($dir)) { if (is_dir($dir)) {
$objects = scandir($dir); $objects = scandir($dir);
foreach ($objects as $object) { foreach ($objects as $object) {
if ($object != '.' && $object != '..') { if ($object !== '.' && $object !== '..') {
if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) { if (is_dir($dir.DIRECTORY_SEPARATOR.$object) && ! is_link($dir.'/'.$object)) {
$this->rrmdir($dir.DIRECTORY_SEPARATOR.$object); $this->rrmdir($dir.DIRECTORY_SEPARATOR.$object);
} else { } else {

View File

@@ -2,6 +2,8 @@
namespace App\Livewire; namespace App\Livewire;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use App\Models\ZEmail; use App\Models\ZEmail;
use Livewire\Component; use Livewire\Component;
@@ -14,11 +16,12 @@ class Home extends Component
$email = ZEmail::getEmail(); $email = ZEmail::getEmail();
$messages = ZEmail::getMessages($email); $messages = ZEmail::getMessages($email);
if (count($messages['data']) > 0) { if (count($messages['data']) > 0) {
return redirect()->route('mailbox'); return to_route('mailbox');
} }
return null;
} }
public function render() public function render(): Factory|View
{ {
return view('livewire.home'); return view('livewire.home');
} }

View File

@@ -2,11 +2,13 @@
namespace App\Livewire; namespace App\Livewire;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Livewire\Component; use Livewire\Component;
class ListBlog extends Component class ListBlog extends Component
{ {
public function render() public function render(): Factory|View
{ {
return view('livewire.list-blog'); return view('livewire.list-blog');
} }

View File

@@ -2,24 +2,24 @@
namespace App\Livewire; namespace App\Livewire;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Livewire\Component; use Livewire\Component;
class Page extends Component class Page extends Component
{ {
public $slug; public $slug;
public function mount($slug) public function mount($slug): void
{ {
$this->slug = $slug; $this->slug = $slug;
} }
public function render() public function render(): Factory|View
{ {
$page = \App\Models\Page::where('slug', $this->slug)->firstOrFail(); $page = \App\Models\Page::query()->where('slug', $this->slug)->firstOrFail();
if ($page->is_published == false) { abort_if($page->is_published == false, 404);
abort(404);
}
return view('livewire.page', [ return view('livewire.page', [
'page' => $page, 'page' => $page,

View File

@@ -15,17 +15,11 @@ class TicketResponseNotification extends Mailable
{ {
use Queueable, SerializesModels; use Queueable, SerializesModels;
public Ticket $ticket;
public Collection $responses;
/** /**
* Create a new message instance. * Create a new message instance.
*/ */
public function __construct(Ticket $ticket, Collection $responses) public function __construct(public Ticket $ticket, public Collection $responses)
{ {
$this->ticket = $ticket;
$this->responses = $responses;
} }
/** /**

View File

@@ -2,6 +2,7 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -31,7 +32,8 @@ class ActivationKey extends Model
/** /**
* Scope to filter unactivated keys * Scope to filter unactivated keys
*/ */
public function scopeUnactivated($query) #[Scope]
protected function unactivated($query)
{ {
return $query->where('is_activated', false); return $query->where('is_activated', false);
} }
@@ -39,7 +41,8 @@ class ActivationKey extends Model
/** /**
* Scope to filter activated keys * Scope to filter activated keys
*/ */
public function scopeActivated($query) #[Scope]
protected function activated($query)
{ {
return $query->where('is_activated', true); return $query->where('is_activated', true);
} }

View File

@@ -2,13 +2,13 @@
namespace App\Models; namespace App\Models;
use DateTimeImmutable;
use Illuminate\Support\Facades\Date;
use App\ColorPicker; use App\ColorPicker;
use Carbon\Carbon;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use DateTime; use DateTime;
use Ddeboer\Imap\ConnectionInterface; use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\Search\Date\Since; use Ddeboer\Imap\Search\Date\Since;
use Ddeboer\Imap\Search\Email\To;
use Ddeboer\Imap\Server; use Ddeboer\Imap\Server;
use Exception; use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -55,20 +55,16 @@ class Email extends Model
public static function connectMailBox($imap = null): ConnectionInterface public static function connectMailBox($imap = null): ConnectionInterface
{ {
if ($imap === null) { if ($imap === null) {
$imap = json_decode(config('app.settings.imap_settings'), true); $imap = json_decode((string) config('app.settings.imap_settings'), true);
} }
$flags = $imap['protocol'].'/'.$imap['encryption']; $flags = $imap['protocol'].'/'.$imap['encryption'];
if ($imap['validate_cert']) { $flags = $imap['validate_cert'] ? $flags.'/validate-cert' : $flags.'/novalidate-cert';
$flags = $flags.'/validate-cert';
} else {
$flags = $flags.'/novalidate-cert';
}
$server = new Server($imap['host'], $imap['port'], $flags); $server = new Server($imap['host'], $imap['port'], $flags);
return $server->authenticate($imap['username'], $imap['password']); return $server->authenticate($imap['username'], $imap['password']);
} }
public static function fetchProcessStoreEmail() public static function fetchProcessStoreEmail(): void
{ {
try { try {
@@ -82,7 +78,7 @@ class Email extends Model
$sender = $message->getFrom(); $sender = $message->getFrom();
$date = $message->getDate(); $date = $message->getDate();
if (! $date) { if (!$date instanceof DateTimeImmutable) {
$date = new DateTime; $date = new DateTime;
if ($message->getHeaders()->get('udate')) { if ($message->getHeaders()->get('udate')) {
$date->setTimestamp($message->getHeaders()->get('udate')); $date->setTimestamp($message->getHeaders()->get('udate'));
@@ -104,17 +100,11 @@ class Email extends Model
$obj = []; $obj = [];
$to = $message->getHeaders()->get('To') ? array_map(function ($entry) { $to = $message->getHeaders()->get('To') ? array_map(fn($entry): string => $entry->mailbox.'@'.$entry->host, $message->getHeaders()->get('To')) : [];
return $entry->mailbox.'@'.$entry->host;
}, $message->getHeaders()->get('To')) : [];
$cc = $message->getHeaders()->get('Cc') ? array_map(function ($entry) { $cc = $message->getHeaders()->get('Cc') ? array_map(fn($entry): string => $entry->mailbox.'@'.$entry->host, $message->getHeaders()->get('Cc')) : [];
return $entry->mailbox.'@'.$entry->host;
}, $message->getHeaders()->get('Cc')) : [];
$bcc = $message->getHeaders()->get('Bcc') ? array_map(function ($entry) { $bcc = $message->getHeaders()->get('Bcc') ? array_map(fn($entry): string => $entry->mailbox.'@'.$entry->host, $message->getHeaders()->get('Bcc')) : [];
return $entry->mailbox.'@'.$entry->host;
}, $message->getHeaders()->get('Bcc')) : [];
$messageTime = $message->getDate(); $messageTime = $message->getDate();
$utcTime = CarbonImmutable::instance($messageTime)->setTimezone('UTC')->toDateTimeString(); $utcTime = CarbonImmutable::instance($messageTime)->setTimezone('UTC')->toDateTimeString();
@@ -139,9 +129,11 @@ class Email extends Model
$attachments = $message->getAttachments(); $attachments = $message->getAttachments();
$directory = './tmp/attachments/'.$obj['id'].'/'; $directory = './tmp/attachments/'.$obj['id'].'/';
is_dir($directory) || mkdir($directory, 0777, true); if (!is_dir($directory)) {
mkdir($directory, 0777, true);
}
foreach ($attachments as $attachment) { foreach ($attachments as $attachment) {
$filenameArray = explode('.', $attachment->getFilename()); $filenameArray = explode('.', (string) $attachment->getFilename());
$extension = $filenameArray[count($filenameArray) - 1]; $extension = $filenameArray[count($filenameArray) - 1];
if (in_array($extension, $allowed)) { if (in_array($extension, $allowed)) {
if (! file_exists($directory.$attachment->getFilename())) { if (! file_exists($directory.$attachment->getFilename())) {
@@ -177,7 +169,7 @@ class Email extends Model
if (! $message->isSeen()) { if (! $message->isSeen()) {
$initialData = $obj; $initialData = $obj;
$data = [ $data = [
'message_id' => Carbon::parse($utcTime)->format('Ymd').$initialData['id'], 'message_id' => Date::parse($utcTime)->format('Ymd').$initialData['id'],
'subject' => $initialData['subject'], 'subject' => $initialData['subject'],
'from_name' => $initialData['sender_name'], 'from_name' => $initialData['sender_name'],
'from_email' => $initialData['sender_email'], 'from_email' => $initialData['sender_email'],
@@ -197,7 +189,7 @@ class Email extends Model
]; ];
try { try {
self::create($data); self::query()->create($data);
$checkAction = config('app.move_or_delete'); $checkAction = config('app.move_or_delete');
if ($checkAction != null) { if ($checkAction != null) {
if ($checkAction == 'delete') { if ($checkAction == 'delete') {
@@ -208,13 +200,13 @@ class Email extends Model
} }
} }
} catch (Exception $e) { } catch (Exception) {
// \Log::error($e); // \Log::error($e);
} }
} else { } else {
$initialData = $obj; $initialData = $obj;
$data = [ $data = [
'message_id' => Carbon::parse($utcTime)->format('Ymd').$initialData['id'], 'message_id' => Date::parse($utcTime)->format('Ymd').$initialData['id'],
'subject' => $initialData['subject'], 'subject' => $initialData['subject'],
'from_name' => $initialData['sender_name'], 'from_name' => $initialData['sender_name'],
'from_email' => $initialData['sender_email'], 'from_email' => $initialData['sender_email'],
@@ -234,7 +226,7 @@ class Email extends Model
]; ];
try { try {
self::create($data); self::query()->create($data);
$checkAction = config('app.move_or_delete'); $checkAction = config('app.move_or_delete');
if ($checkAction != null) { if ($checkAction != null) {
if ($checkAction == 'delete') { if ($checkAction == 'delete') {
@@ -245,7 +237,7 @@ class Email extends Model
} }
} }
} catch (Exception $e) { } catch (Exception) {
// \Log::error($e); // \Log::error($e);
} }
} }
@@ -263,24 +255,24 @@ class Email extends Model
{ {
$validator = Validator::make(['email' => $email], [ $validator = Validator::make(['email' => $email], [
'email' => 'required|email', 'email' => ['required', 'email'],
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return []; return [];
} }
return self::whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get(); return self::query()->whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get();
} }
public static function parseEmail($email, $deleted = []): array public static function parseEmail(string $email, $deleted = []): array
{ {
if (config('app.fetch_from_remote_db')) { if (config('app.fetch_from_remote_db')) {
$messages = RemoteEmail::fetchEmailFromDB($email); $messages = RemoteEmail::fetchEmailFromDB($email);
} else { } else {
$messages = self::fetchEmailFromDB($email); $messages = self::fetchEmailFromDB($email);
} }
$limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15;
$count = 1; $count = 1;
$response = [ $response = [
'data' => [], 'data' => [],
@@ -297,9 +289,9 @@ class Email extends Model
if (in_array($message['message_id'], $deleted)) { if (in_array($message['message_id'], $deleted)) {
// If it exists, delete the matching record from the 'emails' table // If it exists, delete the matching record from the 'emails' table
if (config('app.fetch_from_remote_db')) { if (config('app.fetch_from_remote_db')) {
RemoteEmail::where('message_id', $message['message_id'])->delete(); RemoteEmail::query()->where('message_id', $message['message_id'])->delete();
} else { } else {
Email::where('message_id', $message['message_id'])->delete(); Email::query()->where('message_id', $message['message_id'])->delete();
} }
continue; continue;
@@ -308,23 +300,23 @@ class Email extends Model
$blocked = false; $blocked = false;
$timestamp = $message['timestamp']; $timestamp = $message['timestamp'];
$carbonTimestamp = Carbon::parse($timestamp, 'UTC'); $carbonTimestamp = Date::parse($timestamp, 'UTC');
$obj = []; $obj = [];
$obj['subject'] = $message['subject']; $obj['subject'] = $message['subject'];
$obj['sender_name'] = $message['from_name']; $obj['sender_name'] = $message['from_name'];
$obj['sender_email'] = $message['from_email']; $obj['sender_email'] = $message['from_email'];
$obj['timestamp'] = $message['timestamp']; $obj['timestamp'] = $message['timestamp'];
$obj['date'] = $carbonTimestamp->format('d M Y h:i A'); $obj['date'] = $carbonTimestamp->format('d M Y h:i A');
$obj['datediff'] = $carbonTimestamp->diffForHumans(Carbon::now('UTC')); $obj['datediff'] = $carbonTimestamp->diffForHumans(Date::now('UTC'));
$obj['id'] = $message['message_id']; $obj['id'] = $message['message_id'];
$obj['content'] = $message['body_html']; $obj['content'] = $message['body_html'];
$obj['contentText'] = $message['body_text']; $obj['contentText'] = $message['body_text'];
$obj['attachments'] = []; $obj['attachments'] = [];
$obj['is_seen'] = $message['is_seen']; $obj['is_seen'] = $message['is_seen'];
$obj['sender_photo'] = self::chooseColor(strtoupper(substr($message['from_name'] ?: $message['from_email'], 0, 1))); $obj['sender_photo'] = self::chooseColor(strtoupper(substr((string) $message['from_name'] ?: (string) $message['from_email'], 0, 1)));
$domain = explode('@', $obj['sender_email'])[1]; $domain = explode('@', (string) $obj['sender_email'])[1];
$blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains);
if ($blocked) { if ($blocked) {
$obj['subject'] = __('Blocked'); $obj['subject'] = __('Blocked');
$obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin');
@@ -348,9 +340,9 @@ class Email extends Model
} }
} }
if (config('app.fetch_from_remote_db')) { if (config('app.fetch_from_remote_db')) {
RemoteEmail::where('message_id', $message['message_id'])->update(['is_seen' => true]); RemoteEmail::query()->where('message_id', $message['message_id'])->update(['is_seen' => true]);
} else { } else {
Email::where('message_id', $message['message_id'])->update(['is_seen' => true]); Email::query()->where('message_id', $message['message_id'])->update(['is_seen' => true]);
} }
if (++$count > $limit) { if (++$count > $limit) {
break; break;
@@ -360,7 +352,7 @@ class Email extends Model
return $response; return $response;
} }
public static function deleteBulkAttachments() public static function deleteBulkAttachments(): void
{ {
$dir = public_path('/tmp/attachments'); $dir = public_path('/tmp/attachments');
@@ -373,7 +365,7 @@ class Email extends Model
} }
} }
public static function deleteBulkMailboxes() public static function deleteBulkMailboxes(): string
{ {
$foldersToClean = ['INBOX', 'ZDUMP', 'Trash']; $foldersToClean = ['INBOX', 'ZDUMP', 'Trash'];
$cutoff = (new DateTime)->modify('-3 hours'); $cutoff = (new DateTime)->modify('-3 hours');
@@ -410,15 +402,15 @@ class Email extends Model
return "$totalDeleted message(s) deleted from Trash and ZDUMP."; return "$totalDeleted message(s) deleted from Trash and ZDUMP.";
} }
public static function deleteMessagesFromDB() public static function deleteMessagesFromDB(): string
{ {
$cutoff = Carbon::now('UTC')->subHours(6)->toDateTimeString(); $cutoff = Date::now('UTC')->subHours(6)->toDateTimeString();
$count = count(self::where('timestamp', '<', $cutoff) $count = count(self::query()->where('timestamp', '<', $cutoff)
->orderBy('timestamp', 'desc') ->orderBy('timestamp', 'desc')
->get()); ->get());
if ($count > 0) { if ($count > 0) {
self::where('timestamp', '<', $cutoff)->delete(); self::query()->where('timestamp', '<', $cutoff)->delete();
return "$count old message(s) deleted from the database."; return "$count old message(s) deleted from the database.";
} }
@@ -429,22 +421,17 @@ class Email extends Model
public static function mailToDBStatus(): bool public static function mailToDBStatus(): bool
{ {
if (config('app.fetch_from_remote_db')) { if (config('app.fetch_from_remote_db')) {
$latestRecord = RemoteEmail::orderBy('timestamp', 'desc')->first(); $latestRecord = RemoteEmail::query()->orderBy('timestamp', 'desc')->first();
} else { } else {
$latestRecord = self::orderBy('timestamp', 'desc')->first(); $latestRecord = self::query()->orderBy('timestamp', 'desc')->first();
} }
if (! $latestRecord) { if (! $latestRecord) {
return false; return false;
} }
$currentTime = Carbon::now('UTC'); $currentTime = Date::now('UTC');
$lastRecordTime = Carbon::parse($latestRecord->timestamp); $lastRecordTime = Date::parse($latestRecord->timestamp);
return $lastRecordTime->diffInMinutes($currentTime) < 5;
if ($lastRecordTime->diffInMinutes($currentTime) < 5) {
return true;
}
return false;
} }
public static function cleanMailbox(): string public static function cleanMailbox(): string

View File

@@ -2,7 +2,7 @@
namespace App\Models; namespace App\Models;
use Carbon\Carbon; use Illuminate\Support\Facades\Date;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -26,15 +26,14 @@ class Log extends Model
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
public static function deleteLogsFromDB() public static function deleteLogsFromDB(): string
{ {
$cutoff = Carbon::now('UTC')->subMonths(3)->toDateTimeString(); $cutoff = Date::now('UTC')->subMonths(3)->toDateTimeString();
$count = count(self::where('created_at', '<', $cutoff) $count = count(self::query()->where('created_at', '<', $cutoff)->latest()
->orderBy('created_at', 'desc')
->get()); ->get());
if ($count > 0) { if ($count > 0) {
self::where('created_at', '<', $cutoff)->delete(); self::query()->where('created_at', '<', $cutoff)->delete();
return "$count old log(s) deleted from the database."; return "$count old log(s) deleted from the database.";
} }

View File

@@ -2,6 +2,7 @@
namespace App\Models; namespace App\Models;
use DateTimeImmutable;
use App\ColorPicker; use App\ColorPicker;
use Carbon\Carbon; use Carbon\Carbon;
use DateTime; use DateTime;
@@ -34,21 +35,19 @@ class Message extends Model
$message->subject = $request->subject; $message->subject = $request->subject;
$message->from = $request->from; $message->from = $request->from;
$message->to = $request->to; $message->to = $request->to;
if ($request->has('html')) { $message->body = $request->has('html') ? $request->html : $request->text;
$message->body = $request->html;
} else {
$message->body = $request->text;
}
$message->save(); $message->save();
if ($request->has('content-ids')) { if ($request->has('content-ids')) {
$message->attachments = $request->get('attachment-info'); $message->attachments = $request->get('attachment-info');
$message->save(); $message->save();
$directory = './attachments/'.$message->id; $directory = './attachments/'.$message->id;
is_dir($directory) || mkdir($directory, 0777, true); if (!is_dir($directory)) {
$attachment_ids = json_decode($request->get('attachment-info')); mkdir($directory, 0777, true);
}
$attachment_ids = json_decode((string) $request->get('attachment-info'));
foreach ($attachment_ids as $attachment_id => $attachment_info) { foreach ($attachment_ids as $attachment_id => $attachment_info) {
$allowed = explode(',', 'csv,doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt'); $allowed = explode(',', 'csv,doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt');
$file = explode('.', $attachment_info->filename); $file = explode('.', (string) $attachment_info->filename);
if (in_array($file[count($file) - 1], $allowed)) { if (in_array($file[count($file) - 1], $allowed)) {
Storage::disk('tmp')->putFileAs($directory, $request->file($attachment_id), $attachment_info->filename); Storage::disk('tmp')->putFileAs($directory, $request->file($attachment_id), $attachment_info->filename);
} }
@@ -56,48 +55,43 @@ class Message extends Model
} }
} }
public static function getMessages($email): array public static function getMessages(string $email): array
{ {
$limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15;
$messages = Message::where('to', $email)->orWhere('to', 'like', '%<'.$email.'>%')->limit($limit)->get(); $messages = Message::query()->where('to', $email)->orWhere('to', 'like', '%<'.$email.'>%')->limit($limit)->get();
$response = [ $response = [
'data' => [], 'data' => [],
'notifications' => [], 'notifications' => [],
]; ];
foreach ($messages as $message) { foreach ($messages as $message) {
$content = str_replace('<a', '<a target="blank"', $message->body); $content = str_replace('<a', '<a target="blank"', $message->body);
if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) { if (json_decode((string) config('app.settings.configuration_settings'))->enable_masking_external_link) {
$content = str_replace('href="', 'href="https://href.li/?', $content); $content = str_replace('href="', 'href="https://href.li/?', $content);
} }
$obj = []; $obj = [];
$obj['subject'] = $message->subject; $obj['subject'] = $message->subject;
$sender = explode('<', $message->from); $sender = explode('<', (string) $message->from);
$obj['sender_name'] = $sender[0]; $obj['sender_name'] = $sender[0];
if (isset($sender[1])) { $obj['sender_email'] = isset($sender[1]) ? str_replace('>', '', $sender[1]) : $obj['sender_name'];
$obj['sender_email'] = str_replace('>', '', $sender[1]);
} else {
$obj['sender_email'] = $obj['sender_name'];
}
$obj['timestamp'] = $message->created_at; $obj['timestamp'] = $message->created_at;
$obj['date'] = $message->created_at->format(json_decode(config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); $obj['date'] = $message->created_at->format(json_decode((string) config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A');
$obj['datediff'] = $message->created_at->diffForHumans(); $obj['datediff'] = $message->created_at->diffForHumans();
$obj['id'] = $message->id; $obj['id'] = $message->id;
$obj['content'] = $content; $obj['content'] = $content;
$obj['attachments'] = []; $obj['attachments'] = [];
$domain = explode('@', $obj['sender_email'])[1]; $domain = explode('@', $obj['sender_email'])[1];
$blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains);
if ($blocked) { if ($blocked) {
$obj['subject'] = __('Blocked'); $obj['subject'] = __('Blocked');
$obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin');
} }
if ($message->attachments && ! $blocked) { if ($message->attachments && ! $blocked) {
$attachments = json_decode($message->attachments); $attachments = json_decode((string) $message->attachments);
foreach ($attachments as $id => $attachment) { foreach ($attachments as $id => $attachment) {
$url = config('app.settings.app_base_url').'/tmp/attachments/'.$message->id.'/'.$attachment->filename; $url = config('app.settings.app_base_url').'/tmp/attachments/'.$message->id.'/'.$attachment->filename;
if (str_contains($obj['content'], $id)) { if (str_contains($obj['content'], (string) $id)) {
$obj['content'] = str_replace('cid:'.$id, $url, $obj['content']); $obj['content'] = str_replace('cid:'.$id, $url, $obj['content']);
} else { } elseif (Storage::disk('tmp')->exists('attachments/'.$message->id.'/'.$attachment->filename)) {
if (Storage::disk('tmp')->exists('attachments/'.$message->id.'/'.$attachment->filename)) {
$obj['attachments'][] = [ $obj['attachments'][] = [
'file' => $attachment->filename, 'file' => $attachment->filename,
'url' => $url, 'url' => $url,
@@ -105,7 +99,6 @@ class Message extends Model
} }
} }
} }
}
$response['data'][] = $obj; $response['data'][] = $obj;
if (! $message->is_seen) { if (! $message->is_seen) {
$response['notifications'][] = [ $response['notifications'][] = [
@@ -124,7 +117,7 @@ class Message extends Model
return $response; return $response;
} }
public static function fetchMessages($email, $type = 'to', $deleted = []): array public static function fetchMessages(string $email, $type = 'to', $deleted = []): array
{ {
$allowed = explode(',', 'doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt'); $allowed = explode(',', 'doc,docx,xls,xlsx,ppt,pptx,xps,pdf,dxf,ai,psd,eps,ps,svg,ttf,zip,rar,tar,gzip,mp3,mpeg,wav,ogg,jpeg,jpg,png,gif,bmp,tif,webm,mpeg4,3gpp,mov,avi,mpegs,wmv,flx,txt');
$connection = ZEmail::connectMailBox(); $connection = ZEmail::connectMailBox();
@@ -137,7 +130,7 @@ class Message extends Model
$search->addCondition(new To($email)); $search->addCondition(new To($email));
} }
$messages = $mailbox->getMessages($search, \SORTDATE, true); $messages = $mailbox->getMessages($search, \SORTDATE, true);
$limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15;
$count = 1; $count = 1;
$response = [ $response = [
'data' => [], 'data' => [],
@@ -153,7 +146,7 @@ class Message extends Model
$blocked = false; $blocked = false;
$sender = $message->getFrom(); $sender = $message->getFrom();
$date = $message->getDate(); $date = $message->getDate();
if (! $date) { if (!$date instanceof DateTimeImmutable) {
$date = new DateTime; $date = new DateTime;
if ($message->getHeaders()->get('udate')) { if ($message->getHeaders()->get('udate')) {
$date->setTimestamp($message->getHeaders()->get('udate')); $date->setTimestamp($message->getHeaders()->get('udate'));
@@ -172,7 +165,7 @@ class Message extends Model
} else { } else {
$content = str_replace('<a', '<a target="blank"', str_replace(["\r\n", "\n"], '<br/>', $text)); $content = str_replace('<a', '<a target="blank"', str_replace(["\r\n", "\n"], '<br/>', $text));
} }
if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) { if (json_decode((string) config('app.settings.configuration_settings'))->enable_masking_external_link) {
$content = str_replace('href="', 'href="http://href.li/?', $content); $content = str_replace('href="', 'href="http://href.li/?', $content);
} }
$obj = []; $obj = [];
@@ -180,18 +173,18 @@ class Message extends Model
$obj['sender_name'] = $sender->getName(); $obj['sender_name'] = $sender->getName();
$obj['sender_email'] = $sender->getAddress(); $obj['sender_email'] = $sender->getAddress();
$obj['timestamp'] = $message->getDate(); $obj['timestamp'] = $message->getDate();
$obj['date'] = $date->format(json_decode(config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); $obj['date'] = $date->format(json_decode((string) config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A');
$obj['datediff'] = $datediff->diffForHumans(); $obj['datediff'] = $datediff->diffForHumans();
$obj['id'] = $message->getNumber(); $obj['id'] = $message->getNumber();
$obj['content'] = $content; $obj['content'] = $content;
$obj['contentText'] = $contentText; $obj['contentText'] = $contentText;
$obj['attachments'] = []; $obj['attachments'] = [];
$obj['is_seen'] = true; $obj['is_seen'] = true;
$obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: $sender->getAddress(), 0, 1))); $obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: (string) $sender->getAddress(), 0, 1)));
// Checking if Sender is Blocked // Checking if Sender is Blocked
$domain = explode('@', $obj['sender_email'])[1]; $domain = explode('@', (string) $obj['sender_email'])[1];
$blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains);
if ($blocked) { if ($blocked) {
$obj['subject'] = __('Blocked'); $obj['subject'] = __('Blocked');
$obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin');
@@ -200,9 +193,11 @@ class Message extends Model
if ($message->hasAttachments() && ! $blocked) { if ($message->hasAttachments() && ! $blocked) {
$attachments = $message->getAttachments(); $attachments = $message->getAttachments();
$directory = './tmp/attachments/'.$obj['id'].'/'; $directory = './tmp/attachments/'.$obj['id'].'/';
is_dir($directory) || mkdir($directory, 0777, true); if (!is_dir($directory)) {
mkdir($directory, 0777, true);
}
foreach ($attachments as $attachment) { foreach ($attachments as $attachment) {
$filenameArray = explode('.', $attachment->getFilename()); $filenameArray = explode('.', (string) $attachment->getFilename());
$extension = $filenameArray[count($filenameArray) - 1]; $extension = $filenameArray[count($filenameArray) - 1];
if (in_array($extension, $allowed)) { if (in_array($extension, $allowed)) {
if (! file_exists($directory.$attachment->getFilename())) { if (! file_exists($directory.$attachment->getFilename())) {
@@ -218,7 +213,7 @@ class Message extends Model
if ($attachment->getFilename() !== 'undefined') { if ($attachment->getFilename() !== 'undefined') {
$url = config('app.settings.app_base_url').str_replace('./', '/', $directory.$attachment->getFilename()); $url = config('app.settings.app_base_url').str_replace('./', '/', $directory.$attachment->getFilename());
$structure = $attachment->getStructure(); $structure = $attachment->getStructure();
if (isset($structure->id) && str_contains($obj['content'], trim($structure->id, '<>'))) { if (isset($structure->id) && str_contains((string) $obj['content'], trim($structure->id, '<>'))) {
$obj['content'] = str_replace('cid:'.trim($structure->id, '<>'), $url, $obj['content']); $obj['content'] = str_replace('cid:'.trim($structure->id, '<>'), $url, $obj['content']);
} }
$obj['attachments'][] = [ $obj['attachments'][] = [

View File

@@ -14,9 +14,9 @@ class Meta extends Model
'value', 'value',
]; ];
public function incrementMeta($value = 1) public function incrementMeta($value = 1): bool
{ {
$this->value = $this->value + $value; $this->value += $value;
$this->save(); $this->save();
return true; return true;
@@ -24,7 +24,7 @@ class Meta extends Model
public static function incrementEmailIdsCreated($value = 1): bool public static function incrementEmailIdsCreated($value = 1): bool
{ {
$meta = Meta::where('key', 'email_ids_created')->first(); $meta = Meta::query()->where('key', 'email_ids_created')->first();
if ($meta) { if ($meta) {
$meta->incrementMeta($value); $meta->incrementMeta($value);
@@ -36,7 +36,7 @@ class Meta extends Model
public static function incrementMessagesReceived($value = 1): bool public static function incrementMessagesReceived($value = 1): bool
{ {
$meta = Meta::where('key', 'messages_received')->first(); $meta = Meta::query()->where('key', 'messages_received')->first();
if ($meta) { if ($meta) {
$meta->incrementMeta($value); $meta->incrementMeta($value);
@@ -48,7 +48,7 @@ class Meta extends Model
public static function getEmailIdsCreated() public static function getEmailIdsCreated()
{ {
$meta = Meta::where('key', 'email_ids_created')->first(); $meta = Meta::query()->where('key', 'email_ids_created')->first();
if ($meta) { if ($meta) {
return $meta->value; return $meta->value;
} }
@@ -58,7 +58,7 @@ class Meta extends Model
public static function getMessagesReceived() public static function getMessagesReceived()
{ {
$meta = Meta::where('key', 'messages_received')->first(); $meta = Meta::query()->where('key', 'messages_received')->first();
if ($meta) { if ($meta) {
return $meta->value; return $meta->value;
} }

View File

@@ -2,6 +2,9 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use DateTimeImmutable;
use Illuminate\Support\Facades\Log;
use App\ColorPicker; use App\ColorPicker;
use Carbon\Carbon; use Carbon\Carbon;
use DateTime; use DateTime;
@@ -13,15 +16,16 @@ use Exception;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie; use Illuminate\Support\Facades\Cookie;
use Log;
class Premium extends Model class Premium extends Model
{ {
use HasFactory;
use HasFactory;
use ColorPicker; use ColorPicker;
public static function connectMailBox($imap = null): ConnectionInterface public static function connectMailBox($imap = null): ConnectionInterface
{ {
$imapDB = json_decode(config('app.settings.imap_settings'), true); $imapDB = json_decode((string) config('app.settings.imap_settings'), true);
$imap = [ $imap = [
'host' => $imapDB['premium_host'], 'host' => $imapDB['premium_host'],
'port' => $imapDB['premium_port'], 'port' => $imapDB['premium_port'],
@@ -37,7 +41,7 @@ class Premium extends Model
return ZEmail::connectMailBox($imap); return ZEmail::connectMailBox($imap);
} }
public static function fetchMessages($email, $type = 'to', $deleted = []): array public static function fetchMessages(?string $email, $type = 'to', $deleted = []): array
{ {
if ($email == null) { if ($email == null) {
return [ return [
@@ -56,7 +60,7 @@ class Premium extends Model
$search->addCondition(new To($email)); $search->addCondition(new To($email));
} }
$messages = $mailbox->getMessages($search, \SORTDATE, true); $messages = $mailbox->getMessages($search, \SORTDATE, true);
$limit = json_decode(config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15; $limit = json_decode((string) config('app.settings.configuration_settings'))->fetch_messages_limit ?? 15;
$count = 1; $count = 1;
$response = [ $response = [
'data' => [], 'data' => [],
@@ -71,7 +75,7 @@ class Premium extends Model
$blocked = false; $blocked = false;
$sender = $message->getFrom(); $sender = $message->getFrom();
$date = $message->getDate(); $date = $message->getDate();
if (! $date) { if (!$date instanceof DateTimeImmutable) {
$date = new DateTime; $date = new DateTime;
if ($message->getHeaders()->get('udate')) { if ($message->getHeaders()->get('udate')) {
$date->setTimestamp($message->getHeaders()->get('udate')); $date->setTimestamp($message->getHeaders()->get('udate'));
@@ -90,7 +94,7 @@ class Premium extends Model
} else { } else {
$content = str_replace('<a', '<a target="blank"', str_replace(["\r\n", "\n"], '<br/>', $text)); $content = str_replace('<a', '<a target="blank"', str_replace(["\r\n", "\n"], '<br/>', $text));
} }
if (json_decode(config('app.settings.configuration_settings'))->enable_masking_external_link) { if (json_decode((string) config('app.settings.configuration_settings'))->enable_masking_external_link) {
$content = str_replace('href="', 'href="http://href.li/?', $content); $content = str_replace('href="', 'href="http://href.li/?', $content);
} }
@@ -99,7 +103,7 @@ class Premium extends Model
$obj['sender_name'] = $sender->getName(); $obj['sender_name'] = $sender->getName();
$obj['sender_email'] = $sender->getAddress(); $obj['sender_email'] = $sender->getAddress();
$obj['timestamp'] = $message->getDate(); $obj['timestamp'] = $message->getDate();
$obj['date'] = $date->format(json_decode(config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A'); $obj['date'] = $date->format(json_decode((string) config('app.settings.configuration_settings'))->date_format ?? 'd M Y h:i A');
$obj['datediff'] = $datediff->diffForHumans(); $obj['datediff'] = $datediff->diffForHumans();
$obj['id'] = $message->getNumber(); $obj['id'] = $message->getNumber();
$obj['size'] = $message->getSize(); $obj['size'] = $message->getSize();
@@ -107,11 +111,11 @@ class Premium extends Model
$obj['contentText'] = $contentText; $obj['contentText'] = $contentText;
$obj['attachments'] = []; $obj['attachments'] = [];
$obj['is_seen'] = true; $obj['is_seen'] = true;
$obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: $sender->getAddress(), 0, 1))); $obj['sender_photo'] = self::chooseColor(strtoupper(substr($sender->getName() ?: (string) $sender->getAddress(), 0, 1)));
// Checking if Sender is Blocked // Checking if Sender is Blocked
$domain = explode('@', $obj['sender_email'])[1]; $domain = explode('@', (string) $obj['sender_email'])[1];
$blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains);
if ($blocked) { if ($blocked) {
$obj['subject'] = __('Blocked'); $obj['subject'] = __('Blocked');
$obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin');
@@ -120,9 +124,11 @@ class Premium extends Model
if ($message->hasAttachments() && ! $blocked) { if ($message->hasAttachments() && ! $blocked) {
$attachments = $message->getAttachments(); $attachments = $message->getAttachments();
$directory = './tmp/premium/attachments/'.$obj['id'].'/'; $directory = './tmp/premium/attachments/'.$obj['id'].'/';
is_dir($directory) || mkdir($directory, 0777, true); if (!is_dir($directory)) {
mkdir($directory, 0777, true);
}
foreach ($attachments as $attachment) { foreach ($attachments as $attachment) {
$filenameArray = explode('.', $attachment->getFilename()); $filenameArray = explode('.', (string) $attachment->getFilename());
$extension = $filenameArray[count($filenameArray) - 1]; $extension = $filenameArray[count($filenameArray) - 1];
if (in_array($extension, $allowed)) { if (in_array($extension, $allowed)) {
if (! file_exists($directory.$attachment->getFilename())) { if (! file_exists($directory.$attachment->getFilename())) {
@@ -132,13 +138,13 @@ class Premium extends Model
$attachment->getDecodedContent() $attachment->getDecodedContent()
); );
} catch (Exception $e) { } catch (Exception $e) {
\Illuminate\Support\Facades\Log::error($e->getMessage()); Log::error($e->getMessage());
} }
} }
if ($attachment->getFilename() !== 'undefined') { if ($attachment->getFilename() !== 'undefined') {
$url = config('app.settings.app_base_url').str_replace('./', '/', $directory.$attachment->getFilename()); $url = config('app.settings.app_base_url').str_replace('./', '/', $directory.$attachment->getFilename());
$structure = $attachment->getStructure(); $structure = $attachment->getStructure();
if (isset($structure->id) && str_contains($obj['content'], trim($structure->id, '<>'))) { if (isset($structure->id) && str_contains((string) $obj['content'], trim($structure->id, '<>'))) {
$obj['content'] = str_replace('cid:'.trim($structure->id, '<>'), $url, $obj['content']); $obj['content'] = str_replace('cid:'.trim($structure->id, '<>'), $url, $obj['content']);
} }
$obj['attachments'][] = [ $obj['attachments'][] = [
@@ -172,12 +178,12 @@ class Premium extends Model
return $response; return $response;
} }
public static function getMessages($email, $type = 'to', $deleted = []): array public static function getMessages(?string $email, $type = 'to', $deleted = []): array
{ {
return self::fetchMessages($email, $type, $deleted); return self::fetchMessages($email, $type, $deleted);
} }
public static function deleteMessage($id): void public static function deleteMessage(int $id): void
{ {
$connection = self::connectMailBox(); $connection = self::connectMailBox();
$mailbox = $connection->getMailbox('INBOX'); $mailbox = $connection->getMailbox('INBOX');
@@ -189,18 +195,16 @@ class Premium extends Model
{ {
if (Cookie::has('p_email')) { if (Cookie::has('p_email')) {
return Cookie::get('p_email'); return Cookie::get('p_email');
} else {
return $generate ? self::generateRandomEmail() : null;
} }
return $generate ? self::generateRandomEmail() : null;
} }
public static function getEmails() public static function getEmails()
{ {
if (Cookie::has('p_emails')) { if (Cookie::has('p_emails')) {
return unserialize(Cookie::get('p_emails')); return unserialize(Cookie::get('p_emails'));
} else {
return [];
} }
return [];
} }
public static function setEmail($email): void public static function setEmail($email): void
@@ -213,7 +217,7 @@ class Premium extends Model
public static function setEmailP($email): void public static function setEmailP($email): void
{ {
$usageLogs = UsageLog::where(['user_id' => auth()->user()->id])->first(); $usageLogs = UsageLog::query()->where(['user_id' => auth()->user()->id])->first();
$emails = $usageLogs->emails_created_history; $emails = $usageLogs->emails_created_history;
if (is_array($emails) && in_array($email, $emails)) { if (is_array($emails) && in_array($email, $emails)) {
Cookie::queue('p_email', $email, 43800); Cookie::queue('p_email', $email, 43800);
@@ -238,9 +242,9 @@ class Premium extends Model
public static function createCustomEmailFull($email): string public static function createCustomEmailFull($email): string
{ {
$data = explode('@', $email); $data = explode('@', (string) $email);
$username = $data[0]; $username = $data[0];
if (strlen($username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { if (strlen($username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) {
$zemail = new Premium; $zemail = new Premium;
$username = $zemail->generateRandomUsername(); $username = $zemail->generateRandomUsername();
} }
@@ -249,11 +253,11 @@ class Premium extends Model
return self::createCustomEmail($username, $domain); return self::createCustomEmail($username, $domain);
} }
public static function createCustomEmail($username, $domain): string public static function createCustomEmail($username, string $domain): string
{ {
$username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower($username)); $username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower((string) $username));
$settings = json_decode(config('app.settings.configuration_settings'), true); $settings = json_decode((string) config('app.settings.configuration_settings'), true);
$forbidden_ids = $settings['forbidden_ids'] ?? []; $forbidden_ids = $settings['forbidden_ids'] ?? [];
$gmail_usernames = $settings['premium_gmailUsernames'] ?? []; $gmail_usernames = $settings['premium_gmailUsernames'] ?? [];
$outlook_usernames = $settings['premium_outlookUsernames'] ?? []; $outlook_usernames = $settings['premium_outlookUsernames'] ?? [];
@@ -267,7 +271,7 @@ class Premium extends Model
return self::generateRandomGmail(true); return self::generateRandomGmail(true);
} }
if ($username === '' && in_array($domain, ['outlook.com'])) { if ($username === '' && $domain === 'outlook.com') {
return self::generateRandomOutlook(true); return self::generateRandomOutlook(true);
} }
@@ -277,9 +281,9 @@ class Premium extends Model
return $zemail->generateRandomUsername().'@'.$domain; return $zemail->generateRandomUsername().'@'.$domain;
} }
if (in_array($domain, ['outlook.com'])) { if ($domain === 'outlook.com') {
if (str_contains($username, '+')) { if (str_contains((string) $username, '+')) {
[$check_username, $post_username] = explode('+', $username, 2); [$check_username, $post_username] = explode('+', (string) $username, 2);
if (in_array($check_username, $outlook_usernames)) { if (in_array($check_username, $outlook_usernames)) {
$email = $username.'@'.$domain; $email = $username.'@'.$domain;
@@ -295,8 +299,8 @@ class Premium extends Model
} }
if (in_array($domain, ['gmail.com', 'googlemail.com'])) { if (in_array($domain, ['gmail.com', 'googlemail.com'])) {
if (str_contains($username, '+')) { if (str_contains((string) $username, '+')) {
[$check_username, $post_username] = explode('+', $username, 2); [$check_username, $post_username] = explode('+', (string) $username, 2);
if (in_array($check_username, $gmail_usernames)) { if (in_array($check_username, $gmail_usernames)) {
$email = $username.'@'.$domain; $email = $username.'@'.$domain;
@@ -304,7 +308,7 @@ class Premium extends Model
$email = $zemail->getRandomGmailUser().'+'.$post_username.'@'.$domain; $email = $zemail->getRandomGmailUser().'+'.$post_username.'@'.$domain;
} }
} elseif (str_contains($username, '.')) { } elseif (str_contains((string) $username, '.')) {
$check_username = str_replace('.', '', $username); $check_username = str_replace('.', '', $username);
if (in_array($check_username, $gmail_usernames)) { if (in_array($check_username, $gmail_usernames)) {
@@ -341,14 +345,14 @@ class Premium extends Model
$domain = $zemail->getRandomDomain(); $domain = $zemail->getRandomDomain();
if ($domain == 'gmail.com') { if ($domain == 'gmail.com') {
$rd = mt_rand(0, 1); $rd = mt_rand(0, 1);
if ($rd == 0) { if ($rd === 0) {
$email = $zemail->generateRandomGmail(false); $email = $zemail->generateRandomGmail(false);
} else { } else {
$email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@gmail.com'; $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@gmail.com';
} }
} elseif ($domain == 'googlemail.com') { } elseif ($domain == 'googlemail.com') {
$rd = mt_rand(0, 1); $rd = mt_rand(0, 1);
if ($rd == 0) { if ($rd === 0) {
$email = $zemail->generateRandomGmail(false); $email = $zemail->generateRandomGmail(false);
} else { } else {
$email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@googlemail.com'; $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@googlemail.com';
@@ -369,11 +373,11 @@ class Premium extends Model
{ {
$zemail = new Premium; $zemail = new Premium;
$uname = $zemail->getRandomGmailUser(); $uname = $zemail->getRandomGmailUser();
$uname_len = strlen($uname); $uname_len = strlen((string) $uname);
$len_power = $uname_len - 1; $len_power = $uname_len - 1;
$combination = pow(2, $len_power); $combination = 2 ** $len_power;
$rand_comb = mt_rand(1, $combination); mt_rand(1, $combination);
$formatted = implode(' ', str_split($uname)); $formatted = implode(' ', str_split((string) $uname));
$uname_exp = explode(' ', $formatted); $uname_exp = explode(' ', $formatted);
$bin = intval(''); $bin = intval('');
@@ -385,7 +389,7 @@ class Premium extends Model
$email = ''; $email = '';
for ($i = 0; $i < $len_power; $i++) { for ($i = 0; $i < $len_power; $i++) {
$email .= $uname_exp[$i]; $email .= $uname_exp[$i];
if ($bin[$i]) { if ($bin[$i] !== '' && $bin[$i] !== '0') {
$email .= '.'; $email .= '.';
} }
} }
@@ -414,7 +418,7 @@ class Premium extends Model
return $email; return $email;
} }
private static function storeEmail($email): void private static function storeEmail(string $email): void
{ {
Log::create([ Log::create([
'user_id' => auth()->user()->id, 'user_id' => auth()->user()->id,
@@ -447,8 +451,8 @@ class Premium extends Model
private function generateRandomUsername(): string private function generateRandomUsername(): string
{ {
$start = json_decode(config('app.settings.configuration_settings'))->random_username_length_min ?? 0; $start = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_min ?? 0;
$end = json_decode(config('app.settings.configuration_settings'))->random_username_length_max ?? 0; $end = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_max ?? 0;
if ($start == 0 && $end == 0) { if ($start == 0 && $end == 0) {
return $this->generatePronounceableWord(); return $this->generatePronounceableWord();
} }
@@ -458,33 +462,33 @@ class Premium extends Model
protected function generatedRandomBetweenLength($start, $end): string protected function generatedRandomBetweenLength($start, $end): string
{ {
$length = rand($start, $end); $length = random_int($start, $end);
return $this->generateRandomString($length); return $this->generateRandomString($length);
} }
private function getRandomDomain() private function getRandomDomain()
{ {
$domains = json_decode(config('app.settings.configuration_settings'))->premium_domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->premium_domains ?? [];
$count = count($domains); $count = count($domains);
return $count > 0 ? $domains[rand(1, $count) - 1] : ''; return $count > 0 ? $domains[random_int(1, $count) - 1] : '';
} }
private function getRandomGmailUser() private function getRandomGmailUser()
{ {
$gmailusername = json_decode(config('app.settings.configuration_settings'))->premium_gmailUsernames ?? []; $gmailusername = json_decode((string) config('app.settings.configuration_settings'))->premium_gmailUsernames ?? [];
$count = count($gmailusername); $count = count($gmailusername);
return $count > 0 ? $gmailusername[rand(1, $count) - 1] : ''; return $count > 0 ? $gmailusername[random_int(1, $count) - 1] : '';
} }
private function getRandomOutlookUser() private function getRandomOutlookUser()
{ {
$outlook_username = json_decode(config('app.settings.configuration_settings'))->premium_outlookUsernames ?? []; $outlook_username = json_decode((string) config('app.settings.configuration_settings'))->premium_outlookUsernames ?? [];
$count = count($outlook_username); $count = count($outlook_username);
return $count > 0 ? $outlook_username[rand(1, $count) - 1] : ''; return $count > 0 ? $outlook_username[random_int(1, $count) - 1] : '';
} }
private function generatePronounceableWord(): string private function generatePronounceableWord(): string
@@ -494,21 +498,21 @@ class Premium extends Model
$a = $c.$v; // both $a = $c.$v; // both
$random = ''; $random = '';
for ($j = 0; $j < 2; $j++) { for ($j = 0; $j < 2; $j++) {
$random .= $c[rand(0, strlen($c) - 1)]; $random .= $c[random_int(0, strlen($c) - 1)];
$random .= $v[rand(0, strlen($v) - 1)]; $random .= $v[random_int(0, strlen($v) - 1)];
$random .= $a[rand(0, strlen($a) - 1)]; $random .= $a[random_int(0, strlen($a) - 1)];
} }
return $random; return $random;
} }
private function generateRandomString($length = 10): string private function generateRandomString(int $length = 10): string
{ {
$characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters); $charactersLength = strlen($characters);
$randomString = ''; $randomString = '';
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)]; $randomString .= $characters[random_int(0, $charactersLength - 1)];
} }
return $randomString; return $randomString;
@@ -524,10 +528,7 @@ class Premium extends Model
return; return;
} }
$usageLog = UsageLog::firstOrCreate( $usageLog = UsageLog::query()->firstOrCreate(['user_id' => $user->id], ['ip_address' => request()->ip()]);
['user_id' => $user->id],
['ip_address' => request()->ip()]
);
$usageLog->increment('emails_created_count', $count); $usageLog->increment('emails_created_count', $count);
} }
@@ -539,10 +540,7 @@ class Premium extends Model
return; return;
} }
$usageLog = UsageLog::firstOrCreate( $usageLog = UsageLog::query()->firstOrCreate(['user_id' => $user->id], ['ip_address' => request()->ip()]);
['user_id' => $user->id],
['ip_address' => request()->ip()]
);
$usageLog->increment('emails_received_count', $count); $usageLog->increment('emails_received_count', $count);
} }
@@ -556,10 +554,7 @@ class Premium extends Model
} }
$ip = request()->ip(); $ip = request()->ip();
$usageLog = UsageLog::firstOrCreate( $usageLog = UsageLog::query()->firstOrCreate(['user_id' => $user->id], ['ip_address' => $ip]);
['user_id' => $user->id],
['ip_address' => $ip]
);
$history = $usageLog->emails_created_history ?? []; $history = $usageLog->emails_created_history ?? [];
if (! in_array($email, $history)) { if (! in_array($email, $history)) {

View File

@@ -2,8 +2,8 @@
namespace App\Models; namespace App\Models;
use Illuminate\Support\Facades\Date;
use App\ColorPicker; use App\ColorPicker;
use Carbon\Carbon;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -48,7 +48,7 @@ class PremiumEmail extends Model
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
public static function createEmail($message, $email): void public static function createEmail(array $message, $email): void
{ {
$initialData = $message; $initialData = $message;
if (config('app.fetch_from_db') && config('app.fetch_from_remote_db')) { if (config('app.fetch_from_db') && config('app.fetch_from_remote_db')) {
@@ -56,9 +56,9 @@ class PremiumEmail extends Model
} else { } else {
$utcTime = CarbonImmutable::instance($message['timestamp'])->setTimezone('UTC')->toDateTimeString(); $utcTime = CarbonImmutable::instance($message['timestamp'])->setTimezone('UTC')->toDateTimeString();
} }
$messageId = Carbon::parse($utcTime)->format('Ymd').$initialData['id']; $messageId = Date::parse($utcTime)->format('Ymd').$initialData['id'];
$userId = \auth()->user()->id; $userId = \auth()->user()->id;
$exists = PremiumEmail::where('user_id', $userId)->where('message_id', $messageId)->exists(); $exists = PremiumEmail::query()->where('user_id', $userId)->where('message_id', $messageId)->exists();
$data = [ $data = [
'user_id' => $userId, 'user_id' => $userId,
@@ -82,7 +82,7 @@ class PremiumEmail extends Model
]; ];
if (! $exists) { if (! $exists) {
PremiumEmail::create($data); PremiumEmail::query()->create($data);
} }
} }
@@ -90,14 +90,14 @@ class PremiumEmail extends Model
{ {
$validator = Validator::make(['user_id' => $userId], [ $validator = Validator::make(['user_id' => $userId], [
'user_id' => 'required|integer', 'user_id' => ['required', 'integer'],
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return []; return [];
} }
return self::whereJsonContains('user_id', $userId)->orderBy('timestamp', 'desc')->get(); return self::query()->whereJsonContains('user_id', $userId)->orderBy('timestamp', 'desc')->get();
} }
public static function parseEmail($userId, $deleted = []): array public static function parseEmail($userId, $deleted = []): array
@@ -114,7 +114,7 @@ class PremiumEmail extends Model
if (in_array($message['message_id'], $deleted)) { if (in_array($message['message_id'], $deleted)) {
// If it exists, delete the matching record from the 'emails' table // If it exists, delete the matching record from the 'emails' table
Email::where('message_id', $message['message_id'])->delete(); Email::query()->where('message_id', $message['message_id'])->delete();
continue; continue;
} }
@@ -122,7 +122,7 @@ class PremiumEmail extends Model
$blocked = false; $blocked = false;
$timestamp = $message['timestamp']; $timestamp = $message['timestamp'];
$carbonTimestamp = Carbon::parse($timestamp, 'UTC'); $carbonTimestamp = Date::parse($timestamp, 'UTC');
$obj = []; $obj = [];
$obj['subject'] = $message['subject']; $obj['subject'] = $message['subject'];
$obj['to'] = $message['to']; $obj['to'] = $message['to'];
@@ -130,16 +130,16 @@ class PremiumEmail extends Model
$obj['sender_email'] = $message['from_email']; $obj['sender_email'] = $message['from_email'];
$obj['timestamp'] = $message['timestamp']; $obj['timestamp'] = $message['timestamp'];
$obj['date'] = $carbonTimestamp->format('d M Y h:i A'); $obj['date'] = $carbonTimestamp->format('d M Y h:i A');
$obj['datediff'] = $carbonTimestamp->diffForHumans(Carbon::now('UTC')); $obj['datediff'] = $carbonTimestamp->diffForHumans(Date::now('UTC'));
$obj['id'] = $message['message_id']; $obj['id'] = $message['message_id'];
$obj['content'] = $message['body_html']; $obj['content'] = $message['body_html'];
$obj['contentText'] = $message['body_text']; $obj['contentText'] = $message['body_text'];
$obj['attachments'] = []; $obj['attachments'] = [];
$obj['is_seen'] = $message['is_seen']; $obj['is_seen'] = $message['is_seen'];
$obj['sender_photo'] = self::chooseColor(strtoupper(substr($message['from_name'] ?: $message['from_email'], 0, 1))); $obj['sender_photo'] = self::chooseColor(strtoupper(substr((string) $message['from_name'] ?: (string) $message['from_email'], 0, 1)));
$domain = explode('@', $obj['sender_email'])[1]; $domain = explode('@', (string) $obj['sender_email'])[1];
$blocked = in_array($domain, json_decode(config('app.settings.configuration_settings'))->blocked_domains); $blocked = in_array($domain, json_decode((string) config('app.settings.configuration_settings'))->blocked_domains);
if ($blocked) { if ($blocked) {
$obj['subject'] = __('Blocked'); $obj['subject'] = __('Blocked');
$obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin'); $obj['content'] = __('Emails from').' '.$domain.' '.__('are blocked by Admin');
@@ -162,7 +162,7 @@ class PremiumEmail extends Model
file_put_contents(storage_path('logs/zemail.csv'), request()->ip().','.date('Y-m-d h:i:s a').','.$obj['sender_email'].','.$email.PHP_EOL, FILE_APPEND); file_put_contents(storage_path('logs/zemail.csv'), request()->ip().','.date('Y-m-d h:i:s a').','.$obj['sender_email'].','.$email.PHP_EOL, FILE_APPEND);
} }
} }
PremiumEmail::where('message_id', $message['message_id'])->update(['is_seen' => true]); PremiumEmail::query()->where('message_id', $message['message_id'])->update(['is_seen' => true]);
if (++$count > $limit) { if (++$count > $limit) {
break; break;
} }

View File

@@ -42,13 +42,13 @@ class RemoteEmail extends Model
public static function fetchEmailFromDB($email) public static function fetchEmailFromDB($email)
{ {
$validator = Validator::make(['email' => $email], [ $validator = Validator::make(['email' => $email], [
'email' => 'required|email', 'email' => ['required', 'email'],
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return []; return [];
} }
return self::whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get(); return self::query()->whereJsonContains('to', $email)->orderBy('timestamp', 'desc')->get();
} }
} }

View File

@@ -2,7 +2,6 @@
namespace App\Models; namespace App\Models;
use Carbon\Carbon;
use Exception; use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -20,7 +19,7 @@ class Ticket extends Model
{ {
parent::boot(); parent::boot();
static::creating(function ($ticket) { static::creating(function ($ticket): void {
if (empty($ticket->ticket_id)) { if (empty($ticket->ticket_id)) {
$ticket->ticket_id = 'TICKET-'.strtoupper(Str::random(6)); $ticket->ticket_id = 'TICKET-'.strtoupper(Str::random(6));
} }
@@ -46,7 +45,7 @@ class Ticket extends Model
public static function autoClose(): bool public static function autoClose(): bool
{ {
try { try {
$tickets = Ticket::where('status', 'pending') $tickets = Ticket::query()->where('status', 'pending')
->where('last_response_at', '<', now()->subDays(3)) ->where('last_response_at', '<', now()->subDays(3))
->get(); ->get();
if (count($tickets) > 0) { if (count($tickets) > 0) {
@@ -54,7 +53,7 @@ class Ticket extends Model
$ticket->status = 'closed'; $ticket->status = 'closed';
$ticket->save(); $ticket->save();
TicketResponse::create([ TicketResponse::query()->create([
'ticket_id' => $ticket->id, 'ticket_id' => $ticket->id,
'user_id' => 1, 'user_id' => 1,
'response' => 'This ticket has been auto-closed due to inactivity.', 'response' => 'This ticket has been auto-closed due to inactivity.',
@@ -63,7 +62,7 @@ class Ticket extends Model
} }
return true; return true;
} catch (Exception $e) { } catch (Exception) {
return false; return false;
} }

View File

@@ -2,8 +2,8 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Ddeboer\Imap\ConnectionInterface; use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\Search\Email\To;
use Ddeboer\Imap\Server; use Ddeboer\Imap\Server;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cookie; use Illuminate\Support\Facades\Cookie;
@@ -12,23 +12,21 @@ use function str_replace;
class ZEmail extends Model class ZEmail extends Model
{ {
use HasFactory;
use HasFactory;
public static function connectMailBox($imap = null): ConnectionInterface public static function connectMailBox($imap = null): ConnectionInterface
{ {
if ($imap === null) { if ($imap === null) {
$imap = json_decode(config('app.settings.imap_settings'), true); $imap = json_decode((string) config('app.settings.imap_settings'), true);
} }
$flags = $imap['protocol'].'/'.$imap['encryption']; $flags = $imap['protocol'].'/'.$imap['encryption'];
if ($imap['validate_cert']) { $flags = $imap['validate_cert'] ? $flags.'/validate-cert' : $flags.'/novalidate-cert';
$flags = $flags.'/validate-cert';
} else {
$flags = $flags.'/novalidate-cert';
}
$server = new Server($imap['host'], $imap['port'], $flags); $server = new Server($imap['host'], $imap['port'], $flags);
return $server->authenticate($imap['username'], $imap['password']); return $server->authenticate($imap['username'], $imap['password']);
} }
public static function getMessages($email, $type = 'to', $deleted = []): array public static function getMessages(string $email, $type = 'to', $deleted = []): array
{ {
if (config('app.beta_feature')) { if (config('app.beta_feature')) {
return Message::getMessages($email); return Message::getMessages($email);
@@ -39,15 +37,14 @@ class ZEmail extends Model
if (config('app.fetch_from_db')) { if (config('app.fetch_from_db')) {
if (Email::mailToDBStatus()) { if (Email::mailToDBStatus()) {
return Email::parseEmail($email, $deleted); return Email::parseEmail($email, $deleted);
} else {
return Message::fetchMessages($email, $type, $deleted);
} }
return Message::fetchMessages($email, $type, $deleted);
} }
return Message::fetchMessages($email, $type, $deleted); return Message::fetchMessages($email, $type, $deleted);
} }
public static function deleteMessage($id): void public static function deleteMessage(int $id): void
{ {
$connection = ZEmail::connectMailBox(); $connection = ZEmail::connectMailBox();
$mailbox = $connection->getMailbox('INBOX'); $mailbox = $connection->getMailbox('INBOX');
@@ -59,18 +56,16 @@ class ZEmail extends Model
{ {
if (Cookie::has('email')) { if (Cookie::has('email')) {
return Cookie::get('email'); return Cookie::get('email');
} else {
return $generate ? ZEmail::generateRandomEmail() : null;
} }
return $generate ? ZEmail::generateRandomEmail() : null;
} }
public static function getEmails() public static function getEmails()
{ {
if (Cookie::has('emails')) { if (Cookie::has('emails')) {
return unserialize(Cookie::get('emails')); return unserialize(Cookie::get('emails'));
} else {
return [];
} }
return [];
} }
public static function setEmail($email): void public static function setEmail($email): void
@@ -99,9 +94,9 @@ class ZEmail extends Model
public static function createCustomEmailFull($email): string public static function createCustomEmailFull($email): string
{ {
$data = explode('@', $email); $data = explode('@', (string) $email);
$username = $data[0]; $username = $data[0];
if (strlen($username) < json_decode(config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode(config('app.settings.configuration_settings'))->custom_username_length_max) { if (strlen($username) < json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_min || strlen($username) > json_decode((string) config('app.settings.configuration_settings'))->custom_username_length_max) {
$zemail = new ZEmail; $zemail = new ZEmail;
$username = $zemail->generateRandomUsername(); $username = $zemail->generateRandomUsername();
} }
@@ -110,11 +105,11 @@ class ZEmail extends Model
return ZEmail::createCustomEmail($username, $domain); return ZEmail::createCustomEmail($username, $domain);
} }
public static function createCustomEmail($username, $domain): string public static function createCustomEmail($username, string $domain): string
{ {
$username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower($username)); $username = preg_replace('/[^a-zA-Z0-9+.]/', '', strtolower((string) $username));
$settings = json_decode(config('app.settings.configuration_settings'), true); $settings = json_decode((string) config('app.settings.configuration_settings'), true);
$forbidden_ids = $settings['forbidden_ids'] ?? []; $forbidden_ids = $settings['forbidden_ids'] ?? [];
$gmail_usernames = $settings['gmailUsernames'] ?? []; $gmail_usernames = $settings['gmailUsernames'] ?? [];
$outlook_usernames = $settings['outlookUsernames'] ?? []; $outlook_usernames = $settings['outlookUsernames'] ?? [];
@@ -124,7 +119,7 @@ class ZEmail extends Model
$min_length = $settings['custom_username_length_min'] ?? 3; $min_length = $settings['custom_username_length_min'] ?? 3;
$max_length = $settings['custom_username_length_max'] ?? 20; $max_length = $settings['custom_username_length_max'] ?? 20;
if (strlen($username) < $min_length || strlen($username) > $max_length) { if (strlen((string) $username) < $min_length || strlen((string) $username) > $max_length) {
$zemail = new ZEmail; $zemail = new ZEmail;
$username = $zemail->generateRandomUsername(); $username = $zemail->generateRandomUsername();
} }
@@ -137,7 +132,7 @@ class ZEmail extends Model
return ZEmail::generateRandomGmail(true); return ZEmail::generateRandomGmail(true);
} }
if ($username === '' && in_array($domain, ['outlook.com'])) { if ($username === '' && $domain === 'outlook.com') {
return ZEmail::generateRandomOutlook(true); return ZEmail::generateRandomOutlook(true);
} }
@@ -147,9 +142,9 @@ class ZEmail extends Model
return $zemail->generateRandomUsername().'@'.$domain; return $zemail->generateRandomUsername().'@'.$domain;
} }
if (in_array($domain, ['outlook.com'])) { if ($domain === 'outlook.com') {
if (str_contains($username, '+')) { if (str_contains((string) $username, '+')) {
[$check_username, $post_username] = explode('+', $username, 2); [$check_username, $post_username] = explode('+', (string) $username, 2);
if (in_array($check_username, $outlook_usernames)) { if (in_array($check_username, $outlook_usernames)) {
$email = $username.'@'.$domain; $email = $username.'@'.$domain;
@@ -165,8 +160,8 @@ class ZEmail extends Model
} }
if (in_array($domain, ['gmail.com', 'googlemail.com'])) { if (in_array($domain, ['gmail.com', 'googlemail.com'])) {
if (str_contains($username, '+')) { if (str_contains((string) $username, '+')) {
[$check_username, $post_username] = explode('+', $username, 2); [$check_username, $post_username] = explode('+', (string) $username, 2);
if (in_array($check_username, $gmail_usernames)) { if (in_array($check_username, $gmail_usernames)) {
$email = $username.'@'.$domain; $email = $username.'@'.$domain;
@@ -174,7 +169,7 @@ class ZEmail extends Model
$email = $zemail->getRandomGmailUser().'+'.$post_username.'@'.$domain; $email = $zemail->getRandomGmailUser().'+'.$post_username.'@'.$domain;
} }
} elseif (str_contains($username, '.')) { } elseif (str_contains((string) $username, '.')) {
$check_username = str_replace('.', '', $username); $check_username = str_replace('.', '', $username);
if (in_array($check_username, $gmail_usernames)) { if (in_array($check_username, $gmail_usernames)) {
@@ -211,14 +206,14 @@ class ZEmail extends Model
$domain = $zemail->getRandomDomain(); $domain = $zemail->getRandomDomain();
if ($domain == 'gmail.com') { if ($domain == 'gmail.com') {
$rd = mt_rand(0, 1); $rd = mt_rand(0, 1);
if ($rd == 0) { if ($rd === 0) {
$email = $zemail->generateRandomGmail(); $email = $zemail->generateRandomGmail();
} else { } else {
$email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@gmail.com'; $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@gmail.com';
} }
} elseif ($domain == 'googlemail.com') { } elseif ($domain == 'googlemail.com') {
$rd = mt_rand(0, 1); $rd = mt_rand(0, 1);
if ($rd == 0) { if ($rd === 0) {
$email = $zemail->generateRandomGmail(); $email = $zemail->generateRandomGmail();
} else { } else {
$email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@googlemail.com'; $email = $zemail->getRandomGmailUser().'+'.$zemail->generateRandomUsername().'@googlemail.com';
@@ -239,11 +234,11 @@ class ZEmail extends Model
{ {
$zemail = new ZEmail; $zemail = new ZEmail;
$uname = $zemail->getRandomGmailUser(); $uname = $zemail->getRandomGmailUser();
$uname_len = strlen($uname); $uname_len = strlen((string) $uname);
$len_power = $uname_len - 1; $len_power = $uname_len - 1;
$combination = pow(2, $len_power); $combination = 2 ** $len_power;
$rand_comb = mt_rand(1, $combination); mt_rand(1, $combination);
$formatted = implode(' ', str_split($uname)); $formatted = implode(' ', str_split((string) $uname));
$uname_exp = explode(' ', $formatted); $uname_exp = explode(' ', $formatted);
$bin = intval(''); $bin = intval('');
@@ -255,7 +250,7 @@ class ZEmail extends Model
$email = ''; $email = '';
for ($i = 0; $i < $len_power; $i++) { for ($i = 0; $i < $len_power; $i++) {
$email .= $uname_exp[$i]; $email .= $uname_exp[$i];
if ($bin[$i]) { if ($bin[$i] !== '' && $bin[$i] !== '0') {
$email .= '.'; $email .= '.';
} }
} }
@@ -284,9 +279,9 @@ class ZEmail extends Model
return $email; return $email;
} }
private static function storeEmail($email): void private static function storeEmail(string $email): void
{ {
Log::create([ Log::query()->create([
'ip' => request()->ip(), 'ip' => request()->ip(),
'email' => $email, 'email' => $email,
]); ]);
@@ -314,8 +309,8 @@ class ZEmail extends Model
private function generateRandomUsername(): string private function generateRandomUsername(): string
{ {
$start = json_decode(config('app.settings.configuration_settings'))->random_username_length_min ?? 0; $start = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_min ?? 0;
$end = json_decode(config('app.settings.configuration_settings'))->random_username_length_max ?? 0; $end = json_decode((string) config('app.settings.configuration_settings'))->random_username_length_max ?? 0;
if ($start == 0 && $end == 0) { if ($start == 0 && $end == 0) {
return $this->generatePronounceableWord(); return $this->generatePronounceableWord();
} }
@@ -325,34 +320,34 @@ class ZEmail extends Model
protected function generatedRandomBetweenLength($start, $end): string protected function generatedRandomBetweenLength($start, $end): string
{ {
$length = rand($start, $end); $length = random_int($start, $end);
return $this->generateRandomString($length); return $this->generateRandomString($length);
} }
private function getRandomDomain() private function getRandomDomain()
{ {
$domains = json_decode(config('app.settings.configuration_settings'))->domains ?? []; $domains = json_decode((string) config('app.settings.configuration_settings'))->domains ?? [];
$count = count($domains); $count = count($domains);
return $count > 0 ? $domains[rand(1, $count) - 1] : ''; return $count > 0 ? $domains[random_int(1, $count) - 1] : '';
} }
private function getRandomGmailUser() private function getRandomGmailUser()
{ {
$gmailusername = json_decode(config('app.settings.configuration_settings'))->gmailUsernames ?? []; $gmailusername = json_decode((string) config('app.settings.configuration_settings'))->gmailUsernames ?? [];
$count = count($gmailusername); $count = count($gmailusername);
return $count > 0 ? $gmailusername[rand(1, $count) - 1] : ''; return $count > 0 ? $gmailusername[random_int(1, $count) - 1] : '';
} }
private function getRandomOutlookUser() private function getRandomOutlookUser()
{ {
$outlook_username = json_decode(config('app.settings.configuration_settings'))->outlookUsernames ?? []; $outlook_username = json_decode((string) config('app.settings.configuration_settings'))->outlookUsernames ?? [];
$count = count($outlook_username); $count = count($outlook_username);
return $count > 0 ? $outlook_username[rand(1, $count) - 1] : ''; return $count > 0 ? $outlook_username[random_int(1, $count) - 1] : '';
} }
private function generatePronounceableWord(): string private function generatePronounceableWord(): string
@@ -362,21 +357,21 @@ class ZEmail extends Model
$a = $c.$v; // both $a = $c.$v; // both
$random = ''; $random = '';
for ($j = 0; $j < 2; $j++) { for ($j = 0; $j < 2; $j++) {
$random .= $c[rand(0, strlen($c) - 1)]; $random .= $c[random_int(0, strlen($c) - 1)];
$random .= $v[rand(0, strlen($v) - 1)]; $random .= $v[random_int(0, strlen($v) - 1)];
$random .= $a[rand(0, strlen($a) - 1)]; $random .= $a[random_int(0, strlen($a) - 1)];
} }
return $random; return $random;
} }
private function generateRandomString($length = 10): string private function generateRandomString(int $length = 10): string
{ {
$characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters); $charactersLength = strlen($characters);
$randomString = ''; $randomString = '';
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)]; $randomString .= $characters[random_int(0, $charactersLength - 1)];
} }
return $randomString; return $randomString;

View File

@@ -2,9 +2,9 @@
namespace App; namespace App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use Exception; use Exception;
use Http;
use Log;
trait NotifyMe trait NotifyMe
{ {

View File

@@ -2,10 +2,10 @@
namespace App\Providers; namespace App\Providers;
use Illuminate\Support\Facades\DB;
use App\Models\Blog; use App\Models\Blog;
use App\Models\Menu; use App\Models\Menu;
use App\Models\Plan; use App\Models\Plan;
use DB;
use Exception; use Exception;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Laravel\Cashier\Cashier; use Laravel\Cashier\Cashier;
@@ -39,27 +39,19 @@ class AppServiceProvider extends ServiceProvider
private function loadApplicationData(): void private function loadApplicationData(): void
{ {
try { try {
$settings = cache()->remember('app_settings', now()->addHours(6), function () { $settings = cache()->remember('app_settings', now()->addHours(6), fn(): array => (array) DB::table('settings')->find(1));
return (array) DB::table('settings')->find(1);
});
$menus = cache()->remember('app_menus', now()->addHours(6), function () { $menus = cache()->remember('app_menus', now()->addHours(6), Menu::all(...));
return Menu::all();
});
$blogs = cache()->remember('app_blogs', now()->addHours(6), function () { $blogs = cache()->remember('app_blogs', now()->addHours(6), fn() => Blog::query()->where('is_published', 1)->get());
return Blog::where('is_published', 1)->get();
});
$plans = cache()->remember('app_plans', now()->addHours(6), function () { $plans = cache()->remember('app_plans', now()->addHours(6), Plan::all(...));
return Plan::all();
});
config(['app.settings' => (array) $settings]); config(['app.settings' => (array) $settings]);
config(['app.menus' => $menus]); config(['app.menus' => $menus]);
config(['app.blogs' => $blogs]); config(['app.blogs' => $blogs]);
config(['app.plans' => $plans]); config(['app.plans' => $plans]);
} catch (Exception $e) { } catch (Exception) {
// Fail silently if database is not available // Fail silently if database is not available
// This allows the application to boot during migrations and testing // This allows the application to boot during migrations and testing
} }

View File

@@ -10,7 +10,6 @@ use Filament\Pages\Dashboard;
use Filament\Panel; use Filament\Panel;
use Filament\PanelProvider; use Filament\PanelProvider;
use Filament\Support\Colors\Color; use Filament\Support\Colors\Color;
use Filament\Widgets;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies; use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;

View File

@@ -1,5 +1,6 @@
<?php <?php
use App\Http\Middleware\Locale;
use Illuminate\Foundation\Application; use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Foundation\Configuration\Middleware;
@@ -11,15 +12,15 @@ return Application::configure(basePath: dirname(__DIR__))
commands: __DIR__.'/../routes/console.php', commands: __DIR__.'/../routes/console.php',
health: '/up', health: '/up',
) )
->withMiddleware(function (Middleware $middleware) { ->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [ $middleware->web(append: [
\App\Http\Middleware\Locale::class, Locale::class,
]); ]);
$middleware->validateCsrfTokens(except: [ $middleware->validateCsrfTokens(except: [
'stripe/*', 'stripe/*',
'webhook/oxapay', 'webhook/oxapay',
]); ]);
}) })
->withExceptions(function (Exceptions $exceptions) { ->withExceptions(function (Exceptions $exceptions): void {
// //
})->create(); })->create();

View File

@@ -20,6 +20,7 @@
}, },
"require-dev": { "require-dev": {
"barryvdh/laravel-debugbar": "^3.15", "barryvdh/laravel-debugbar": "^3.15",
"driftingly/rector-laravel": "^2.1",
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",
"filament/upgrade": "~4.0", "filament/upgrade": "~4.0",
"laravel/boost": "^1.7", "laravel/boost": "^1.7",

38
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "4f524140d1c67cd77b488f1510913b56", "content-hash": "4cdd6fb15d89efed5ce17b76086a103a",
"packages": [ "packages": [
{ {
"name": "anourvalar/eloquent-serialize", "name": "anourvalar/eloquent-serialize",
@@ -8999,6 +8999,42 @@
}, },
"time": "2025-04-07T20:06:18+00:00" "time": "2025-04-07T20:06:18+00:00"
}, },
{
"name": "driftingly/rector-laravel",
"version": "2.1.3",
"source": {
"type": "git",
"url": "https://github.com/driftingly/rector-laravel.git",
"reference": "2f1e9c3997bf45592d58916f0cedd775e844b9c6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/driftingly/rector-laravel/zipball/2f1e9c3997bf45592d58916f0cedd775e844b9c6",
"reference": "2f1e9c3997bf45592d58916f0cedd775e844b9c6",
"shasum": ""
},
"require": {
"php": "^7.4 || ^8.0",
"rector/rector": "^2.2.7",
"webmozart/assert": "^1.11"
},
"type": "rector-extension",
"autoload": {
"psr-4": {
"RectorLaravel\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Rector upgrades rules for Laravel Framework",
"support": {
"issues": "https://github.com/driftingly/rector-laravel/issues",
"source": "https://github.com/driftingly/rector-laravel/tree/2.1.3"
},
"time": "2025-11-04T18:32:57+00:00"
},
{ {
"name": "fakerphp/faker", "name": "fakerphp/faker",
"version": "v1.24.1", "version": "v1.24.1",

View File

@@ -33,7 +33,7 @@ return [
'fetch_from_db' => env('FETCH_FETCH_FOR_DB', false), 'fetch_from_db' => env('FETCH_FETCH_FOR_DB', false),
'fetch_from_remote_db' => env('FETCH_FROM_REMOTE_DB', false), 'fetch_from_remote_db' => env('FETCH_FROM_REMOTE_DB', false),
'force_db_mail' => env('FORCE_DB_MAIL', false), 'force_db_mail' => env('FORCE_DB_MAIL', false),
'move_or_delete' => env('MOVE_OR_DELETE', null), 'move_or_delete' => env('MOVE_OR_DELETE'),
'auto_fetch_mail' => env('AUTO_FETCH_MAIL', false), 'auto_fetch_mail' => env('AUTO_FETCH_MAIL', false),
'notify_tg_bot_token' => env('NOTIFY_TG_BOT_TOKEN', ''), 'notify_tg_bot_token' => env('NOTIFY_TG_BOT_TOKEN', ''),
@@ -114,7 +114,7 @@ return [
'previous_keys' => [ 'previous_keys' => [
...array_filter( ...array_filter(
explode(',', env('APP_PREVIOUS_KEYS', '')) explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
), ),
], ],

View File

@@ -1,5 +1,7 @@
<?php <?php
use App\Models\User;
return [ return [
/* /*
@@ -62,7 +64,7 @@ return [
'providers' => [ 'providers' => [
'users' => [ 'users' => [
'driver' => 'eloquent', 'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class), 'model' => env('AUTH_MODEL', User::class),
], ],
// 'users' => [ // 'users' => [

View File

@@ -14,7 +14,7 @@ return [
| |
*/ */
'enabled' => env('DEBUGBAR_ENABLED', null), 'enabled' => env('DEBUGBAR_ENABLED'),
'hide_empty_tabs' => true, // Hide tabs until they have content 'hide_empty_tabs' => true, // Hide tabs until they have content
'except' => [ 'except' => [
'telescope*', 'telescope*',

View File

@@ -1,5 +1,7 @@
<?php <?php
use Propaganistas\LaravelDisposableEmail\Fetcher\DefaultFetcher;
return [ return [
/* /*
@@ -34,7 +36,7 @@ return [
| |
*/ */
'fetcher' => \Propaganistas\LaravelDisposableEmail\Fetcher\DefaultFetcher::class, 'fetcher' => DefaultFetcher::class,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View File

@@ -54,7 +54,7 @@ return [
'stack' => [ 'stack' => [
'driver' => 'stack', 'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', 'single')), 'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false, 'ignore_exceptions' => false,
], ],

View File

@@ -46,7 +46,7 @@ return [
'username' => env('MAIL_USERNAME'), 'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'), 'password' => env('MAIL_PASSWORD'),
'timeout' => null, 'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url(env('APP_URL', 'http://localhost'), PHP_URL_HOST)), 'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
], ],
'ses' => [ 'ses' => [

View File

@@ -1,5 +1,8 @@
<?php <?php
use Laravel\Sanctum\Http\Middleware\AuthenticateSession;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Laravel\Sanctum\Sanctum; use Laravel\Sanctum\Sanctum;
return [ return [
@@ -15,7 +18,7 @@ return [
| |
*/ */
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( 'stateful' => explode(',', (string) env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s', '%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(), Sanctum::currentApplicationUrlWithPort(),
@@ -76,9 +79,9 @@ return [
*/ */
'middleware' => [ 'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class, 'authenticate_session' => AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class, 'encrypt_cookies' => EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, 'validate_csrf_token' => ValidateCsrfToken::class,
], ],
]; ];

View File

@@ -2,11 +2,12 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\ActivationKey;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str; use Illuminate\Support\Str;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\ActivationKey> * @extends Factory<ActivationKey>
*/ */
class ActivationKeyFactory extends Factory class ActivationKeyFactory extends Factory
{ {

View File

@@ -2,12 +2,13 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Blog;
use App\Models\Category; use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str; use Illuminate\Support\Str;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Blog> * @extends Factory<Blog>
*/ */
class BlogFactory extends Factory class BlogFactory extends Factory
{ {

View File

@@ -2,11 +2,12 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str; use Illuminate\Support\Str;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Category> * @extends Factory<Category>
*/ */
class CategoryFactory extends Factory class CategoryFactory extends Factory
{ {

View File

@@ -2,10 +2,11 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Email;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Email> * @extends Factory<Email>
*/ */
class EmailFactory extends Factory class EmailFactory extends Factory
{ {

View File

@@ -2,11 +2,12 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Log;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Log> * @extends Factory<Log>
*/ */
class LogFactory extends Factory class LogFactory extends Factory
{ {

View File

@@ -2,10 +2,11 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Menu;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Menu> * @extends Factory<Menu>
*/ */
class MenuFactory extends Factory class MenuFactory extends Factory
{ {

View File

@@ -2,10 +2,11 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Message;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Message> * @extends Factory<Message>
*/ */
class MessageFactory extends Factory class MessageFactory extends Factory
{ {

View File

@@ -5,6 +5,9 @@ namespace Database\Factories;
use App\Models\Meta; use App\Models\Meta;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Meta>
*/
class MetaFactory extends Factory class MetaFactory extends Factory
{ {
protected $model = Meta::class; protected $model = Meta::class;

View File

@@ -2,11 +2,12 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Page;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str; use Illuminate\Support\Str;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Page> * @extends Factory<Page>
*/ */
class PageFactory extends Factory class PageFactory extends Factory
{ {

View File

@@ -2,10 +2,11 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Plan;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Plan> * @extends Factory<Plan>
*/ */
class PlanFactory extends Factory class PlanFactory extends Factory
{ {

View File

@@ -2,10 +2,11 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\PremiumEmail;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\PremiumEmail> * @extends Factory<PremiumEmail>
*/ */
class PremiumEmailFactory extends Factory class PremiumEmailFactory extends Factory
{ {

View File

@@ -5,6 +5,9 @@ namespace Database\Factories;
use App\Models\RemoteEmail; use App\Models\RemoteEmail;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<RemoteEmail>
*/
class RemoteEmailFactory extends Factory class RemoteEmailFactory extends Factory
{ {
protected $model = RemoteEmail::class; protected $model = RemoteEmail::class;

View File

@@ -2,10 +2,11 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Setting;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Setting> * @extends Factory<Setting>
*/ */
class SettingFactory extends Factory class SettingFactory extends Factory
{ {

View File

@@ -2,11 +2,12 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\Ticket;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Ticket> * @extends Factory<Ticket>
*/ */
class TicketFactory extends Factory class TicketFactory extends Factory
{ {

View File

@@ -2,12 +2,13 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\TicketResponse;
use App\Models\Ticket; use App\Models\Ticket;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\TicketResponse> * @extends Factory<TicketResponse>
*/ */
class TicketResponseFactory extends Factory class TicketResponseFactory extends Factory
{ {

View File

@@ -2,11 +2,12 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\UsageLog;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\UsageLog> * @extends Factory<UsageLog>
*/ */
class UsageLogFactory extends Factory class UsageLogFactory extends Factory
{ {

View File

@@ -2,12 +2,13 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str; use Illuminate\Support\Str;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User> * @extends Factory<User>
*/ */
class UserFactory extends Factory class UserFactory extends Factory
{ {
@@ -38,7 +39,7 @@ class UserFactory extends Factory
*/ */
public function unverified(): static public function unverified(): static
{ {
return $this->state(fn (array $attributes) => [ return $this->state(fn (array $attributes): array => [
'email_verified_at' => null, 'email_verified_at' => null,
]); ]);
} }

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('users', function (Blueprint $table) { Schema::create('users', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('name'); $table->string('name');
$table->string('email')->unique(); $table->string('email')->unique();
@@ -21,13 +21,13 @@ return new class extends Migration
$table->timestamps(); $table->timestamps();
}); });
Schema::create('password_reset_tokens', function (Blueprint $table) { Schema::create('password_reset_tokens', function (Blueprint $table): void {
$table->string('email')->primary(); $table->string('email')->primary();
$table->string('token'); $table->string('token');
$table->timestamp('created_at')->nullable(); $table->timestamp('created_at')->nullable();
}); });
Schema::create('sessions', function (Blueprint $table) { Schema::create('sessions', function (Blueprint $table): void {
$table->string('id')->primary(); $table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index(); $table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable(); $table->string('ip_address', 45)->nullable();

View File

@@ -11,13 +11,13 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('cache', function (Blueprint $table) { Schema::create('cache', function (Blueprint $table): void {
$table->string('key')->primary(); $table->string('key')->primary();
$table->mediumText('value'); $table->mediumText('value');
$table->integer('expiration'); $table->integer('expiration');
}); });
Schema::create('cache_locks', function (Blueprint $table) { Schema::create('cache_locks', function (Blueprint $table): void {
$table->string('key')->primary(); $table->string('key')->primary();
$table->string('owner'); $table->string('owner');
$table->integer('expiration'); $table->integer('expiration');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('jobs', function (Blueprint $table) { Schema::create('jobs', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('queue')->index(); $table->string('queue')->index();
$table->longText('payload'); $table->longText('payload');
@@ -21,7 +21,7 @@ return new class extends Migration
$table->unsignedInteger('created_at'); $table->unsignedInteger('created_at');
}); });
Schema::create('job_batches', function (Blueprint $table) { Schema::create('job_batches', function (Blueprint $table): void {
$table->string('id')->primary(); $table->string('id')->primary();
$table->string('name'); $table->string('name');
$table->integer('total_jobs'); $table->integer('total_jobs');
@@ -34,7 +34,7 @@ return new class extends Migration
$table->integer('finished_at')->nullable(); $table->integer('finished_at')->nullable();
}); });
Schema::create('failed_jobs', function (Blueprint $table) { Schema::create('failed_jobs', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('uuid')->unique(); $table->string('uuid')->unique();
$table->text('connection'); $table->text('connection');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::table('users', function (Blueprint $table) { Schema::table('users', function (Blueprint $table): void {
$table->integer('level')->default(0)->after('id'); $table->integer('level')->default(0)->after('id');
}); });
} }
@@ -21,7 +21,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::table('users', function (Blueprint $table) { Schema::table('users', function (Blueprint $table): void {
$table->dropColumn('level'); $table->dropColumn('level');
}); });
} }

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('settings', function (Blueprint $table) { Schema::create('settings', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('app_name'); $table->string('app_name');
$table->string('app_version')->default('1.0'); $table->string('app_version')->default('1.0');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::table('settings', function (Blueprint $table) { Schema::table('settings', function (Blueprint $table): void {
$table->json('imap_settings')->default('[]')->after('app_footer'); $table->json('imap_settings')->default('[]')->after('app_footer');
}); });
} }
@@ -21,7 +21,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::table('settings', function (Blueprint $table) { Schema::table('settings', function (Blueprint $table): void {
$table->dropColumn('imap_settings'); $table->dropColumn('imap_settings');
}); });
} }

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::table('settings', function (Blueprint $table) { Schema::table('settings', function (Blueprint $table): void {
$table->json('configuration_settings')->default('[]')->after('imap_settings'); $table->json('configuration_settings')->default('[]')->after('imap_settings');
}); });
} }
@@ -21,7 +21,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::table('settings', function (Blueprint $table) { Schema::table('settings', function (Blueprint $table): void {
$table->dropColumn('configuration_settings'); $table->dropColumn('configuration_settings');
}); });
} }

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::table('settings', function (Blueprint $table) { Schema::table('settings', function (Blueprint $table): void {
$table->json('ads_settings')->default('[]')->after('configuration_settings'); $table->json('ads_settings')->default('[]')->after('configuration_settings');
}); });
} }
@@ -21,7 +21,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::table('settings', function (Blueprint $table) { Schema::table('settings', function (Blueprint $table): void {
$table->dropColumn('ads_settings'); $table->dropColumn('ads_settings');
}); });
} }

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('metas', function (Blueprint $table) { Schema::create('metas', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('key'); $table->string('key');
$table->text('value')->nullable(); $table->text('value')->nullable();

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('logs', function (Blueprint $table) { Schema::create('logs', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('ip'); $table->string('ip');
$table->string('email'); $table->string('email');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('messages', function (Blueprint $table) { Schema::create('messages', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('subject'); $table->string('subject');
$table->string('from'); $table->string('from');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('emails', function (Blueprint $table) { Schema::create('emails', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('message_id')->unique()->index(); $table->string('message_id')->unique()->index();
$table->string('subject')->nullable(); $table->string('subject')->nullable();

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('pages', function (Blueprint $table) { Schema::create('pages', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('title'); $table->string('title');
$table->string('slug'); $table->string('slug');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('menus', function (Blueprint $table) { Schema::create('menus', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('name'); $table->string('name');
$table->string('url'); $table->string('url');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('categories', function (Blueprint $table) { Schema::create('categories', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('name'); $table->string('name');
$table->string('slug'); $table->string('slug');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('blogs', function (Blueprint $table) { Schema::create('blogs', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('post'); $table->string('post');
$table->string('slug'); $table->string('slug');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::table('users', function (Blueprint $table) { Schema::table('users', function (Blueprint $table): void {
$table->string('stripe_id')->nullable()->index(); $table->string('stripe_id')->nullable()->index();
$table->string('pm_type')->nullable(); $table->string('pm_type')->nullable();
$table->string('pm_last_four', 4)->nullable(); $table->string('pm_last_four', 4)->nullable();
@@ -24,7 +24,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::table('users', function (Blueprint $table) { Schema::table('users', function (Blueprint $table): void {
$table->dropIndex([ $table->dropIndex([
'stripe_id', 'stripe_id',
]); ]);

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('subscriptions', function (Blueprint $table) { Schema::create('subscriptions', function (Blueprint $table): void {
$table->id(); $table->id();
$table->foreignId('user_id'); $table->foreignId('user_id');
$table->string('type'); $table->string('type');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('subscription_items', function (Blueprint $table) { Schema::create('subscription_items', function (Blueprint $table): void {
$table->id(); $table->id();
$table->foreignId('subscription_id'); $table->foreignId('subscription_id');
$table->string('stripe_id')->unique(); $table->string('stripe_id')->unique();

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('plans', function (Blueprint $table) { Schema::create('plans', function (Blueprint $table): void {
$table->id(); $table->id();
$table->string('name'); $table->string('name');
$table->text('description')->nullable(); $table->text('description')->nullable();

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('usage_logs', function (Blueprint $table) { Schema::create('usage_logs', function (Blueprint $table): void {
$table->bigIncrements('id'); $table->bigIncrements('id');
$table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('user_id');
$table->ipAddress('ip_address'); $table->ipAddress('ip_address');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::table('logs', function (Blueprint $table) { Schema::table('logs', function (Blueprint $table): void {
$table->unsignedBigInteger('user_id')->nullable()->after('id'); $table->unsignedBigInteger('user_id')->nullable()->after('id');
$table->foreign('user_id')->references('id')->on('users'); $table->foreign('user_id')->references('id')->on('users');
}); });
@@ -22,7 +22,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::table('logs', function (Blueprint $table) { Schema::table('logs', function (Blueprint $table): void {
$table->dropForeign(['user_id']); $table->dropForeign(['user_id']);
$table->dropColumn('user_id'); $table->dropColumn('user_id');
}); });

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('premium_emails', function (Blueprint $table) { Schema::create('premium_emails', function (Blueprint $table): void {
$table->id(); $table->id();
$table->unsignedBigInteger('user_id'); $table->unsignedBigInteger('user_id');
$table->string('message_id')->unique()->index(); $table->string('message_id')->unique()->index();

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