Skip to content

A free open source IT asset/license management system

66.1 KB
Raw Blame
<?php

namespace App\Http\Controllers;

use App\Enums\ActionType;
use App\Helpers\Helper;
use App\Helpers\StorageHelper;
use App\Http\Requests\ImageUploadRequest;
use App\Http\Requests\SettingsSamlRequest;
use App\Http\Requests\StoreLabelSettings;
use App\Http\Requests\StoreLdapSettings;
use App\Http\Requests\StoreLocalizationSettings;
use App\Http\Requests\StoreNotificationSettings;
use App\Http\Requests\StoreSecuritySettings;
use App\Models\Actionlog;
use App\Models\Asset;
use App\Models\CustomField;
use App\Models\Group;
use App\Models\Labels\CustomUserLabel;
use App\Models\Setting;
use App\Models\User;
use App\Notifications\MailTest;
use App\Rules\CssColor;
use App\Traits\LocksLongRunningOperation;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use League\Csv\EscapeFormula;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use ZipArchive;

/**
 * This controller handles all actions related to Settings for
 * the Snipe-IT Asset Management application.
 *
 * @version    v1.0
 */
class SettingsController extends Controller
{
    use LocksLongRunningOperation;

    /**
     * Shared mutex key for backup + restore. Both operations acquire
     * the same key so they're mutually exclusive. Restore is
     * backup-plus-more (it optionally takes a pre-restore backup, wipes, replays),
     * so a concurrent plain backup firing while a restore holds this
     * lock would race the pre-restore backup write against the
     * concurrent backup's write to the same backup disk.
     */
    private const BACKUP_RESTORE_LOCK = 'backup-restore:running';

    /**
     * Return a view that shows some of the key settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function index(): View
    {
        $settings = Setting::getSettings();

        $impersonationUsernames = (array) config('app.user_impersonation_usernames');
        if (empty($impersonationUsernames)) {
            $impersonators = collect();
            $missingImpersonationUsernames = [];
        } else {
            $impersonators = User::withTrashed()
                ->whereIn(DB::raw('LOWER(username)'), array_map('mb_strtolower', $impersonationUsernames))
                ->orderBy('username')
                ->get();
            $foundLower = $impersonators->map(fn ($u) => mb_strtolower((string) $u->username))->all();
            $missingImpersonationUsernames = array_values(array_filter(
                $impersonationUsernames,
                fn ($name) => ! in_array(mb_strtolower($name), $foundLower, true)
            ));
        }

        // Grab the adapters list so we can populate the hidden keywords for the settings search box
        $adapterKeywords = implode(' ', \App\SyncAdapters\SyncAdapter::typeLabels());

        return view('settings/index', compact('settings', 'impersonators', 'missingImpersonationUsernames', 'adapterKeywords'));
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function getSettings(): View
    {
        $setting = Setting::getSettings();

        return view('settings/general', compact('setting'));
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function postSettings(Request $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        $setting->modellist_displays = '';

        if (($request->filled('show_in_model_list')) && (count($request->input('show_in_model_list')) > 0)) {
            $setting->modellist_displays = implode(',', $request->input('show_in_model_list'));
        }

        $old_locations_fmcs = $setting->scope_locations_fmcs;
        $setting->full_multiple_companies_support = $request->input('full_multiple_companies_support', '0');
        $setting->scope_locations_fmcs = $request->input('scope_locations_fmcs', '0');
        $setting->null_company_is_floater = $request->input('null_company_is_floater', '0');

        // These options make no sense without FullMultipleCompanySupport
        if (! $setting->full_multiple_companies_support) {
            $setting->scope_locations_fmcs = '0';
            $setting->null_company_is_floater = '0';
        }

        // check for inconsistencies when activating scoped locations
        if ($old_locations_fmcs == '0' && $setting->scope_locations_fmcs == '1') {
            $mismatched = Helper::test_locations_fmcs(false);
            if (count($mismatched) != 0) {
                return redirect()->back()->withInput()->with('error', trans_choice('admin/settings/message.location_scoping.mismatch', count($mismatched)).' '.trans('admin/settings/message.location_scoping.not_saved'));
            }
        }

        $setting->unique_serial = $request->input('unique_serial', '0');
        $setting->shortcuts_enabled = $request->input('shortcuts_enabled', '0');
        $setting->show_images_in_email = $request->input('show_images_in_email', '0');
        $setting->show_archived_in_list = $request->input('show_archived_in_list', '0');
        $setting->dashboard_message = $request->input('dashboard_message');
        $setting->email_domain = $request->input('email_domain');
        $setting->email_format = $request->input('email_format');
        $setting->username_format = $request->input('username_format');
        $setting->require_accept_signature = $request->input('require_accept_signature', '0');
        $setting->show_assigned_assets = $request->input('show_assigned_assets', '0');
        if (! config('app.lock_passwords')) {
            $setting->login_note = $request->input('login_note');
        }

        $setting->default_eula_text = $request->input('default_eula_text');
        $setting->thumbnail_max_h = $request->input('thumbnail_max_h');
        $setting->privacy_policy_link = $request->input('privacy_policy_link');
        $setting->depreciation_method = $request->input('depreciation_method');
        $setting->dash_chart_type = $request->input('dash_chart_type');
        $setting->profile_edit = $request->input('profile_edit', 0);
        $setting->require_checkinout_notes = $request->input('require_checkinout_notes', 0);
        $setting->manager_view_enabled = $request->input('manager_view_enabled', 0);

        if ($request->input('per_page') != '') {
            $setting->per_page = $request->input('per_page');
        } else {
            $setting->per_page = 200;
        }

        if ($setting->save()) {
            return redirect()->route('settings.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Stream a CSV of every location-scoping FMCS mismatch.
     *
     * This endpoint runs the full walk (artisan=true) and streams
     * the same table columns the CLI command prints, as CSV.
     */
    public function downloadLocationScopingReport(): \Symfony\Component\HttpFoundation\StreamedResponse
    {
        $mismatched = Helper::test_locations_fmcs(true);

        $filename = 'location-scoping-mismatches-'.date('Y-m-d').'.csv';

        return response()->streamDownload(function () use ($mismatched) {
            $out = fopen('php://output', 'w');
            fputcsv($out, [
                'Type',
                'ID',
                'Name',
                'Checkout Type',
                'Company IDs',
                'Item Companies',
                'Item Location',
                'Location Company',
                'Location Company ID',
            ], escape: '\\', eol: "\r\n");

            // Formula-escape data rows using the same helper + setting as
            // ReportsController's exports. Row values include user-editable
            // free text (item name, item companies, item location, location
            // company) which a low-privilege user could set to a spreadsheet
            // formula. Without escaping, the payload evaluates when a
            // superuser opens the downloaded CSV in Excel / LibreOffice /
            // Google Sheets. Same backtick prefix ReportsController uses.
            $formatter = new EscapeFormula('`');
            foreach ($mismatched as $row) {
                if (config('app.escape_formulas') === false) {
                    fputcsv($out, $row, escape: '\\', eol: "\r\n");
                } else {
                    fputcsv($out, $formatter->escapeRecord($row), escape: '\\', eol: "\r\n");
                }
            }
            fclose($out);
        }, $filename, ['Content-Type' => 'text/csv']);
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function getBranding(): View
    {
        $setting = Setting::getSettings();

        return view('settings.branding', compact('setting'));
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function postBranding(ImageUploadRequest $request): RedirectResponse
    {
        // Something has gone horribly wrong - no settings record exists!
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        $setting->brand = $request->input('brand', '1');

        $setting->support_footer = $request->input('support_footer');
        $setting->version_footer = $request->input('version_footer');
        $setting->footer_text = $request->input('footer_text');
        $setting->show_url_in_emails = $request->input('show_url_in_emails', '0');
        $setting->logo_print_assets = $request->input('logo_print_assets', '0');
        $setting->load_remote = $request->input('load_remote', 0);

        // Only allow the site name, images, and CSS to be changed if lock_passwords is false
        // Because public demos make people act like dicks

        if (! config('app.lock_passwords')) {

            if ($request->has('site_name')) {
                $request->validate(['site_name' => 'required']);
            }

            $request->validate([
                'header_color' => ['nullable', new CssColor],
                'link_light_color' => ['nullable', new CssColor],
                'link_dark_color' => ['nullable', new CssColor],
                'nav_link_color' => ['nullable', new CssColor],
            ]);

            $setting->header_color = $request->input('header_color', '#3c8dbc');
            $setting->link_light_color = $request->input('link_light_color', '#296282');
            $setting->link_dark_color = $request->input('link_dark_color', '#5fa4cc');
            $setting->nav_link_color = $request->input('nav_link_color', '#FFFFFF');

            $setting->site_name = $request->input('site_name', 'Snipe-IT');
            $setting->custom_css = $request->input('custom_css');

            // Logo upload
            $setting = $request->handleImages($setting, 600, 'logo', '', 'logo');

            if ($request->input('clear_logo') == '1') {
                $setting = $request->deleteExistingImage($setting, '', 'logo');
                $setting->logo = null;
                $setting->brand = 1;
            }

            // Email logo upload
            $setting = $request->handleImages($setting, 600, 'email_logo', '', 'email_logo');
            if ($request->input('clear_email_logo') == '1') {
                $setting = $request->deleteExistingImage($setting, '', 'email_logo');
                $setting->email_logo = null;
            }

            // Label logo upload
            $setting = $request->handleImages($setting, 600, 'label_logo', '', 'label_logo');

            if ($request->input('clear_label_logo') == '1') {
                $setting = $request->deleteExistingImage($setting, '', 'label_logo');
                $setting->label_logo = null;
            }

            // Acceptance PDF upload
            $setting = $request->handleImages($setting, 600, 'acceptance_pdf_logo', '', 'acceptance_pdf_logo');
            if ($request->input('clear_acceptance_pdf_logo') == '1') {
                $setting = $request->deleteExistingImage($setting, '', 'acceptance_pdf_logo');
                $setting->acceptance_pdf_logo = null;
            }

            // Favicon upload
            $setting = $request->handleImages($setting, 100, 'favicon', '', 'favicon');
            if ($request->input('clear_favicon') == '1') {
                $setting = $request->deleteExistingImage($setting, '', 'favicon');
                $setting->favicon = null;
            }

            // Default avatar upload
            $setting = $request->handleImages($setting, 500, 'default_avatar', 'avatars', 'default_avatar');
            if ($request->input('clear_default_avatar') == '1') {
                // Don't delete the file, just update the field if this is the default
                if ($setting->default_avatar != 'default.png') {
                    $setting = $request->deleteExistingImage($setting, 'avatars', 'default_avatar');
                }
                $setting->default_avatar = null;
            }

            if ($request->input('restore_default_avatar') == '1') {
                $setting->default_avatar = 'default.png';
            }
        }

        if ($setting->save()) {
            return redirect()->route('settings.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function getSecurity(): View
    {
        $setting = Setting::getSettings();

        return view('settings.security', compact('setting'));
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function postSecurity(StoreSecuritySettings $request): RedirectResponse
    {
        $this->validate($request, [
            'pwd_secure_complexity' => 'array',
            'pwd_secure_complexity.*' => [
                Rule::in([
                    'disallow_same_pwd_as_user_fields',
                    'letters',
                    'numbers',
                    'symbols',
                    'case_diff',
                ]),
            ],
        ]);

        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }
        if (! config('app.lock_passwords')) {
            if ($request->input('two_factor_enabled') == '') {
                $setting->two_factor_enabled = null;
            } else {
                $setting->two_factor_enabled = $request->input('two_factor_enabled');
            }

            // remote user login
            $setting->login_remote_user_enabled = (int) $request->input('login_remote_user_enabled');
            $setting->login_common_disabled = (int) $request->input('login_common_disabled');
            $setting->login_remote_user_custom_logout_url = $request->input('login_remote_user_custom_logout_url');
            $setting->login_remote_user_header_name = $request->input('login_remote_user_header_name');
        }

        $setting->pwd_secure_uncommon = (int) $request->input('pwd_secure_uncommon');
        $setting->pwd_secure_min = (int) $request->input('pwd_secure_min');
        $setting->pwd_secure_complexity = '';

        if ($request->filled('pwd_secure_complexity')) {
            $setting->pwd_secure_complexity = implode('|', $request->input('pwd_secure_complexity'));
        }

        if ($setting->save()) {
            return redirect()->route('settings.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function getLocalization(): View
    {
        $setting = Setting::getSettings();

        return view('settings.localization', compact('setting'));
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function postLocalization(StoreLocalizationSettings $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        if (! config('app.lock_passwords')) {
            $setting->locale = $request->input('locale', 'en-US');
        }
        $setting->default_currency = $request->input('default_currency', '$');
        $setting->date_display_format = $request->input('date_display_format');
        $setting->time_display_format = $request->input('time_display_format');
        $setting->digit_separator = $request->input('digit_separator');
        $setting->name_display_format = $request->input('name_display_format');
        $setting->week_start = $request->input('week_start', 0);

        if ($setting->save()) {
            return redirect()->route('settings.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function getAlerts(): View
    {
        $setting = Setting::getSettings();

        return view('settings.alerts', compact('setting'));
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function postAlerts(StoreNotificationSettings $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        // Check if the audit interval has changed - if it has, check if we should update all of the assets audit dates
        if ((($request->input('audit_interval') != $setting->audit_interval)) && ($request->input('update_existing_dates') == 1)) {

            // This could be a negative number if the user is trying to set the audit interval to a lower number than it was before
            $audit_diff_months = ((int) $request->input('audit_interval') - (int) ($setting->audit_interval));

            // Batch update the dates. We have to use this method to avoid time limit exceeded errors on very large datasets,
            // but it DOES mean this change doesn't get logged in the action logs, since it skips the observer.
            // @see https://stackoverflow.com/questions/54879160/laravel-observer-not-working-on-bulk-insert
            $affected = Asset::whereNotNull('next_audit_date')
                ->whereNull('deleted_at')
                ->update(
                    ['next_audit_date' => DB::raw('DATE_ADD(next_audit_date, INTERVAL '.$audit_diff_months.' MONTH)')]
                );

            Log::debug($affected.' assets affected by audit interval update');
        }

        $alert_email = rtrim($request->input('alert_email'), ',');
        $alert_email = trim($alert_email);
        $admin_cc_email = rtrim($request->input('admin_cc_email'), ',');
        $admin_cc_email = trim($admin_cc_email);

        $setting->alert_email = $alert_email;
        $setting->admin_cc_email = $admin_cc_email;
        $setting->admin_cc_always = $request->validated('admin_cc_always');
        $setting->alerts_enabled = $request->input('alerts_enabled', '0');
        $setting->alert_interval = $request->input('alert_interval');
        $setting->alert_threshold = $request->input('alert_threshold');
        $setting->audit_interval = $request->input('audit_interval');
        $setting->audit_warning_days = $request->input('audit_warning_days');
        $setting->due_checkin_days = $request->input('due_checkin_days');
        $setting->show_alerts_in_menu = $request->input('show_alerts_in_menu', '0');

        if ($setting->save()) {
            return redirect()->route('settings.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function getIntegrations(): View
    {
        $setting = Setting::getSettings();

        return view('settings.integrations', compact('setting'));
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function getAssetTags(): View
    {
        $setting = Setting::getSettings();

        return view('settings.asset_tags', compact('setting'));
    }

    /**
     * Saves settings from form.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.0]
     */
    public function postAssetTags(Request $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        $setting->auto_increment_prefix = $request->input('auto_increment_prefix');
        $setting->auto_increment_assets = $request->input('auto_increment_assets', '0');
        $setting->zerofill_count = $request->input('zerofill_count');
        $setting->next_auto_tag_base = $request->input('next_auto_tag_base');

        if ($setting->save()) {
            return redirect()->route('settings.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v4.0]
     */
    public function getPhpInfo(): View|RedirectResponse
    {
        if (config('app.debug') === true) {
            return view('settings.phpinfo');
        }

        return redirect()->route('settings.index')
            ->with('error', 'PHP syetem debugging information is only available when debug is enabled in your .env file.');
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v4.0]
     */
    public function getLabels(): View
    {
        $is_gd_installed = extension_loaded('gd');
        $setting = Setting::getSettings();

        if (str_starts_with($setting->label2_template, 'custom:')) {
            $customLabelId = (int) str_replace('custom:', '', $setting->label2_template);

            $setting->label2_template_name = CustomUserLabel::find($customLabelId)?->name
                ?? $setting->label2_template;
        }

        return view('settings.labels')
            ->with('setting', $setting)
            ->with('is_gd_installed', $is_gd_installed)
            ->with('customFields', CustomField::where('field_encrypted', '=', 0)->get());
    }

    /**
     * Saves settings from form.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v4.0]
     */
    public function postLabels(StoreLabelSettings $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }
        $wasLabel2Enabled = $setting->label2_enable;
        $setting->label2_enable = $request->input('label2_enable');
        $setting->label2_template = $request->input('label2_template');
        $setting->label2_title = $request->input('label2_title');
        $setting->label2_asset_logo = $request->input('label2_asset_logo');
        $setting->label2_1d_type = $request->input('label2_1d_type');
        $setting->label2_2d_type = $request->input('label2_2d_type');
        $setting->label2_2d_prefix = $request->input('label2_2d_prefix');
        $setting->label2_2d_target = $request->input('label2_2d_target');
        $setting->label2_fields = $request->input('label2_fields');
        $setting->label2_empty_row_count = $request->input('label2_empty_row_count');
        if (! $wasLabel2Enabled && ! $request->boolean('label2_enable')) {
            $setting->labels_per_page = $request->input('labels_per_page');
            $setting->labels_width = $request->input('labels_width');
            $setting->labels_height = $request->input('labels_height');
            $setting->labels_pmargin_left = $request->input('labels_pmargin_left');
            $setting->labels_pmargin_right = $request->input('labels_pmargin_right');
            $setting->labels_pmargin_top = $request->input('labels_pmargin_top');
            $setting->labels_pmargin_bottom = $request->input('labels_pmargin_bottom');
            $setting->labels_display_bgutter = $request->input('labels_display_bgutter');
            $setting->labels_display_sgutter = $request->input('labels_display_sgutter');
            $setting->labels_fontsize = $request->input('labels_fontsize');
            $setting->labels_pagewidth = $request->input('labels_pagewidth');
            $setting->labels_pageheight = $request->input('labels_pageheight');
            $setting->labels_display_company_name = $request->input('labels_display_company_name', '0');
            // Barcodes
            $setting->qr_code = $request->input('qr_code', '0');
            // 1D-Barcode
            $setting->alt_barcode_enabled = $request->input('alt_barcode_enabled', '0');
            // QR-Code
            $setting->qr_text = $request->input('qr_text');

            if ($request->filled('labels_display_name')) {
                $setting->labels_display_name = 1;
            } else {
                $setting->labels_display_name = 0;
            }

            if ($request->filled('labels_display_serial')) {
                $setting->labels_display_serial = 1;
            } else {
                $setting->labels_display_serial = 0;
            }

            if ($request->filled('labels_display_tag')) {
                $setting->labels_display_tag = 1;
            } else {
                $setting->labels_display_tag = 0;
            }

            if ($request->filled('labels_display_tag')) {
                $setting->labels_display_tag = 1;
            } else {
                $setting->labels_display_tag = 0;
            }

            if ($request->filled('labels_display_model')) {
                $setting->labels_display_model = 1;
            } else {
                $setting->labels_display_model = 0;
            }
        }

        if (! $wasLabel2Enabled && $request->boolean('label2_enable')) {
            $setting->label2_title = $setting->qr_text;
        }

        if ($setting->save()) {
            $selectedTemplate = $setting->label2_template;

            CustomUserLabel::where('is_default', true)->update(['is_default' => false]);

            if (str_starts_with($selectedTemplate, 'custom:')) {
                $customLabelId = (int) str_replace('custom:', '', $selectedTemplate);

                CustomUserLabel::whereKey($customLabelId)->update([
                    'is_default' => true,
                ]);
            }

            return redirect()->route('settings.labels.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v4.0]
     */
    public function getLdapSettings(): View
    {
        $setting = Setting::getSettings();
        $groups = Group::pluck('name', 'id');

        return view('settings.ldap', compact('setting', 'groups'));
    }

    /**
     * Saves settings from form.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v4.0]
     */
    public function postLdapSettings(StoreLdapSettings $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        if (! config('app.lock_passwords') === true) {
            $setting->ldap_enabled = $request->input('ldap_enabled', '0');
            $setting->ldap_server = $request->input('ldap_server');
            $setting->ldap_server_cert_ignore = $request->input('ldap_server_cert_ignore', false);
            $setting->ldap_uname = $request->input('ldap_uname');
            if ($request->filled('ldap_pword')) {
                $setting->ldap_pword = Crypt::encrypt($request->input('ldap_pword'));
            }
            $setting->ldap_basedn = $request->input('ldap_basedn');
            $setting->ldap_default_group = $request->input('ldap_default_group');
            $setting->ldap_filter = $request->input('ldap_filter');
            $setting->ldap_username_field = $request->input('ldap_username_field');
            $setting->ldap_display_name = $request->input('ldap_display_name');
            $setting->ldap_lname_field = $request->input('ldap_lname_field');
            $setting->ldap_fname_field = $request->input('ldap_fname_field');
            $setting->ldap_auth_filter_query = $request->input('ldap_auth_filter_query');
            $setting->ldap_version = $request->input('ldap_version', 3);
            $setting->ldap_active_flag = $request->input('ldap_active_flag', 0);
            $setting->ldap_invert_active_flag = $request->input('ldap_invert_active_flag', 0);
            $setting->ldap_emp_num = $request->input('ldap_emp_num');
            $setting->ldap_email = $request->input('ldap_email');
            $setting->ldap_manager = $request->input('ldap_manager');
            $setting->ad_domain = $request->input('ad_domain');
            $setting->is_ad = $request->input('is_ad', '0');
            $setting->ad_append_domain = $request->input('ad_append_domain', '0');
            $setting->ldap_tls = $request->input('ldap_tls', '0');
            $setting->ldap_pw_sync = $request->input('ldap_pw_sync', '0');
            $setting->custom_forgot_pass_url = $request->input('custom_forgot_pass_url');
            $setting->ldap_phone_field = $request->input('ldap_phone');
            $setting->ldap_mobile = $request->input('ldap_mobile');
            $setting->ldap_jobtitle = $request->input('ldap_jobtitle');
            $setting->ldap_address = $request->input('ldap_address');
            $setting->ldap_city = $request->input('ldap_city');
            $setting->ldap_state = $request->input('ldap_state');
            $setting->ldap_zip = $request->input('ldap_zip');
            $setting->ldap_country = $request->input('ldap_country');
            $setting->ldap_location = $request->input('ldap_location');
            $setting->ldap_dept = $request->input('ldap_dept');
            $setting->ldap_client_tls_cert = $request->input('ldap_client_tls_cert');
            $setting->ldap_client_tls_key = $request->input('ldap_client_tls_key');
        }

        if ($setting->save()) {
            return redirect()->route('settings.ldap.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author Johnson Yi <[email protected]>
     *
     * @since v5.0.0
     */
    public function getSamlSettings(): View
    {
        $setting = Setting::getSettings();

        return view('settings.saml', compact('setting'));
    }

    /**
     * Saves settings from form.
     *
     * @author Johnson Yi <[email protected]>
     *
     * @since v5.0.0
     */
    public function postSamlSettings(SettingsSamlRequest $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        $setting->saml_enabled = $request->input('saml_enabled', '0');
        $setting->saml_idp_metadata = $request->input('saml_idp_metadata');
        $setting->saml_attr_mapping_username = $request->input('saml_attr_mapping_username');
        $setting->saml_forcelogin = $request->input('saml_forcelogin', '0');
        $setting->saml_slo = $request->input('saml_slo', '0');
        if (! empty($request->input('saml_sp_privatekey'))) {
            $setting->saml_sp_x509cert = $request->input('saml_sp_x509cert');
            $setting->saml_sp_privatekey = $request->input('saml_sp_privatekey');
        }
        if (! empty($request->input('saml_sp_x509certNew'))) {
            $setting->saml_sp_x509certNew = $request->input('saml_sp_x509certNew');
        } else {
            $setting->saml_sp_x509certNew = '';
        }
        $setting->saml_custom_settings = $request->input('saml_custom_settings');

        if ($setting->save()) {
            return redirect()->route('settings.saml.index')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Do we need this? Can we not just call getSettings() directly?
     */
    public static function getPDFBranding(): Setting
    {
        $pdf_branding = Setting::getSettings();

        return $pdf_branding;
    }

    /**
     * Show Google login settings form
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v6.1.1]
     */
    public function getGoogleLoginSettings(): View
    {
        $setting = Setting::getSettings();

        return view('settings.google', compact('setting'));
    }

    /**
     * ShSaveow Google login settings form
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v6.1.1]
     */
    public function postGoogleLoginSettings(Request $request): RedirectResponse
    {
        if (! config('app.lock_passwords')) {
            $setting = Setting::getSettings();

            $setting->google_login = $request->input('google_login', 0);
            $setting->google_client_id = $request->input('google_client_id');
            $setting->google_client_secret = $request->input('google_client_secret');

            if ($setting->save()) {
                return redirect()->route('settings.index')
                    ->with('success', trans('admin/settings/message.update.success'));
            }

            return redirect()->back()->withInput()->withErrors($setting->getErrors());
        }

        return redirect()->back()->with('error', trans('general.feature_disabled'));
    }

    /**
     * Show the listing of backups.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.8]
     */
    public function getBackups(): View
    {
        $settings = Setting::getSettings();
        $backupName = config('backup.backup.name', 'backups');
        $disk = Storage::disk('backup');
        $files_raw = [];

        foreach ($disk->files($backupName) as $file) {
            // Skip dotfiles like .gitignore and .DS_STORE
            if (substr(basename($file), 0, 1) === '.') {
                continue;
            }
            $file_timestamp = $disk->lastModified($file);
            $files_raw[] = [
                'filename' => basename($file),
                'filesize' => Setting::fileSizeConvert($disk->size($file)),
                'modified_value' => $file_timestamp,
                'modified_display' => date($settings->date_display_format.' '.$settings->time_display_format, $file_timestamp),
            ];
        }

        // Reverse the array so it lists oldest first
        $files = array_reverse($files_raw);

        // Belt-and-suspenders UI feedback for the shared backup+restore
        // mutex. The write-side rejects a concurrent trigger regardless,
        // this just stops the admin from clicking a button that will
        // immediately bounce.
        $backupRestoreRunning = $this->isOperationLocked(self::BACKUP_RESTORE_LOCK);

        return view('settings/backups', compact('files', 'backupRestoreRunning'));
    }

    /**
     * Process the backup.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.8]
     */
    public function postBackups(): RedirectResponse
    {
        if (config('app.lock_passwords')) {
            return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
        }

        if (! $this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {
            return redirect()->route('settings.backups.index')
                ->with('error', $this->operationAlreadyRunningMessage('general.backup_or_restore'));
        }

        try {
            Artisan::call('snipeit:backup', ['--filename' => 'manual-backup-'.date('Y-m-d-H-i-s')]);
            $output = Artisan::output();

            // Backup completed
            if (! preg_match('/failed/', $output)) {
                return redirect()->route('settings.backups.index')
                    ->with('success', trans('admin/settings/message.backup.generated'));
            }

            $formatted_output = str_replace('Backup completed!', '', $output);
            $output_split = explode('...', $formatted_output);

            if (array_key_exists(2, $output_split)) {
                return redirect()->route('settings.backups.index')->with('error', $output_split[2]);
            }

            return redirect()->route('settings.backups.index')->with('error', $formatted_output);
        } finally {
            $this->releaseOperationLock(self::BACKUP_RESTORE_LOCK);
        }
    }

    /**
     * Download the backup file.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.8]
     */
    public function downloadFile($filename = null): RedirectResponse|BinaryFileResponse|StreamedResponse
    {
        // Path inside the backup disk mirrors getBackups(): spatie writes
        // to <disk root>/<backup.backup.name>/*.zip, and BinFile.name
        // defaults to 'backups'. StorageHelper::downloader('backup')
        // dispatches to response()->download on the local driver and to
        // Storage::disk('backup')->download on the s3 driver, so this
        // works for both destinations without a driver switch here.
        $backupName = config('backup.backup.name', 'backups');
        $filename = basename((string) $filename);

        if ($this->hasInvalidBackupFilename($filename)) {
            return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
        }

        if (! config('app.lock_passwords')) {
            $path = $backupName.'/'.$filename;
            if (Storage::disk('backup')->exists($path)) {
                Log::warning('User '.auth()->user()->username.' is attempting to download backup file: '.$filename);

                return StorageHelper::downloader($path, 'backup');
            } else {
                // Redirect to the backup page
                return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
            }
        } else {
            // Redirect to the backup page
            return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
        }
    }

    /**
     * Delete the backup file.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v1.8]
     */
    public function deleteFile($filename = null): RedirectResponse
    {
        $filename = basename((string) $filename);

        if ($this->hasInvalidBackupFilename($filename)) {
            return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
        }

        if (config('app.allow_backup_delete') == 'true') {

            if (! config('app.lock_passwords')) {
                // Same disk + path so S3-destination backup is deletable from the UI.
                $disk = Storage::disk('backup');
                $path = config('backup.backup.name', 'backups').'/'.$filename;

                if ($disk->exists($path)) {

                    try {
                        Log::warning('User '.auth()->user()->username.' is attempting to delete backup file: '.$filename);
                        $disk->delete($path);

                        return redirect()->route('settings.backups.index')->with('success', trans('admin/settings/message.backup.file_deleted'));
                    } catch (\Exception $e) {
                        Log::debug($e);
                    }
                } else {
                    return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
                }
            }

            return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
        }

        // Hell to the no
        Log::warning('User ID '.auth()->id().' is attempting to delete backup file '.$filename.' and is not authorized to.');

        return redirect()->route('settings.backups.index')->with('error', trans('general.backup_delete_not_allowed'));
    }

    /**
     * Uploads a backup file
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v6.0]
     */
    public function postUploadBackup(Request $request): RedirectResponse
    {

        if (! config('app.lock_passwords')) {
            if (! $request->hasFile('file')) {
                return redirect()->route('settings.backups.index')->with('error', 'No file uploaded');
            } else {

                $max_file_size = Helper::file_upload_max_size();
                $validator = Validator::make($request->all(), [
                    'file' => 'required|mimes:zip|max:'.$max_file_size,
                ]);

                if ($validator->passes()) {

                    $upload_filename = 'uploaded-'.date('U').'-'.Str::slug(pathinfo($request->file('file')->getClientOriginalName(), PATHINFO_FILENAME)).'.zip';

                    Storage::putFileAs('app/backups', $request->file('file'), $upload_filename);

                    return redirect()->route('settings.backups.index')->with('success', 'File uploaded');
                }

                return redirect()->route('settings.backups.index')->withErrors($validator);
            }
        } else {
            return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
        }
    }

    /**
     * Restore the backup file.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v6.0]
     */
    public function postRestore(Request $request, $filename = null): RedirectResponse
    {
        $filename = basename((string) $filename);

        if ($this->hasInvalidBackupFilename($filename)) {
            return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
        }

        if (config('app.lock_passwords')) {
            return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
        }

        if (! $this->acquireOperationLock(self::BACKUP_RESTORE_LOCK)) {
            return redirect()->route('settings.backups.index')
                ->with('error', $this->operationAlreadyRunningMessage('general.backup_or_restore'));
        }

        // Path inside the backup disk mirrors getBackups / downloadFile /
        // deleteFile. spatie writes to <disk root>/<backup.backup.name>/
        // and the name defaults to 'backups'.
        $backupDisk = Storage::disk('backup');
        $backupName = config('backup.backup.name', 'backups');
        $diskPath = $backupName.'/'.$filename;

        if (! $backupDisk->exists($diskPath)) {
            return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
        }

        // ZipArchive and snipeit:restore both need a local filesystem path.
        // On the local driver, resolve directly to the disk's on-disk path
        // and let the restore CLI read it in place. On any remote driver
        // (s3), stream the archive down to a temp file so downstream code
        // that expects a real path still works. The finally block below
        // unlinks the temp file on every exit path so a bail-out doesn't
        // leave hundreds of megabytes stranded in storage/app/restore-temp.
        $localTempPath = null;
        try {
            if (config('filesystems.disks.backup.driver') === 'local') {
                $absolutePath = $backupDisk->path($diskPath);
            } else {
                $tempDir = storage_path('app/restore-temp');
                if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) {
                    Log::error('Restore aborted: could not create temp directory '.$tempDir);

                    return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));
                }
                $localTempPath = $tempDir.'/'.$filename;
                // readStream returns null on failure, fopen returns false.
                $srcStream = $backupDisk->readStream($diskPath);
                $dstStream = fopen($localTempPath, 'w');
                if ($srcStream === null || $dstStream === false) {
                    if (is_resource($srcStream)) {
                        fclose($srcStream);
                    }
                    if (is_resource($dstStream)) {
                        fclose($dstStream);
                    }
                    Log::error('Restore aborted: failed to open streams for temp copy of '.$diskPath);

                    return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));
                }
                stream_copy_to_stream($srcStream, $dstStream);
                fclose($srcStream);
                fclose($dstStream);
                $absolutePath = $localTempPath;
            }

            // Verify the archive is actually a zip and can be opened, BEFORE we
            // do anything destructive. Prior behavior wiped the database first
            // and only then tried to open the archive. An invalid or corrupted
            // upload therefore destroyed the existing database and left the
            // install with an empty migrated schema, while the flow still
            // reported success because snipeit:restore returns exit 0 on
            // internal errors (see RestoreFromBackup::handle).
            //
            // Refuse to proceed if the PHP zip extension is not loaded. The
            // downstream snipeit:restore command needs ZipArchive too, so
            // running it without ext-zip would fail after the wipe.
            if (! class_exists(ZipArchive::class)) {
                Log::error('Restore aborted: PHP zip extension is not loaded, cannot validate archive before wiping database.');

                return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.zip_extension_missing'));
            }

            $zip = new ZipArchive;
            $openResult = $zip->open($absolutePath);
            if ($openResult !== true) {
                Log::warning('Restore aborted: archive at '.$absolutePath.' failed zip open with code '.$openResult);

                return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.archive_invalid', ['filename' => $filename]));
            }
            $zip->close();

            // grab the user's info so we can make sure they exist in the system
            $user = User::find(auth()->id());

            // Take a fresh pre-restore backup so we can point the operator at
            // it if the restore fails after we wipe. This is the mitigation
            // the pre-existing
            $requestedBackupFilename = 'pre-restore-'.date('Y-m-d-H-i-s').'.zip';
            // spatie prepends filename_prefix to the filename provided so this is the actual name on disk:
            $preRestoreBackupFilename = config('backup.backup.destination.filename_prefix').$requestedBackupFilename;
            $preRestoreDiskPath = $backupName.'/'.$preRestoreBackupFilename;
            $preBackupHint = config('filesystems.disks.backup.driver') === 'local'
                ? $backupDisk->path($preRestoreDiskPath)
                : 'backup disk ('.$preRestoreDiskPath.')';

            Log::debug('Running pre-restore backup: '.$preRestoreBackupFilename);
            $preBackupExit = Artisan::call('snipeit:backup', [
                '--filename' => $requestedBackupFilename,
                '--force' => true,
            ]);

            if ($preBackupExit !== 0 || ! $backupDisk->exists($preRestoreDiskPath)) {
                Log::warning('Pre-restore backup failed (exit '.$preBackupExit.'); aborting restore to protect existing data.');

                return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.pre_backup_failed'));
            }

            Log::warning('User '.auth()->user()->username.' is attempting to restore from: '.$absolutePath.' (pre-restore backup at '.$preBackupHint.')');

            $restore_params = [
                '--force' => true,
                '--no-progress' => true,
                'filename' => $absolutePath,
            ];

            if ($request->input('clean')) {
                Log::debug("Attempting 'clean' - first, guessing prefix...");
                Artisan::call('snipeit:restore', [
                    '--sanitize-guess-prefix' => true,
                    'filename' => $absolutePath,
                ]);
                $guess_prefix_output = Artisan::output();
                Log::debug("Sanitize output is: $guess_prefix_output");
                [$prefix, $_output] = explode("\n", $guess_prefix_output);
                Log::debug("prefix is: '$prefix'");
                $restore_params['--sanitize-with-prefix'] = $prefix;
            }

            Artisan::call('db:wipe', ['--force' => true]);

            // run the restore command
            $restoreExit = Artisan::call('snipeit:restore', $restore_params);
            $restoreOutput = Artisan::output();
            Log::debug('snipeit:restore output: '.$restoreOutput);

            // snipeit:restore returns 0 even on some internal errors, so we also
            // scan its output for its own "Could not access file" / "DB_CONNECTION
            // must be MySQL" style error strings.
            $restoreLooksFailed = $restoreExit !== 0 || str_contains(strtolower($restoreOutput), 'could not access file') || str_contains(strtolower($restoreOutput), 'db_connection must be mysql');

            if ($restoreLooksFailed) {
                Log::error('Restore failed after db:wipe. Pre-restore backup available at '.$preBackupHint);

                return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [
                    'backup' => $preRestoreBackupFilename,
                ]));
            }

            /* Run migrations */
            Log::debug('Migrating database...');
            $migrateExit = Artisan::call('migrate', ['--force' => true]);
            $migrate_output = Artisan::output();
            Log::debug($migrate_output);

            if ($migrateExit !== 0) {
                Log::error('Migrate failed after restore. Pre-restore backup available at '.$preBackupHint);

                return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.restore.failed_with_backup', [
                    'backup' => $preRestoreBackupFilename,
                ]));
            }

            // Check that the last migration in the migrations dir actually ran.
            $migrationFiles = glob(database_path('migrations/*.php'));
            if ($migrationFiles !== false && $migrationFiles !== []) {
                sort($migrationFiles);
                $newestMigration = basename((string) end($migrationFiles), '.php');
                $migrationApplied = DB::table('migrations')
                    ->where('migration', $newestMigration)
                    ->exists();
                if (! $migrationApplied) {
                    Log::error(
                        'Migrate reported success after restore, but the newest migration ('
                        .$newestMigration
                        .') is not recorded in the migrations table. Schema is out of date. Pre-restore backup available at '
                        .$preBackupHint
                    );

                    Auth::logout();

                    return redirect()->route('login')->with('error', trans('admin/settings/message.restore.failed_with_backup', [
                        'backup' => $preRestoreBackupFilename,
                    ]));
                }
            }

            $find_user = DB::table('users')->where('username', $user->username)->exists();

            if (! $find_user) {
                Log::warning('Attempting to restore user: '.$user->username);
                $new_user = $user->replicate();
                $new_user->push();
            } else {
                Log::debug('User: '.$user->username.' already exists.');
            }

            Log::debug('Logging all users out..');
            Artisan::call('snipeit:global-logout', ['--force' => true]);

            DB::table('users')->update(['remember_token' => null]);
            Auth::logout();

            return redirect()->route('login')->with('success', trans('admin/settings/message.restore.success'));
        } finally {
            // Temp copy only exists when we downloaded from a remote
            // driver. On the local driver $localTempPath stays null and
            // we skip the unlink entirely, so we don't accidentally
            // reach into the backup disk's own storage.
            if ($localTempPath !== null && file_exists($localTempPath)) {
                @unlink($localTempPath);
            }
            $this->releaseOperationLock(self::BACKUP_RESTORE_LOCK);
        }
    }

    /**
     * Return a form to allow a super admin to update settings.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v4.0]
     */
    public function getPurge(): View|RedirectResponse
    {

        Log::warning('User '.auth()->user()->username.' (ID: '.auth()->id().') is attempting a PURGE');

        if (config('app.allow_purge') == 'true') {
            return view('settings.purge-form');
        }

        return redirect()->route('settings.index')->with('error', trans('general.purge_not_allowed'));
    }

    /**
     * Purges soft-deletes.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v3.0]
     */
    public function postPurge(Request $request): RedirectResponse
    {
        Log::warning('User '.auth()->user()->username.' (ID'.auth()->id().') is attempting a PURGE');

        if (config('app.allow_purge') == 'true') {
            Log::debug('Purging is not allowed via the .env');

            if (! config('app.lock_passwords')) {

                if ($request->input('confirm_purge') == 'DELETE') {

                    Log::warning('User ID '.auth()->id().' initiated a PURGE!');
                    // Run a backup immediately before processing
                    Artisan::call('backup:run');
                    Artisan::call('snipeit:purge', ['--force' => 'true', '--no-interaction' => true]);
                    $output = Artisan::output();

                    return redirect()->route('settings.index')
                        ->with('output', $output)->with('success', trans('admin/settings/message.purge.success'));
                } else {
                    return redirect()->route('settings.purge.index')
                        ->with('error', trans('admin/settings/message.purge.validation_failed'));
                }
            } else {
                return redirect()->route('settings.index')
                    ->with('error', trans('general.feature_disabled'));
            }
        }

        Log::error('User '.auth()->user()->username.' (ID'.auth()->id().') is attempting to purge deleted data and is not authorized to.');

        // Nope.
        return redirect()->route('settings.index')
            ->with('error', trans('general.purge_not_allowed'));
    }

    /**
     * Returns a page with the API token generation interface.
     *
     * We created a controller method for this because closures aren't allowed
     * in the routes file if you want to be able to cache the routes.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v4.0]
     */
    public function api(): View
    {
        $personalAccessTokenCount = DB::table('oauth_access_tokens')
            ->join('oauth_clients', 'oauth_access_tokens.client_id', '=', 'oauth_clients.id')
            ->where('oauth_clients.personal_access_client', true)
            ->count();

        $setting = Setting::getSettings();
        $blockApiUserAgents = (bool) old('block_api_user_agents', $setting?->block_api_user_agents);
        $blockedApiUserAgents = old(
            'blocked_api_user_agents',
            $setting?->blocked_api_user_agents ?? implode("\n", Setting::DEFAULT_BLOCKED_API_USER_AGENTS),
        );
        $blockBlankApiUserAgents = (bool) old('block_blank_api_user_agents', $setting?->block_blank_api_user_agents);

        return view('settings.api', [
            'personalAccessTokenCount' => $personalAccessTokenCount,
            'setting' => $setting,
            'blockApiUserAgents' => $blockApiUserAgents,
            'blockedApiUserAgents' => $blockedApiUserAgents,
            'blockBlankApiUserAgents' => $blockBlankApiUserAgents,
        ]);
    }

    /**
     * Persist the API request-filter settings (User-Agent allow/block list)
     * from the API settings page.
     */
    public function postApiRequestFilters(Request $request): RedirectResponse
    {
        if (is_null($setting = Setting::getSettings())) {
            return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
        }

        // Check we're not on the public demo, and redirect without saving if we are.
        // Otherwise this could mess with the demo API explorer
        if (config('app.lock_passwords')) {
            return redirect()
                ->to(route('settings.oauth.index').'#api-request-filters')
                ->with('error', trans('general.feature_disabled'));
        }

        $setting->block_api_user_agents = $request->boolean('block_api_user_agents');
        $blockedUserAgents = trim((string) $request->input('blocked_api_user_agents', ''));
        $setting->blocked_api_user_agents = $blockedUserAgents === '' ? null : $blockedUserAgents;
        $setting->block_blank_api_user_agents = $request->boolean('block_blank_api_user_agents');

        if ($setting->save()) {
            return redirect()
                ->to(route('settings.oauth.index').'#api-request-filters')
                ->with('success', trans('admin/settings/message.update.success'));
        }

        return redirect()->back()->withInput()->withErrors($setting->getErrors());
    }

    /**
     * Revoke a personal access token from the admin OAuth settings page.
     */
    public function revokePersonalAccessToken(string $token): RedirectResponse
    {
        $tokenRow = DB::table('oauth_access_tokens')
            ->join('oauth_clients', 'oauth_access_tokens.client_id', '=', 'oauth_clients.id')
            ->where('oauth_access_tokens.id', $token)
            ->where('oauth_clients.personal_access_client', true)
            ->select(['oauth_access_tokens.id', 'oauth_access_tokens.user_id'])
            ->first();

        if ($tokenRow === null) {
            return redirect()
                ->to(route('settings.oauth.index').'#personal-access-tokens')
                ->with('error', trans('admin/settings/message.oauth.token_not_found'));
        }

        DB::table('oauth_access_tokens')
            ->where('id', $tokenRow->id)
            ->update(['revoked' => true]);

        $logaction = new Actionlog;
        $logaction->item_type = User::class;
        $logaction->item_id = $tokenRow->user_id;
        $logaction->target_type = User::class;
        $logaction->target_id = $tokenRow->user_id;
        $logaction->created_by = auth()->id();
        // $logaction->note = 'Token ID: ' . $tokenRow->id;
        $logaction->logaction(ActionType::TokenRevoked);

        return redirect()
            ->to(route('settings.oauth.index').'#personal-access-tokens')
            ->with('success', trans('admin/settings/message.oauth.token_revoked'));
    }

    /**
     * Unrevoke a personal access token from the admin OAuth settings page.
     */
    public function unrevokePersonalAccessToken(string $token): RedirectResponse
    {
        $tokenRow = DB::table('oauth_access_tokens')
            ->join('oauth_clients', 'oauth_access_tokens.client_id', '=', 'oauth_clients.id')
            ->where('oauth_access_tokens.id', $token)
            ->where('oauth_clients.personal_access_client', true)
            ->select(['oauth_access_tokens.id', 'oauth_access_tokens.user_id'])
            ->first();

        if ($tokenRow === null) {
            return redirect()
                ->to(route('settings.oauth.index').'#personal-access-tokens')
                ->with('error', trans('admin/settings/message.oauth.token_not_found'));
        }

        DB::table('oauth_access_tokens')
            ->where('id', $tokenRow->id)
            ->update(['revoked' => false]);

        $logaction = new Actionlog;
        $logaction->item_type = User::class;
        $logaction->item_id = $tokenRow->user_id;
        $logaction->target_type = User::class;
        $logaction->target_id = $tokenRow->user_id;
        $logaction->created_by = auth()->id();
        // $logaction->note = 'Token ID: ' . $tokenRow->id;
        $logaction->logaction(ActionType::TokenUnrevoked);

        return redirect()
            ->to(route('settings.oauth.index').'#personal-access-tokens')
            ->with('success', trans('admin/settings/message.oauth.token_unrevoked'));
    }

    /**
     * Test the email configuration.
     *
     * @author [A. Gianotto] [<[email protected]>]
     *
     * @since [v3.0]
     */
    public function ajaxTestEmail(): JsonResponse
    {
        try {
            (new User)->forceFill([
                'name' => config('mail.from.name'),
                'email' => config('mail.from.address'),
            ])->notify(new MailTest);
            Log::debug('Attempting to send mail to '.config('mail.from.address'));

            return response()->json(Helper::formatStandardApiResponse('success', null, trans('mail_sent.mail_sent')));
        } catch (\Exception $e) {
            Log::error('Mail sent from '.config('mail.from.address').' with errors '.$e->getMessage());
            Log::debug($e);

            return response()->json(Helper::formatStandardApiResponse('success', null, $e->getMessage()));
        }
    }

    /**
     * Get login attempts view
     *
     * @author [A. Gianotto] [<[email protected]>]
     */
    public function getLoginAttempts(): View
    {
        return view('settings.logins');
    }

    /**
     * Revoke an OAuth client from the admin OAuth settings page.
     */
    public function revokeOAuthClient(string $client): RedirectResponse
    {
        $oauthClient = DB::table('oauth_clients')
            ->where('id', $client)
            ->first();

        if ($oauthClient === null) {
            return redirect()
                ->to(route('settings.oauth.index').'#oauth-clients')
                ->with('error', trans('admin/settings/message.oauth.client_not_found'));
        }

        DB::table('oauth_clients')
            ->where('id', $client)
            ->update(['revoked' => true]);

        return redirect()
            ->to(route('settings.oauth.index').'#oauth-clients')
            ->with('success', trans('admin/settings/message.oauth.client_revoked'));
    }

    /**
     * Unrevoke an OAuth client from the admin OAuth settings page.
     */
    public function unrevokeOAuthClient(string $client): RedirectResponse
    {
        $oauthClient = DB::table('oauth_clients')
            ->where('id', $client)
            ->first();

        if ($oauthClient === null) {
            return redirect()
                ->to(route('settings.oauth.index').'#oauth-clients')
                ->with('error', trans('admin/settings/message.oauth.client_not_found'));
        }

        DB::table('oauth_clients')
            ->where('id', $client)
            ->update(['revoked' => false]);

        return redirect()
            ->to(route('settings.oauth.index').'#oauth-clients')
            ->with('success', trans('admin/settings/message.oauth.client_unrevoked'));
    }

    private function hasInvalidBackupFilename(string $filename): bool
    {
        if ($filename === '' || $filename === '.' || $filename === '..') {
            return true;
        }

        // Reject path separators in case a crafted value survives route decoding.
        return str_contains($filename, '/') || str_contains($filename, '\\');
    }
}