A free open source IT asset/license management system
Apply pint to Console directory
snipe8bce38b9187d
diff --git a/app/Console/Commands/CheckinLicensesFromAllUsers.php b/app/Console/Commands/CheckinLicensesFromAllUsers.phpindex 5e02bffb7b..285aab1a4b 100644--- a/app/Console/Commands/CheckinLicensesFromAllUsers.php+++ b/app/Console/Commands/CheckinLicensesFromAllUsers.php@@ -4,9 +4,7 @@ namespace App\Console\Commands;use App\Models\License;use App\Models\LicenseSeat;-use App\Models\User;use Illuminate\Console\Command;-use Illuminate\Database\Eloquent\Model;class CheckinLicensesFromAllUsers extends Command{diff --git a/app/Console/Commands/CheckoutLicenseToAllUsers.php b/app/Console/Commands/CheckoutLicenseToAllUsers.phpindex 801b3d187a..f0d8cfbb6a 100644--- a/app/Console/Commands/CheckoutLicenseToAllUsers.php+++ b/app/Console/Commands/CheckoutLicenseToAllUsers.php@@ -3,10 +3,8 @@namespace App\Console\Commands;use App\Models\License;-use App\Models\LicenseSeat;use App\Models\User;use Illuminate\Console\Command;-use Illuminate\Database\Eloquent\Model;class CheckoutLicenseToAllUsers extends Command{@@ -75,6 +73,7 @@ class CheckoutLicenseToAllUsers extends Commandif ($user->licenses->where('id', '=', $license_id)->count()) {$this->info($user->username.' already has this license checked out to them. Skipping... ');+continue;}diff --git a/app/Console/Commands/CleanIncorrectCheckoutAcceptances.php b/app/Console/Commands/CleanIncorrectCheckoutAcceptances.phpindex 30dca964c7..2bea433d84 100644--- a/app/Console/Commands/CleanIncorrectCheckoutAcceptances.php+++ b/app/Console/Commands/CleanIncorrectCheckoutAcceptances.php@@ -21,7 +21,7 @@ class CleanIncorrectCheckoutAcceptances extends Command** @var string*/- protected $description = "Delete checkout acceptances for checkouts to non-users";+ protected $description = 'Delete checkout acceptances for checkouts to non-users';/*** Execute the console command.@@ -35,30 +35,32 @@ class CleanIncorrectCheckoutAcceptances extends Command$this->withProgressBar(CheckoutAcceptance::all(), function ($checkoutAcceptance) use (&$deletions, &$skips) {$item = $checkoutAcceptance->checkoutable;$checkout_to_id = $checkoutAcceptance->assigned_to_id;- if(is_null($item)) {+ if (is_null($item)) {$this->info("'Checkoutable' Item is null, going to next record");- return; //'false' allegedly breaks execution entirely, so 'true' maybe doesn't? hrm. just straight return maybe?++ return; // 'false' allegedly breaks execution entirely, so 'true' maybe doesn't? hrm. just straight return maybe?}- if(get_class($item) == LicenseSeat::class) {+ if (get_class($item) == LicenseSeat::class) {$item = $item->license;}- foreach($item->assetlog()->where('action_type','checkout')->get() as $assetlog) {+ foreach ($item->assetlog()->where('action_type', 'checkout')->get() as $assetlog) {if ($assetlog->target_id == $checkout_to_id && $assetlog->target_type != User::class) {- //We have a checkout-to an ID for a non-User, which matches to an ID in the checkout_acceptances table+ // We have a checkout-to an ID for a non-User, which matches to an ID in the checkout_acceptances table- //now, let's compare the _times_ - are they close?- //I'm picking `created_at` over `action_date` because I'm more interested in when the actionlogs- //were _created_, not when they were alleged to have happened - those created_at times need to be within 'X' seconds of- //each other (currently 5)- if ($assetlog->created_at->diffInSeconds($checkoutAcceptance->created_at, true) <= 5) { //we're allowing for five _ish_ seconds of slop+ // now, let's compare the _times_ - are they close?+ // I'm picking `created_at` over `action_date` because I'm more interested in when the actionlogs+ // were _created_, not when they were alleged to have happened - those created_at times need to be within 'X' seconds of+ // each other (currently 5)+ if ($assetlog->created_at->diffInSeconds($checkoutAcceptance->created_at, true) <= 5) { // we're allowing for five _ish_ seconds of slop$deletions++;$checkoutAcceptance->forceDelete(); // HARD delete this record; it should have never been+return;} else {- //$this->info("The two records are too far apart");+ // $this->info("The two records are too far apart");}} else {- //$this->info("No match! checkout to id: " . $checkout_to_id." target_id: ".$assetlog->target_id." target_type: ".$assetlog->target_type);+ // $this->info("No match! checkout to id: " . $checkout_to_id." target_id: ".$assetlog->target_id." target_type: ".$assetlog->target_type);}}$skips++;diff --git a/app/Console/Commands/CleanOldCheckoutRequests.php b/app/Console/Commands/CleanOldCheckoutRequests.phpindex a96a58a349..ed9835419b 100644--- a/app/Console/Commands/CleanOldCheckoutRequests.php+++ b/app/Console/Commands/CleanOldCheckoutRequests.php@@ -8,6 +8,7 @@ use Illuminate\Console\Command;class CleanOldCheckoutRequests extends Command{private int $deletions = 0;+private int $skips = 0;/**@@ -44,12 +45,14 @@ class CleanOldCheckoutRequests extends Commandif ($this->shouldForceDelete($request)) {$request->forceDelete();$this->deletions++;+return;}if ($this->shouldSoftDelete($request)) {$request->delete();$this->deletions++;+return;}@@ -64,7 +67,7 @@ class CleanOldCheckoutRequests extends Commandprivate function shouldForceDelete(CheckoutRequest $request){// check if the requestable or user relationship is null- return !$request->requestable || !$request->user;+ return ! $request->requestable || ! $request->user;}private function shouldSoftDelete(CheckoutRequest $request)diff --git a/app/Console/Commands/CreateAdmin.php b/app/Console/Commands/CreateAdmin.phpindex 114f92dae4..1ae5163a60 100644--- a/app/Console/Commands/CreateAdmin.php+++ b/app/Console/Commands/CreateAdmin.php@@ -2,31 +2,28 @@namespace App\Console\Commands;+use App\Models\User;use Illuminate\Console\Command;-use \App\Models\User;-+use Illuminate\Support\Carbon;class CreateAdmin extends Command{-/** @mixin User **//*** App\Console\CreateAdmin+ ** @property mixed $first_name* @property string $last_name* @property string $username* @property string $email* @property string $permissions* @property string $password- * @property boolean $activated- * @property boolean $show_in_list- * @property boolean $autoassign_licenses- * @property \Illuminate\Support\Carbon|null $created_at+ * @property bool $activated+ * @property bool $show_in_list+ * @property bool $autoassign_licenses+ * @property Carbon|null $created_at* @property mixed $created_by*/---protected $signature = 'snipeit:create-admin {--first_name=} {--last_name=} {--email=} {--username=} {--password=} {show_in_list?} {autoassign_licenses?}';/**@@ -46,7 +43,6 @@ class CreateAdmin extends Commandparent::__construct();}-public function handle(){$first_name = $this->option('first_name');@@ -57,8 +53,6 @@ class CreateAdmin extends Command$show_in_list = $this->argument('show_in_list');$autoassign_licenses = $this->argument('autoassign_licenses');--if (($first_name == '') || ($last_name == '') || ($username == '') || ($email == '') || ($password == '')) {$this->info('ERROR: All fields are required.');} else {diff --git a/app/Console/Commands/FixBulkAccessoryCheckinActionLogEntries.php b/app/Console/Commands/FixBulkAccessoryCheckinActionLogEntries.phpindex 694d8d3b30..21e2c0c8df 100644--- a/app/Console/Commands/FixBulkAccessoryCheckinActionLogEntries.php+++ b/app/Console/Commands/FixBulkAccessoryCheckinActionLogEntries.php@@ -24,6 +24,7 @@ class FixBulkAccessoryCheckinActionLogEntries extends Commandprotected $description = 'This script attempts to fix timestamps and missing created_by values for bulk checkin entries in the log table';private bool $dryrun = false;+private bool $skipBackup = false;/**@@ -50,10 +51,11 @@ class FixBulkAccessoryCheckinActionLogEntries extends Commandif ($logs->isEmpty()) {$this->info('No logs found with incorrect timestamps.');+return 0;}- $this->info('Found ' . $logs->count() . ' logs with incorrect timestamps:');+ $this->info('Found '.$logs->count().' logs with incorrect timestamps:');$this->table(['ID', 'Created By', 'Created At', 'Updated At'],@@ -67,11 +69,11 @@ class FixBulkAccessoryCheckinActionLogEntries extends Command}));- if (!$this->dryrun && !$this->confirm('Update these logs?')) {+ if (! $this->dryrun && ! $this->confirm('Update these logs?')) {return 0;}- if (!$this->dryrun && !$this->skipBackup) {+ if (! $this->dryrun && ! $this->skipBackup) {$this->info('Backing up the database before making changes...');$this->call('snipeit:backup');}@@ -83,7 +85,7 @@ class FixBulkAccessoryCheckinActionLogEntries extends Commandforeach ($logs as $log) {$this->newLine();- $this->info('Processing log id:' . $log->id);+ $this->info('Processing log id:'.$log->id);// created_by was not being set for accessory bulk checkins// so let's see if there was another bulk checkin log@@ -106,7 +108,7 @@ class FixBulkAccessoryCheckinActionLogEntries extends Command$this->line(vsprintf('Updating log id:%s from %s to %s', [$log->id, $log->created_at, $log->updated_at]));$log->created_at = $log->updated_at;- if (!$this->dryrun) {+ if (! $this->dryrun) {Model::withoutTimestamps(function () use ($log) {$log->saveQuietly();});@@ -129,7 +131,7 @@ class FixBulkAccessoryCheckinActionLogEntries extends Command* This method attempts to find a bulk check in log that was* created at the same time as the log passed in.*/- private function getCreatedByAttributeFromSimilarLog(Actionlog $log): null|int+ private function getCreatedByAttributeFromSimilarLog(Actionlog $log): ?int{$similarLog = Actionlog::query()->whereNotNull('created_by')diff --git a/app/Console/Commands/FixDoubleEscape.php b/app/Console/Commands/FixDoubleEscape.phpindex 42a1765913..f7ab5b0112 100644--- a/app/Console/Commands/FixDoubleEscape.php+++ b/app/Console/Commands/FixDoubleEscape.php@@ -2,6 +2,21 @@namespace App\Console\Commands;+use App\Models\Accessory;+use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\Company;+use App\Models\Component;+use App\Models\Consumable;+use App\Models\Department;+use App\Models\Depreciation;+use App\Models\Group;+use App\Models\License;+use App\Models\Location;+use App\Models\Manufacturer;+use App\Models\Statuslabel;+use App\Models\Supplier;+use App\Models\User;use Illuminate\Console\Command;class FixDoubleEscape extends Command@@ -38,21 +53,21 @@ class FixDoubleEscape extends Commandpublic function handle(){$tables = [- \App\Models\Asset::class => ['name'],- \App\Models\License::class => ['name'],- \App\Models\Consumable::class => ['name'],- \App\Models\Accessory::class => ['name'],- \App\Models\Component::class => ['name'],- \App\Models\Company::class => ['name'],- \App\Models\Manufacturer::class => ['name'],- \App\Models\Supplier::class => ['name'],- \App\Models\Statuslabel::class => ['name'],- \App\Models\Depreciation::class => ['name'],- \App\Models\AssetModel::class => ['name'],- \App\Models\Group::class => ['name'],- \App\Models\Department::class => ['name'],- \App\Models\Location::class => ['name'],- \App\Models\User::class => ['first_name', 'last_name'],+ Asset::class => ['name'],+ License::class => ['name'],+ Consumable::class => ['name'],+ Accessory::class => ['name'],+ Component::class => ['name'],+ Company::class => ['name'],+ Manufacturer::class => ['name'],+ Supplier::class => ['name'],+ Statuslabel::class => ['name'],+ Depreciation::class => ['name'],+ AssetModel::class => ['name'],+ Group::class => ['name'],+ Department::class => ['name'],+ Location::class => ['name'],+ User::class => ['first_name', 'last_name'],];$count = [];diff --git a/app/Console/Commands/FixMismatchedAssetsAndLogs.php b/app/Console/Commands/FixMismatchedAssetsAndLogs.phpindex 34b6b3edfc..78e0ba5d71 100644--- a/app/Console/Commands/FixMismatchedAssetsAndLogs.php+++ b/app/Console/Commands/FixMismatchedAssetsAndLogs.php@@ -4,6 +4,7 @@ namespace App\Console\Commands;use App\Models\Actionlog;use App\Models\Asset;+use App\Models\User;use Illuminate\Console\Command;class FixMismatchedAssetsAndLogs extends Command@@ -56,26 +57,26 @@ class FixMismatchedAssetsAndLogs extends Command$mismatch_count = 0;$assets = Asset::whereNotNull('assigned_to')- ->where('assigned_type', '=', \App\Models\User::class)+ ->where('assigned_type', '=', User::class)->orderBy('id', 'ASC')->get();foreach ($assets as $asset) {// get the last checkout of the asset- if ($checkout_log = Actionlog::where('target_type', '=', \App\Models\User::class)+ if ($checkout_log = Actionlog::where('target_type', '=', User::class)->where('action_type', '=', 'checkout')->where('item_id', '=', $asset->id)->orderBy('created_at', 'DESC')->first()) {- // Now check for a subsequent checkin log - we want to ignore those- if (! $checkin_log = Actionlog::where('target_type', '=', \App\Models\User::class)- ->where('action_type', '=', 'checkin from')- ->where('item_id', '=', $asset->id)- ->whereDate('created_at', '>', $checkout_log->created_at)- ->orderBy('created_at', 'DESC')- ->first()) {+ // Now check for a subsequent checkin log - we want to ignore those+ if (! $checkin_log = Actionlog::where('target_type', '=', User::class)+ ->where('action_type', '=', 'checkin from')+ ->where('item_id', '=', $asset->id)+ ->whereDate('created_at', '>', $checkout_log->created_at)+ ->orderBy('created_at', 'DESC')+ ->first()) {- //print_r($asset);+ // print_r($asset);if ($checkout_log->target_id != $asset->assigned_to) {$this->error('Log ID: '.$checkout_log->id.' -- Asset ID '.$checkout_log->item_id.' SHOULD BE checked out to User '.$checkout_log->target_id.' but its assigned_to is '.$asset->assigned_to);@@ -90,7 +91,7 @@ class FixMismatchedAssetsAndLogs extends Command$mismatch_count++;}} else {- //$this->info('Asset ID '.$asset->id.': There is a checkin '.$checkin_log->created_at.' after this checkout '.$checkout_log->created_at);+ // $this->info('Asset ID '.$asset->id.': There is a checkin '.$checkin_log->created_at.' after this checkout '.$checkout_log->created_at);}}}diff --git a/app/Console/Commands/FixUpAssignedTypeWithoutAssignedTo.php b/app/Console/Commands/FixUpAssignedTypeWithoutAssignedTo.phpindex f368929f16..f9530f5e4e 100644--- a/app/Console/Commands/FixUpAssignedTypeWithoutAssignedTo.php+++ b/app/Console/Commands/FixUpAssignedTypeWithoutAssignedTo.php@@ -27,6 +27,6 @@ class FixUpAssignedTypeWithoutAssignedTo extends Commandpublic function handle(){DB::table('assets')->whereNotNull('assigned_type')->whereNull('assigned_to')->update(['assigned_type' => null]);- $this->info("Assets with an assigned_type but no assigned_to are fixed");+ $this->info('Assets with an assigned_type but no assigned_to are fixed');}}diff --git a/app/Console/Commands/FixupAssignedToWithoutAssignedType.php b/app/Console/Commands/FixupAssignedToWithoutAssignedType.phpindex ea3a55439a..5405e70e5c 100644--- a/app/Console/Commands/FixupAssignedToWithoutAssignedType.php+++ b/app/Console/Commands/FixupAssignedToWithoutAssignedType.php@@ -27,40 +27,42 @@ class FixupAssignedToWithoutAssignedType extends Command*/public function handle(){- $assets = Asset::whereNull("assigned_type")->whereNotNull("assigned_to")->withTrashed();+ $assets = Asset::whereNull('assigned_type')->whereNotNull('assigned_to')->withTrashed();$this->withProgressBar($assets->get(), function (Asset $asset) {- //now check each action log, from the most recent backwards, to find the last checkin or checkout- foreach($asset->log()->orderBy("id","desc")->get() as $action_log) {- if($this->option("debug")) {- $this->info("Asset id: " . $asset->id . " action log, action type is: " . $action_log->action_type);+ // now check each action log, from the most recent backwards, to find the last checkin or checkout+ foreach ($asset->log()->orderBy('id', 'desc')->get() as $action_log) {+ if ($this->option('debug')) {+ $this->info('Asset id: '.$asset->id.' action log, action type is: '.$action_log->action_type);}- switch($action_log->action_type) {+ switch ($action_log->action_type) {case 'checkin from':- if($this->option("debug")) {- $this->info("Doing a checkin for ".$asset->id);+ if ($this->option('debug')) {+ $this->info('Doing a checkin for '.$asset->id);}$asset->assigned_to = null;// if you have a required custom field, we still want to save, and we *don't* want an action_log$asset->saveQuietly();+return;case 'checkout':- if($this->option("debug")) {- $this->info("Doing a checkout for " . $asset->id . " picking target type: " . $action_log->target_type);+ if ($this->option('debug')) {+ $this->info('Doing a checkout for '.$asset->id.' picking target type: '.$action_log->target_type);}- if($asset->assigned_to != $action_log->target_id) {- $this->error("Asset's assigned_to does *NOT* match Action Log's target_id. \$asset->assigned_to=".$asset->assigned_to." vs. \$action_log->target_id=".$action_log->target_id);- //FIXME - do we abort here? Do we try to keep looking? I don't know, this means your data is *really* messed up...+ if ($asset->assigned_to != $action_log->target_id) {+ $this->error("Asset's assigned_to does *NOT* match Action Log's target_id. \$asset->assigned_to=".$asset->assigned_to.' vs. $action_log->target_id='.$action_log->target_id);+ // FIXME - do we abort here? Do we try to keep looking? I don't know, this means your data is *really* messed up...}$asset->assigned_type = $action_log->target_type;$asset->saveQuietly(); // see above+return;}}- $asset->assigned_to = null; //asset was never checked in or out in its lifetime - it stays 'checked in'- $asset->saveQuietly(); //see above+ $asset->assigned_to = null; // asset was never checked in or out in its lifetime - it stays 'checked in'+ $asset->saveQuietly(); // see above});$this->newLine();- $this->info("Assets assigned_type are fixed");+ $this->info('Assets assigned_type are fixed');}}diff --git a/app/Console/Commands/GeneratePersonalAccessToken.php b/app/Console/Commands/GeneratePersonalAccessToken.phpindex 63b246978e..84243a491e 100644--- a/app/Console/Commands/GeneratePersonalAccessToken.php+++ b/app/Console/Commands/GeneratePersonalAccessToken.php@@ -2,14 +2,13 @@namespace App\Console\Commands;-use Illuminate\Console\Command;use App\Models\User;-use Laravel\Passport\TokenRepository;+use Illuminate\Console\Command;use Illuminate\Support\Facades\DB;+use Laravel\Passport\TokenRepository;class GeneratePersonalAccessToken extends Command{-/*** The name and signature of the console command.*@@ -27,15 +26,13 @@ class GeneratePersonalAccessToken extends Command*/protected $description = 'This console command allows you to generate Personal API tokens to be used with the Snipe-IT JSON REST API on behalf of a user.';-/*** The token repository implementation.*- * @var \Laravel\Passport\TokenRepository+ * @var TokenRepository*/protected $tokenRepository;-/*** Create a new command instance.*@@ -56,11 +53,11 @@ class GeneratePersonalAccessToken extends Command{$accessTokenName = $this->option('name');- if ($accessTokenName=='') {+ if ($accessTokenName == '') {$accessTokenName = 'CLI Auth Token';}- if ($this->option('user_id')=='') {+ if ($this->option('user_id') == '') {return $this->error('ERROR: user_id cannot be blank.');}@@ -75,7 +72,7 @@ class GeneratePersonalAccessToken extends Command$this->warn('Your API Token has been created. Be sure to copy this token now, as it WILL NOT be accessible again.');- if ($token = DB::table('oauth_access_tokens')->where('user_id', '=', $user->id)->where('name','=',$accessTokenName)->orderBy('created_at', 'desc')->first()) {+ if ($token = DB::table('oauth_access_tokens')->where('user_id', '=', $user->id)->where('name', '=', $accessTokenName)->orderBy('created_at', 'desc')->first()) {$this->info('API Token ID: '.$token->id);}@@ -84,11 +81,8 @@ class GeneratePersonalAccessToken extends Command$this->info('API Token: '.$createAccessToken);}} else {- return $this->error('ERROR: Invalid user. API key was not created.');+ return $this->error('ERROR: Invalid user. API key was not created.');}---}}diff --git a/app/Console/Commands/ImportLocations.php b/app/Console/Commands/ImportLocations.phpindex 3bd28f7f25..d757f0813c 100644--- a/app/Console/Commands/ImportLocations.php+++ b/app/Console/Commands/ImportLocations.php@@ -46,7 +46,7 @@ class ImportLocations extends Command$filename = $this->argument('filename');$csv = Reader::createFromPath(storage_path('private_uploads/imports/').$filename, 'r');$this->info('Attempting to process: '.storage_path('private_uploads/imports/').$filename);- $csv->setHeaderOffset(0); //because we don't want to insert the header+ $csv->setHeaderOffset(0); // because we don't want to insert the header$results = $csv->getRecords();// Import parent location names first if they don't existdiff --git a/app/Console/Commands/KillAllSessions.php b/app/Console/Commands/KillAllSessions.phpindex 043be0fa18..7922985a77 100644--- a/app/Console/Commands/KillAllSessions.php+++ b/app/Console/Commands/KillAllSessions.php@@ -38,22 +38,23 @@ class KillAllSessions extends Commandpublic function handle(){- if (!$this->option('force') && !$this->confirm("****************************************************\nTHIS WILL FORCE A LOGIN FOR ALL LOGGED IN USERS.\n\nAre you SURE you wish to continue? ")) {- return $this->error("Session loss not confirmed");+ if (! $this->option('force') && ! $this->confirm("****************************************************\nTHIS WILL FORCE A LOGIN FOR ALL LOGGED IN USERS.\n\nAre you SURE you wish to continue? ")) {+ return $this->error('Session loss not confirmed');}- $session_files = glob(storage_path("framework/sessions/*"));+ $session_files = glob(storage_path('framework/sessions/*'));$count = 0;foreach ($session_files as $file) {- if (is_file($file))+ if (is_file($file)) {unlink($file);- $count++;+ }+ $count++;}\DB::table('users')->update(['remember_token' => null]);- $this->info($count. ' sessions cleared!');+ $this->info($count.' sessions cleared!');}}diff --git a/app/Console/Commands/LdapSync.php b/app/Console/Commands/LdapSync.phpindex b73f0754eb..bef0ca39e4 100644--- a/app/Console/Commands/LdapSync.php+++ b/app/Console/Commands/LdapSync.php@@ -5,11 +5,11 @@ namespace App\Console\Commands;use App\Models\Asset;use App\Models\Department;use App\Models\Group;-use Illuminate\Console\Command;-use App\Models\Setting;use App\Models\Ldap;-use App\Models\User;use App\Models\Location;+use App\Models\Setting;+use App\Models\User;+use Illuminate\Console\Command;use Illuminate\Support\Facades\Log;class LdapSync extends Command@@ -47,35 +47,34 @@ class LdapSync extends Command{// If LDAP enabled isn't set to 1 (ldap_enabled!=1) then we should cut this short immediately without going any further- if (Setting::getSettings()->ldap_enabled!='1') {+ if (Setting::getSettings()->ldap_enabled != '1') {$this->error('LDAP is not enabled. Aborting. See Settings > LDAP to enable it.');exit();}- ini_set('max_execution_time', env('LDAP_TIME_LIM', 600)); //600 seconds = 10 minutes+ ini_set('max_execution_time', env('LDAP_TIME_LIM', 600)); // 600 seconds = 10 minutesini_set('memory_limit', env('LDAP_MEM_LIM', '500M'));-// Map the LDAP attributes to the Snipe-IT user fields.$ldap_map = [- "username" => Setting::getSettings()->ldap_username_field,- "last_name" => Setting::getSettings()->ldap_lname_field,- "first_name" => Setting::getSettings()->ldap_fname_field,- "active_flag" => Setting::getSettings()->ldap_active_flag,- "emp_num" => Setting::getSettings()->ldap_emp_num,- "email" => Setting::getSettings()->ldap_email,- "phone" => Setting::getSettings()->ldap_phone_field,- "mobile" => Setting::getSettings()->ldap_mobile,- "jobtitle" => Setting::getSettings()->ldap_jobtitle,- "address" => Setting::getSettings()->ldap_address,- "city" => Setting::getSettings()->ldap_city,- "state" => Setting::getSettings()->ldap_state,- "zip" => Setting::getSettings()->ldap_zip,- "country" => Setting::getSettings()->ldap_country,- "location" => Setting::getSettings()->ldap_location,- "dept" => Setting::getSettings()->ldap_dept,- "manager" => Setting::getSettings()->ldap_manager,- "display_name" => Setting::getSettings()->ldap_display_name,+ 'username' => Setting::getSettings()->ldap_username_field,+ 'last_name' => Setting::getSettings()->ldap_lname_field,+ 'first_name' => Setting::getSettings()->ldap_fname_field,+ 'active_flag' => Setting::getSettings()->ldap_active_flag,+ 'emp_num' => Setting::getSettings()->ldap_emp_num,+ 'email' => Setting::getSettings()->ldap_email,+ 'phone' => Setting::getSettings()->ldap_phone_field,+ 'mobile' => Setting::getSettings()->ldap_mobile,+ 'jobtitle' => Setting::getSettings()->ldap_jobtitle,+ 'address' => Setting::getSettings()->ldap_address,+ 'city' => Setting::getSettings()->ldap_city,+ 'state' => Setting::getSettings()->ldap_state,+ 'zip' => Setting::getSettings()->ldap_zip,+ 'country' => Setting::getSettings()->ldap_country,+ 'location' => Setting::getSettings()->ldap_location,+ 'dept' => Setting::getSettings()->ldap_dept,+ 'manager' => Setting::getSettings()->ldap_manager,+ 'display_name' => Setting::getSettings()->ldap_display_name,];$ldap_default_group = Setting::getSettings()->ldap_default_group;@@ -101,13 +100,13 @@ class LdapSync extends Command/*** if a location ID has been specified, use that OU*/- if ( $this->option('location_id') ) {+ if ($this->option('location_id')) {- foreach($this->option('location_id') as $location_id){+ foreach ($this->option('location_id') as $location_id) {$location_ou = Location::where('id', '=', $location_id)->value('ldap_ou');$search_base = $location_ou;Log::debug('Importing users from specified location OU: \"'.$search_base.'\".');- }+ }}/**@@ -153,21 +152,21 @@ class LdapSync extends Command$default_location = null;if ($this->option('location') != '') {if ($default_location = Location::where('name', '=', $this->option('location'))->first()) {- Log::debug('Location name ' . $this->option('location') . ' passed');+ Log::debug('Location name '.$this->option('location').' passed');Log::debug('Importing to '.$default_location->name.' ('.$default_location->id.')');}} elseif ($this->option('location_id')) {- //TODO - figure out how or why this is an array?- foreach($this->option('location_id') as $location_id) {+ // TODO - figure out how or why this is an array?+ foreach ($this->option('location_id') as $location_id) {if ($default_location = Location::where('id', '=', $location_id)->first()) {- Log::debug('Location ID ' . $location_id . ' passed');+ Log::debug('Location ID '.$location_id.' passed');Log::debug('Importing to '.$default_location->name.' ('.$default_location->id.')');}}}- if (!isset($default_location)) {+ if (! isset($default_location)) {Log::debug('That location is invalid or a location was not provided, so no location will be assigned by default.');}@@ -208,17 +207,17 @@ class LdapSync extends Command}$usernames = [];for ($i = 0; $i < $location_users['count']; $i++) {- if (array_key_exists($ldap_map["username"], $location_users[$i])) {+ if (array_key_exists($ldap_map['username'], $location_users[$i])) {$location_users[$i]['ldap_location_override'] = true;$location_users[$i]['location_id'] = $ldap_loc['id'];- $usernames[] = $location_users[$i][$ldap_map["username"]][0];+ $usernames[] = $location_users[$i][$ldap_map['username']][0];}}// Delete located users from the general group.foreach ($results as $key => $generic_entry) {- if ((is_array($generic_entry)) && (array_key_exists($ldap_map["username"], $generic_entry))) {- if (in_array($generic_entry[$ldap_map["username"]][0], $usernames)) {+ if ((is_array($generic_entry)) && (array_key_exists($ldap_map['username'], $generic_entry))) {+ if (in_array($generic_entry[$ldap_map['username']][0], $usernames)) {unset($results[$key]);}}@@ -232,42 +231,41 @@ class LdapSync extends Command$manager_cache = [];- if($ldap_default_group != null) {+ if ($ldap_default_group != null) {$default = Group::find($ldap_default_group);- if (!$default) {+ if (! $default) {$ldap_default_group = null; // un-set the default group if that group doesn't exist}}-// Assign the mapped LDAP attributes for each user to the Snipe-IT user fieldsfor ($i = 0; $i < $results['count']; $i++) {$item = [];- $item['username'] = $results[$i][$ldap_map["username"]][0] ?? null;- $item['display_name'] = $results[$i][$ldap_map["display_name"]][0] ?? null;- $item['employee_number'] = $results[$i][$ldap_map["emp_num"]][0] ?? null;- $item['lastname'] = $results[$i][$ldap_map["last_name"]][0] ?? null;- $item['firstname'] = $results[$i][$ldap_map["first_name"]][0] ?? null;- $item['email'] = $results[$i][$ldap_map["email"]][0] ?? null;+ $item['username'] = $results[$i][$ldap_map['username']][0] ?? null;+ $item['display_name'] = $results[$i][$ldap_map['display_name']][0] ?? null;+ $item['employee_number'] = $results[$i][$ldap_map['emp_num']][0] ?? null;+ $item['lastname'] = $results[$i][$ldap_map['last_name']][0] ?? null;+ $item['firstname'] = $results[$i][$ldap_map['first_name']][0] ?? null;+ $item['email'] = $results[$i][$ldap_map['email']][0] ?? null;$item['ldap_location_override'] = $results[$i]['ldap_location_override'] ?? null;$item['location_id'] = $results[$i]['location_id'] ?? null;- $item['telephone'] = $results[$i][$ldap_map["phone"]][0] ?? null;- $item['mobile'] = $results[$i][$ldap_map["mobile"]][0] ?? null;- $item['jobtitle'] = $results[$i][$ldap_map["jobtitle"]][0] ?? null;- $item['address'] = $results[$i][$ldap_map["address"]][0] ?? null;- $item['city'] = $results[$i][$ldap_map["city"]][0] ?? null;- $item['state'] = $results[$i][$ldap_map["state"]][0] ?? null;- $item['country'] = $results[$i][$ldap_map["country"]][0] ?? null;- $item['zip'] = $results[$i][$ldap_map["zip"]][0] ?? null;- $item['department'] = $results[$i][$ldap_map["dept"]][0] ?? null;- $item['manager'] = $results[$i][$ldap_map["manager"]][0] ?? null;- $item['location'] = $results[$i][$ldap_map["location"]][0] ?? null;- $location = $default_location; //initially, set '$location' to the default_location (which may just be null)+ $item['telephone'] = $results[$i][$ldap_map['phone']][0] ?? null;+ $item['mobile'] = $results[$i][$ldap_map['mobile']][0] ?? null;+ $item['jobtitle'] = $results[$i][$ldap_map['jobtitle']][0] ?? null;+ $item['address'] = $results[$i][$ldap_map['address']][0] ?? null;+ $item['city'] = $results[$i][$ldap_map['city']][0] ?? null;+ $item['state'] = $results[$i][$ldap_map['state']][0] ?? null;+ $item['country'] = $results[$i][$ldap_map['country']][0] ?? null;+ $item['zip'] = $results[$i][$ldap_map['zip']][0] ?? null;+ $item['department'] = $results[$i][$ldap_map['dept']][0] ?? null;+ $item['manager'] = $results[$i][$ldap_map['manager']][0] ?? null;+ $item['location'] = $results[$i][$ldap_map['location']][0] ?? null;+ $location = $default_location; // initially, set '$location' to the default_location (which may just be null)// ONLY if you are using the "ldap_location" option *AND* you have an actual result- if ($ldap_map["location"] && $item['location']) {+ if ($ldap_map['location'] && $item['location']) {$location = Location::firstOrCreate(['name' => $item['location'],]);@@ -289,58 +287,58 @@ class LdapSync extends Command$item['createorupdate'] = 'created';}- //If a sync option is not filled in on the LDAP settings don't populate the user field- if($ldap_map["username"] != null){+ // If a sync option is not filled in on the LDAP settings don't populate the user field+ if ($ldap_map['username'] != null) {$user->username = $item['username'];}- if($ldap_map["display_name"] != null){+ if ($ldap_map['display_name'] != null) {$user->display_name = $item['display_name'];}- if($ldap_map["last_name"] != null){+ if ($ldap_map['last_name'] != null) {$user->last_name = $item['lastname'];}- if($ldap_map["first_name"] != null){+ if ($ldap_map['first_name'] != null) {$user->first_name = $item['firstname'];}- if($ldap_map["emp_num"] != null){+ if ($ldap_map['emp_num'] != null) {$user->employee_num = e($item['employee_number']);}- if($ldap_map["email"] != null){+ if ($ldap_map['email'] != null) {$user->email = $item['email'];}- if($ldap_map["phone"] != null){+ if ($ldap_map['phone'] != null) {$user->phone = $item['telephone'];}- if($ldap_map["mobile"] != null){+ if ($ldap_map['mobile'] != null) {$user->mobile = $item['mobile'];}- if($ldap_map["jobtitle"] != null){+ if ($ldap_map['jobtitle'] != null) {$user->jobtitle = $item['jobtitle'];}- if($ldap_map["address"] != null){+ if ($ldap_map['address'] != null) {$user->address = $item['address'];}- if($ldap_map["city"] != null){+ if ($ldap_map['city'] != null) {$user->city = $item['city'];}- if($ldap_map["state"] != null){+ if ($ldap_map['state'] != null) {$user->state = $item['state'];}- if($ldap_map["country"] != null){+ if ($ldap_map['country'] != null) {$user->country = $item['country'];}- if($ldap_map["zip"] != null){+ if ($ldap_map['zip'] != null) {$user->zip = $item['zip'];}- if($ldap_map["dept"] != null){+ if ($ldap_map['dept'] != null) {$user->department_id = $department->id;}- if($ldap_map["location"] != null){+ if ($ldap_map['location'] != null) {$user->location_id = $location?->id;}- if($ldap_map["manager"] != null){- if($item['manager'] != null) {+ if ($ldap_map['manager'] != null) {+ if ($item['manager'] != null) {// Check Cache firstif (isset($manager_cache[$item['manager']])) {// found in cache; use that and avoid extra lookups@@ -350,23 +348,23 @@ class LdapSync extends Commandtry {$ldap_manager = Ldap::findLdapUsers($item['manager'], -1, $this->option('filter'));} catch (\Exception $e) {- Log::warning("Manager lookup caused an exception: " . $e->getMessage() . ". Falling back to direct username lookup");+ Log::warning('Manager lookup caused an exception: '.$e->getMessage().'. Falling back to direct username lookup');// Hail-mary for Okta manager 'shortnames' - will only work if// Okta configuration is using full email-address-style usernames$ldap_manager = [- "count" => 1,+ 'count' => 1,0 => [- $ldap_map["username"] => [$item['manager']]- ]+ $ldap_map['username'] => [$item['manager']],+ ],];}-+$add_manager_to_cache = true;- if ($ldap_manager["count"] > 0) {+ if ($ldap_manager['count'] > 0) {try {// Get the Manager's username// PHP LDAP returns every LDAP attribute as an array, and 90% of the time it's an array of just one item. But, hey, it's an array.- $ldapManagerUsername = $ldap_manager[0][$ldap_map["username"]][0];+ $ldapManagerUsername = $ldap_manager[0][$ldap_map['username']][0];// Get User from Manager username.$ldap_manager = User::where('username', $ldapManagerUsername)->first();@@ -377,11 +375,11 @@ class LdapSync extends Command}} catch (\Exception $e) {$add_manager_to_cache = false;- \Log::warning('Handling ldap manager ' . $item['manager'] . ' caused an exception: ' . $e->getMessage() . '. Continuing synchronization.');+ \Log::warning('Handling ldap manager '.$item['manager'].' caused an exception: '.$e->getMessage().'. Continuing synchronization.');}}if ($add_manager_to_cache) {- $manager_cache[$item['manager']] = $ldap_manager && isset($ldap_manager->id) ? $ldap_manager->id : null; // Store results in cache, even if 'failed'+ $manager_cache[$item['manager']] = $ldap_manager && isset($ldap_manager->id) ? $ldap_manager->id : null; // Store results in cache, even if 'failed'}}@@ -389,18 +387,18 @@ class LdapSync extends Command}// Sync activated state for Active Directory.- if (!empty($ldap_map["active_flag"])) { // IF we have an 'active' flag set....+ if (! empty($ldap_map['active_flag'])) { // IF we have an 'active' flag set....// ....then *most* things that are truthy will activate the user. Anything falsey will deactivate them.// (Specifically, we don't handle a value of '0.0' correctly)- $raw_value = @$results[$i][$ldap_map["active_flag"]][0];+ $raw_value = @$results[$i][$ldap_map['active_flag']][0];$filter_var = filter_var($raw_value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);-+$boolean_cast = (bool) $raw_value;-+if (Setting::getSettings()->ldap_invert_active_flag === 1) {// Because ldap_active_flag is set, if filter_var is true or boolean_cast is true, then user is suspended- $user->activated = !($filter_var ?? $boolean_cast);- }else{+ $user->activated = ! ($filter_var ?? $boolean_cast);+ } else {$user->activated = $filter_var ?? $boolean_cast; // if filter_var() was true or false, use that. If it's null, use the $boolean_cast}@@ -408,7 +406,6 @@ class LdapSync extends Command// ....otherwise, (ie if no 'active' LDAP flag is defined), IF the UAC setting exists,// ....then use the UAC setting on the account to determine can-log-in vs. cannot-log-in-/* The following is _probably_ the correct logic, but we can't use it becausesome users may have been dependent upon the previous behavior, and thiscould cause additional access to be available to users they don't want@@ -434,7 +431,7 @@ class LdapSync extends Command'262688', // 0x40220 NORMAL_ACCOUNT, PASSWD_NOTREQD, SMARTCARD_REQUIRED'328192', // 0x50200 NORMAL_ACCOUNT, SMARTCARD_REQUIRED, DONT_EXPIRE_PASSWORD'328224', // 0x50220 NORMAL_ACCOUNT, PASSWD_NOT_REQD, SMARTCARD_REQUIRED, DONT_EXPIRE_PASSWORD- '4194816',// 0x400200 NORMAL_ACCOUNT, DONT_REQ_PREAUTH+ '4194816', // 0x400200 NORMAL_ACCOUNT, DONT_REQ_PREAUTH'4260352', // 0x410200 NORMAL_ACCOUNT, DONT_EXPIRE_PASSWORD, DONT_REQ_PREAUTH'1049088', // 0x100200 NORMAL_ACCOUNT, NOT_DELEGATED'1114624', // 0x110200 NORMAL_ACCOUNT, DONT_EXPIRE_PASSWORD, NOT_DELEGATED,@@ -445,14 +442,13 @@ class LdapSync extends Command} /* implied 'else' here - leave the $user->activated flag alone. Newly-created accounts will be active.already-existing accounts will be however the administrator has set them */-if ($item['ldap_location_override'] == true) {$user->location_id = $item['location_id'];- } elseif ((isset($location)) && (!empty($location))) {+ } elseif ((isset($location)) && (! empty($location))) {if ((is_array($location)) && (array_key_exists('id', $location))) {$user->location_id = $location['id'];} elseif (is_object($location)) {- $user->location_id = $location->id; //THIS is the magic line, this should do it.+ $user->location_id = $location->id; // THIS is the magic line, this should do it.}}// TODO - should we be NULLING locations if $location is really `null`, and that's what we came up with?@@ -468,13 +464,13 @@ class LdapSync extends Command$item['note'] = $item['createorupdate'];$item['status'] = 'success';if ($item['createorupdate'] === 'created' && $ldap_default_group) {- // Check if the relationship already exists- if (!$user->groups()->where('group_id', $ldap_default_group)->exists()) {- $user->groups()->attach($ldap_default_group);+ // Check if the relationship already exists+ if (! $user->groups()->where('group_id', $ldap_default_group)->exists()) {+ $user->groups()->attach($ldap_default_group);}}-- //updates assets location based on user's location++ // updates assets location based on user's locationif ($user->wasChanged('location_id')) {foreach ($user->assets as $asset) {$asset->location_id = $user->location_id;diff --git a/app/Console/Commands/LdapTroubleshooter.php b/app/Console/Commands/LdapTroubleshooter.phpindex cb19ff8c53..6921e46499 100644--- a/app/Console/Commands/LdapTroubleshooter.php+++ b/app/Console/Commands/LdapTroubleshooter.php@@ -2,29 +2,32 @@namespace App\Console\Commands;-use Illuminate\Console\Command;+use App\Models\Ldap;use App\Models\Setting;use Exception;+use Illuminate\Console\Command;use Illuminate\Support\Facades\Crypt;-use App\Models\Ldap;/*** Check if a given ip is in a network- * @param string $ip IP to check in IPV4 format eg. 127.0.0.1- * @param string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed- * @return boolean true if the ip is in this range / false if not.+ *+ * @param string $ip IP to check in IPV4 format eg. 127.0.0.1+ * @param string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed+ * @return bool true if the ip is in this range / false if not.*/-function ip_in_range( $ip, $range ) {- if ( strpos( $range, '/' ) == false ) {- $range .= '/32';- }- // $range is in IP/CIDR format eg 127.0.0.1/24- list( $range, $netmask ) = explode( '/', $range, 2 );- $range_decimal = ip2long( $range );- $ip_decimal = ip2long( $ip );- $wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1;- $netmask_decimal = ~ $wildcard_decimal;- return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) );+function ip_in_range($ip, $range)+{+ if (strpos($range, '/') == false) {+ $range .= '/32';+ }+ // $range is in IP/CIDR format eg 127.0.0.1/24+ [$range, $netmask] = explode('/', $range, 2);+ $range_decimal = ip2long($range);+ $ip_decimal = ip2long($ip);+ $wildcard_decimal = pow(2, (32 - $netmask)) - 1;+ $netmask_decimal = ~$wildcard_decimal;++ return ($ip_decimal & $netmask_decimal) == ($range_decimal & $netmask_decimal);}// NOTE - this function was shamelessly stolen from this gist: https://gist.github.com/tott/7684443@@ -33,10 +36,10 @@ function ip_in_range( $ip, $range ) {*/function parenthesized_filter($filter){- if(substr($filter,0,1) == "(" ) {+ if (substr($filter, 0, 1) == '(') {return $filter;} else {- return "(".$filter.")";+ return '('.$filter.')';}}@@ -74,41 +77,44 @@ class LdapTroubleshooter extends Command/*** Output something *only* if debug is enabled- *+ ** @return void*/public function debugout($string){- if($this->option('debug')) {+ if ($this->option('debug')) {$this->line($string);}}/*** Clean the results from ldap_get_entries into something useful- * @param array $array+ *+ * @param array $array* @return array*/- public function ldap_results_cleaner ($array) {+ public function ldap_results_cleaner($array)+ {$cleaned = [];- for($i = 0; $i < $array['count']; $i++) {+ for ($i = 0; $i < $array['count']; $i++) {$row = $array[$i];$clean_row = [];- foreach($row AS $key => $val ) {- $this->debugout("Key is: ".$key);- if($key == "count" || is_int($key) || $key == "dn") {+ foreach ($row as $key => $val) {+ $this->debugout('Key is: '.$key);+ if ($key == 'count' || is_int($key) || $key == 'dn') {$this->debugout(" and we're gonna skip it\n");+continue;}$this->debugout(" And that seems fine.\n");- if(array_key_exists('count',$val)) {- if($val['count'] == 1) {+ if (array_key_exists('count', $val)) {+ if ($val['count'] == 1) {$clean_row[$key] = $val[0];} else {- unset($val['count']); //these counts are annoying+ unset($val['count']); // these counts are annoying$elements = [];- foreach($val as $entry) {- if(isset($ldap_constants[$entry])) {+ foreach ($val as $entry) {+ if (isset($ldap_constants[$entry])) {$elements[] = $ldap_constants[$entry];} else {$elements[] = $entry;@@ -122,6 +128,7 @@ class LdapTroubleshooter extends Command}$cleaned[$i] = $clean_row;}+return $cleaned;}@@ -132,58 +139,58 @@ class LdapTroubleshooter extends Command*/public function handle(){- if($this->option('trace')) {- ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);+ if ($this->option('trace')) {+ ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);}$settings = Setting::getSettings();$this->settings = $settings;- if($this->option('ldap-search')) {- if(!$this->option('force')) {+ if ($this->option('ldap-search')) {+ if (! $this->option('force')) {$confirmation = $this->confirm('WARNING: This command will display your LDAP password on your terminal. Are you sure this is ok?');- if(!$confirmation) {+ if (! $confirmation) {$this->error('ABORTING');exit(-1);}}$output = [];- if($settings->ldap_server_cert_ignore) {- $this->line("# Ignoring server certificate validity");- $output[] = "LDAPTLS_REQCERT=never";+ if ($settings->ldap_server_cert_ignore) {+ $this->line('# Ignoring server certificate validity');+ $output[] = 'LDAPTLS_REQCERT=never';}- if($settings->ldap_client_tls_cert && $settings->ldap_client_tls_key) {- $this->line("# Adding LDAP Client Certificate and Key");- $output[] = "LDAPTLS_CERT=storage/ldap_client_tls.cert";- $output[] = "LDAPTLS_KEY=storage/ldap_client_tls.key";+ if ($settings->ldap_client_tls_cert && $settings->ldap_client_tls_key) {+ $this->line('# Adding LDAP Client Certificate and Key');+ $output[] = 'LDAPTLS_CERT=storage/ldap_client_tls.cert';+ $output[] = 'LDAPTLS_KEY=storage/ldap_client_tls.key';}- $output[] = "ldapsearch";- $output[] = "-H ".$settings->ldap_server;- $output[] = "-x";- $output[] = "-b ".escapeshellarg($settings->ldap_basedn);- $output[] = "-D ".escapeshellarg($settings->ldap_uname);+ $output[] = 'ldapsearch';+ $output[] = '-H '.$settings->ldap_server;+ $output[] = '-x';+ $output[] = '-b '.escapeshellarg($settings->ldap_basedn);+ $output[] = '-D '.escapeshellarg($settings->ldap_uname);try {$w = Crypt::Decrypt($settings->ldap_pword);- } catch (\Exception $e) {- $this->warn("Could not decrypt password. This usually means an LDAP password was not set or the APP_KEY was changed since the LDAP pasword was last saved. Aborting.");+ } catch (Exception $e) {+ $this->warn('Could not decrypt password. This usually means an LDAP password was not set or the APP_KEY was changed since the LDAP pasword was last saved. Aborting.');exit(0);}- $output[] = "-w ". escapeshellarg($w);+ $output[] = '-w '.escapeshellarg($w);$output[] = escapeshellarg(parenthesized_filter($settings->ldap_filter));- if($settings->ldap_tls) {- $this->line("# adding STARTTLS option");- $output[] = "-Z";+ if ($settings->ldap_tls) {+ $this->line('# adding STARTTLS option');+ $output[] = '-Z';}- $output[] = "-v";+ $output[] = '-v';$this->line("\n");- $this->line(implode(" \\\n",$output));+ $this->line(implode(" \\\n", $output));exit(0);}- //PHP Version check for warning+ // PHP Version check for warning$php_version = phpversion();- list($major, $minor, $patch) = explode('.', $php_version);+ [$major, $minor, $patch] = explode('.', $php_version);if ($major < 8 ||($major == 8 && $minor < 3) ||@@ -191,22 +198,22 @@ class LdapTroubleshooter extends Command($major == 8 && $minor == 4 && $patch < 7)) {$this->warn("PHP Version: $php_version WARNING - Versions before 8.3.21 or 8.4.7 will return INCONSISTENT results!");- if (!$this->confirm("Are you sure you wish to continue?")) {- $this->warn("ABORTING");+ if (! $this->confirm('Are you sure you wish to continue?')) {+ $this->warn('ABORTING');exit(-1);}}- if(!$this->option('force')) {+ if (! $this->option('force')) {$confirmation = $this->confirm('WARNING: This command will make several attempts to connect to your LDAP server. Are you sure this is ok?');- if(!$confirmation) {+ if (! $confirmation) {$this->error('ABORTING');exit(-1);}}- //$this->line(print_r($settings,true));- $this->line("STAGE 1: Checking settings");- if(!$settings->ldap_enabled) {+ // $this->line(print_r($settings,true));+ $this->line('STAGE 1: Checking settings');+ if (! $settings->ldap_enabled) {$this->error("WARNING: Snipe-IT's LDAP setting is not turned on. (That may be OK if you're still trying to figure out settings)");}@@ -214,123 +221,126 @@ class LdapTroubleshooter extends Commandtry {$ldap_conn = ldap_connect($settings->ldap_server);} catch (Exception $e) {- $this->error("WARNING: Exception caught when executing 'ldap_connect()' - ".$e->getMessage().". We will try to guess.");+ $this->error("WARNING: Exception caught when executing 'ldap_connect()' - ".$e->getMessage().'. We will try to guess.');}- if(!$ldap_conn) {- $this->error("WARNING: LDAP Server setting of: ".$settings->ldap_server." cannot be parsed. We will try to guess.");- //exit(-1);+ if (! $ldap_conn) {+ $this->error('WARNING: LDAP Server setting of: '.$settings->ldap_server.' cannot be parsed. We will try to guess.');+ // exit(-1);}- //since we never use $ldap_conn again, we don't have to ldap_unbind() it (it's not even connected, tbh - that only happens at bind-time)+ // since we never use $ldap_conn again, we don't have to ldap_unbind() it (it's not even connected, tbh - that only happens at bind-time)$parsed = parse_url($settings->ldap_server);- if(@$parsed['scheme'] != 'ldap' && @$parsed['scheme'] != 'ldaps') {+ if (@$parsed['scheme'] != 'ldap' && @$parsed['scheme'] != 'ldaps') {$this->error("WARNING: LDAP URL Scheme of '".@$parsed['scheme']."' is probably incorrect; should usually be ldap or ldaps");}- if(!@$parsed['host']) {- $this->error("ERROR: Cannot determine hostname or IP from ldap URL: ".$settings->ldap_server.". ABORTING.");+ if (! @$parsed['host']) {+ $this->error('ERROR: Cannot determine hostname or IP from ldap URL: '.$settings->ldap_server.'. ABORTING.');exit(-1);} else {- $this->info("Determined LDAP hostname to be: ".$parsed['host']);+ $this->info('Determined LDAP hostname to be: '.$parsed['host']);}$raw_ips = [];if (inet_pton($parsed['host']) !== false) {- $this->line($parsed['host'] . " already looks like an address; skipping DNS lookup");+ $this->line($parsed['host'].' already looks like an address; skipping DNS lookup');$raw_ips[] = $parsed['host'];} else {- $this->line("Performing DNS lookup of: " . $parsed['host']);+ $this->line('Performing DNS lookup of: '.$parsed['host']);$ips = dns_get_record($parsed['host']);- //$this->info("Host IP is: ".print_r($ips,true));+ // $this->info("Host IP is: ".print_r($ips,true));- if (!$ips || count($ips) == 0) {- $this->error("ERROR: DNS lookup of host: " . $parsed['host'] . " has failed. ABORTING.");+ if (! $ips || count($ips) == 0) {+ $this->error('ERROR: DNS lookup of host: '.$parsed['host'].' has failed. ABORTING.');exit(-1);}- $this->debugout("IP's? " . print_r($ips, true));+ $this->debugout("IP's? ".print_r($ips, true));foreach ($ips as $ip) {- if (!isset($ip['ip'])) {+ if (! isset($ip['ip'])) {continue;}$raw_ips[] = $ip['ip'];}}foreach ($raw_ips as $ip) {- if ($ip == "127.0.0.1") {- $this->error("WARNING: Using the localhost IP as the LDAP server. This is usually wrong");+ if ($ip == '127.0.0.1') {+ $this->error('WARNING: Using the localhost IP as the LDAP server. This is usually wrong');}if (ip_in_range($ip, '10.0.0.0/8') || ip_in_range($ip, '192.168.0.0/16') || ip_in_range($ip, '172.16.0.0/12')) {- $this->error("WARNING: Using an RFC1918 Private address for LDAP server. This may be correct, but it can be a problem if your Snipe-IT instance is not hosted on your private network");+ $this->error('WARNING: Using an RFC1918 Private address for LDAP server. This may be correct, but it can be a problem if your Snipe-IT instance is not hosted on your private network');}}- $this->line("STAGE 2: Checking basic network connectivity");+ $this->line('STAGE 2: Checking basic network connectivity');$ports = [636, 389];- if(@$parsed['port'] && !in_array($parsed['port'],$ports)) {+ if (@$parsed['port'] && ! in_array($parsed['port'], $ports)) {$ports[] = $parsed['port'];}- $open_ports=[];- foreach($ports as $port ) {+ $open_ports = [];+ foreach ($ports as $port) {$errno = 0;$errstr = '';$timeout = 30.0;$result = '';- $this->line("Attempting to connect to port: " . $port . " - may take up to $timeout seconds");+ $this->line('Attempting to connect to port: '.$port." - may take up to $timeout seconds");try {$result = fsockopen($parsed['host'], $port, $errno, $errstr, 30.0);- } catch(Exception $e) {- $this->error("Exception: ".$e->getMessage());+ } catch (Exception $e) {+ $this->error('Exception: '.$e->getMessage());}- if($result) {- $this->info("Success!");+ if ($result) {+ $this->info('Success!');$open_ports[] = $port;} else {$this->error("WARNING: Cannot connect to port: $port - $errstr ($errno)");}}- if(count($open_ports) == 0) {- $this->error("ERROR - no open ports. ABORTING.");+ if (count($open_ports) == 0) {+ $this->error('ERROR - no open ports. ABORTING.');exit(-1);}- $this->line("STAGE 3: Determine encryption algorithm, if any");+ $this->line('STAGE 3: Determine encryption algorithm, if any');$ldap_urls = []; // [url, cert-check?, start_tls?]$pretty_ldap_urls = [];- foreach($open_ports as $port) {+ foreach ($open_ports as $port) {$this->line("Trying TLS first for port $port");- $ldap_url = "ldaps://".$parsed['host'].":$port";- if($this->test_anonymous_bind($ldap_url)) {+ $ldap_url = 'ldaps://'.$parsed['host'].":$port";+ if ($this->test_anonymous_bind($ldap_url)) {$this->info("Anonymous bind succesful to $ldap_url!");- $ldap_urls[] = [ $ldap_url, true, false ];- $pretty_ldap_urls[] = [$ldap_url, "enabled", "n/a (no)"];+ $ldap_urls[] = [$ldap_url, true, false];+ $pretty_ldap_urls[] = [$ldap_url, 'enabled', 'n/a (no)'];+continue; // TODO - lots of copypasta in these if(test_anonymous_bind()) routines...} else {$this->error("WARNING: Failed to bind to $ldap_url - trying without certificate checks.");}- if($this->test_anonymous_bind($ldap_url, false)) {+ if ($this->test_anonymous_bind($ldap_url, false)) {$this->info("Anonymous bind successful to $ldap_url with certificate-checks disabled");$ldap_urls[] = [$ldap_url, false, false];- $pretty_ldap_urls[] = [$ldap_url, "DISABLED", "n/a (no)"];+ $pretty_ldap_urls[] = [$ldap_url, 'DISABLED', 'n/a (no)'];+continue;} else {$this->error("WARNING: Failed to bind to $ldap_url with certificate checks disabled. Trying unencrypted with STARTTLS");}// now switching to ldap:// URL's from ldaps://- $ldap_url = "ldap://".$parsed['host'].":$port";+ $ldap_url = 'ldap://'.$parsed['host'].":$port";- if($this->test_anonymous_bind($ldap_url, true, true)) {+ if ($this->test_anonymous_bind($ldap_url, true, true)) {$this->info("Plain connection to $ldap_url with STARTTLS succesful!");- $ldap_urls[] = [ $ldap_url, true, true ];- $pretty_ldap_urls[] = [$ldap_url, "enabled", "STARTTLS ENABLED"];+ $ldap_urls[] = [$ldap_url, true, true];+ $pretty_ldap_urls[] = [$ldap_url, 'enabled', 'STARTTLS ENABLED'];+continue;} else {$this->error("WARNING: Failed to bind to $ldap_url with STARTTLS enabled. Trying without certificate checks.");@@ -339,224 +349,235 @@ class LdapTroubleshooter extends Commandif ($this->test_anonymous_bind($ldap_url, false, true)) {$this->info("Plain connection to $ldap_url with STARTTLS and cert checks *disabled* successful!");$ldap_urls[] = [$ldap_url, false, true];- $pretty_ldap_urls[] = [$ldap_url, "DISABLED", "STARTTLS ENABLED"];+ $pretty_ldap_urls[] = [$ldap_url, 'DISABLED', 'STARTTLS ENABLED'];+continue;} else {$this->error("WARNING: Failed to bind to $ldap_url with STARTTLS enabled, and cert checks disabled. Trying without STARTTLS");}- if($this->test_anonymous_bind($ldap_url)) {+ if ($this->test_anonymous_bind($ldap_url)) {$this->info("Plain connection to $ldap_url succesful!");- $ldap_urls[] = [ $ldap_url, true, false ];- $pretty_ldap_urls[] = [$ldap_url, "n/a", "starttls disabled"];+ $ldap_urls[] = [$ldap_url, true, false];+ $pretty_ldap_urls[] = [$ldap_url, 'n/a', 'starttls disabled'];+continue;} else {$this->error("WARNING: Failed to bind to $ldap_url. Giving up on port $port");}}- $this->debugout(print_r($ldap_urls,true));+ $this->debugout(print_r($ldap_urls, true));- if(count($ldap_urls) > 0 ) {+ if (count($ldap_urls) > 0) {$this->debugout("Found working LDAP URL's: ");- foreach($ldap_urls as $ldap_url) { // TODO maybe do this as a $this->table() instead?- $this->debugout("LDAP URL: " . $ldap_url[0]);- $this->debugout($ldap_url[0] . ($ldap_url[1] ? " certificate checks enabled" : " certificate checks disabled") . ($ldap_url[2] ? " STARTTLS Enabled " : " STARTTLS Disabled"));+ foreach ($ldap_urls as $ldap_url) { // TODO maybe do this as a $this->table() instead?+ $this->debugout('LDAP URL: '.$ldap_url[0]);+ $this->debugout($ldap_url[0].($ldap_url[1] ? ' certificate checks enabled' : ' certificate checks disabled').($ldap_url[2] ? ' STARTTLS Enabled ' : ' STARTTLS Disabled'));}- $this->table(["URL", "Cert Checks?", "STARTTLS?"], $pretty_ldap_urls);+ $this->table(['URL', 'Cert Checks?', 'STARTTLS?'], $pretty_ldap_urls);} else {$this->error("ERROR - no valid LDAP URL's available - ABORTING");exit(1);}- $this->line("STAGE 4: Test Administrative Bind for LDAP Sync");- foreach($ldap_urls AS $ldap_url) {+ $this->line('STAGE 4: Test Administrative Bind for LDAP Sync');+ foreach ($ldap_urls as $ldap_url) {try {$w = Crypt::Decrypt($settings->ldap_pword);- } catch (\Exception $e) {- $this->warn("Could not decrypt password. This usually means an LDAP password was not set or the APP_KEY was changed since the LDAP pasword was last saved. Aborting.");+ } catch (Exception $e) {+ $this->warn('Could not decrypt password. This usually means an LDAP password was not set or the APP_KEY was changed since the LDAP pasword was last saved. Aborting.');exit(0);}$this->test_authed_bind($ldap_url[0], $ldap_url[1], $ldap_url[2], $settings->ldap_uname, $w);}- $this->line("STAGE 5: Test BaseDN");- //grab all LDAP_ constants and fill up a reversed array mapping from weird LDAP dotted-strings to (Constant Name)+ $this->line('STAGE 5: Test BaseDN');+ // grab all LDAP_ constants and fill up a reversed array mapping from weird LDAP dotted-strings to (Constant Name)$all_defined_constants = get_defined_constants();$ldap_constants = [];- foreach($all_defined_constants AS $key => $val) {- if(starts_with($key,"LDAP_") && is_string($val)) {+ foreach ($all_defined_constants as $key => $val) {+ if (starts_with($key, 'LDAP_') && is_string($val)) {$ldap_constants[$val] = $key; // INVERT the meaning here!}}- $this->debugout("LDAP constants are: ".print_r($ldap_constants,true));+ $this->debugout('LDAP constants are: '.print_r($ldap_constants, true));- foreach($ldap_urls AS $ldap_url) {+ foreach ($ldap_urls as $ldap_url) {try {$w = Crypt::Decrypt($settings->ldap_pword);- } catch (\Exception $e) {- $this->warn("Could not decrypt password. This usually means an LDAP password was not set or the APP_KEY was changed since the LDAP pasword was last saved. Aborting.");+ } catch (Exception $e) {+ $this->warn('Could not decrypt password. This usually means an LDAP password was not set or the APP_KEY was changed since the LDAP pasword was last saved. Aborting.');exit(0);}- if($this->test_informational_bind($ldap_url[0],$ldap_url[1],$ldap_url[2],$settings->ldap_uname,$w,$settings)) {- $this->info("Success getting informational bind!");+ if ($this->test_informational_bind($ldap_url[0], $ldap_url[1], $ldap_url[2], $settings->ldap_uname, $w, $settings)) {+ $this->info('Success getting informational bind!');} else {- $this->error("Unable to get information from bind.");+ $this->error('Unable to get information from bind.');}}- $this->line("STAGE 6: Test LDAP Login to Snipe-IT");- foreach($ldap_urls AS $ldap_url) {- $this->line("Starting auth to " . $ldap_url[0]);- while(true) {- $with_tls = $ldap_url[1] ? "with": "without";- $with_startssl = $ldap_url[2] ? "using": "not using";- if(!$this->confirm('Do you wish to try to authenticate to this directory: '.$ldap_url[0]." $with_tls TLS and $with_startssl STARTSSL?")) {+ $this->line('STAGE 6: Test LDAP Login to Snipe-IT');+ foreach ($ldap_urls as $ldap_url) {+ $this->line('Starting auth to '.$ldap_url[0]);+ while (true) {+ $with_tls = $ldap_url[1] ? 'with' : 'without';+ $with_startssl = $ldap_url[2] ? 'using' : 'not using';+ if (! $this->confirm('Do you wish to try to authenticate to this directory: '.$ldap_url[0]." $with_tls TLS and $with_startssl STARTSSL?")) {break;}- $username = $this->ask("Username");- $password = $this->secret("Password");+ $username = $this->ask('Username');+ $password = $this->secret('Password');$results = $this->test_authed_bind($ldap_url[0], $ldap_url[1], $ldap_url[2], $username, $password); // FIXME - should do some other stuff here, maybe with the concatenating or something? maybe? and/or should put up some results?if ($results) {- $this->info("Success authenticating with " . $username);+ $this->info('Success authenticating with '.$username);} else {- $this->error("Unable to authenticate with " . $username);+ $this->error('Unable to authenticate with '.$username);}}}- $this->info("LDAP TROUBLESHOOTING COMPLETE!");+ $this->info('LDAP TROUBLESHOOTING COMPLETE!');}- public function connect_to_ldap($ldap_url, $check_cert, $start_tls)+ public function connect_to_ldap($ldap_url, $check_cert, $start_tls){if ($check_cert) {- $this->line("we *ARE* checking certs");+ $this->line('we *ARE* checking certs');Ldap::ignoreCertificates(false);} else {- $this->line("we are IGNORING certs");+ $this->line('we are IGNORING certs');Ldap::ignoreCertificates(true);}$lconn = ldap_connect($ldap_url);ldap_set_option($lconn, LDAP_OPT_PROTOCOL_VERSION, 3); // should we 'test' different protocol versions here? Does anyone even use anything other than LDAPv3?- // no - it's formally deprecated: https://tools.ietf.org/html/rfc3494- if($this->settings->ldap_client_tls_cert && $this->settings->ldap_client_tls_key) {+ // no - it's formally deprecated: https://tools.ietf.org/html/rfc3494+ if ($this->settings->ldap_client_tls_cert && $this->settings->ldap_client_tls_key) {// client-side TLS certificate support for LDAP (Google Secure LDAP)putenv('LDAPTLS_CERT=storage/ldap_client_tls.cert');putenv('LDAPTLS_KEY=storage/ldap_client_tls.key');}- if($start_tls) {- if(!ldap_start_tls($lconn)) {- $this->error("WARNING: Unable to start TLS");+ if ($start_tls) {+ if (! ldap_start_tls($lconn)) {+ $this->error('WARNING: Unable to start TLS');+return false;}}- if(!$lconn) {- $this->error("WARNING: Failed to generate connection string - using: ".$ldap_url);+ if (! $lconn) {+ $this->error('WARNING: Failed to generate connection string - using: '.$ldap_url);+return false;}$net = ldap_set_option($lconn, LDAP_OPT_NETWORK_TIMEOUT, $this->option('timeout'));$time = ldap_set_option($lconn, LDAP_OPT_TIMELIMIT, $this->option('timeout'));- if(!$net || !$time) {- $this->error("Unable to set timeouts!");+ if (! $net || ! $time) {+ $this->error('Unable to set timeouts!');}+return $lconn;}public function test_anonymous_bind($ldap_url, $check_cert = true, $start_tls = false){- return $this->timed_boolean_execute(function () use ($ldap_url, $check_cert , $start_tls) {+ return $this->timed_boolean_execute(function () use ($ldap_url, $check_cert, $start_tls) {try {$lconn = $this->connect_to_ldap($ldap_url, $check_cert, $start_tls);- $this->line("Attempting to bind now, this can take a while if we mess it up");+ $this->line('Attempting to bind now, this can take a while if we mess it up');$bind_results = ldap_bind($lconn);- $this->line("Bind results are: " . $bind_results . " which translate into boolean: " . (bool)$bind_results);+ $this->line('Bind results are: '.$bind_results.' which translate into boolean: '.(bool) $bind_results);ldap_close($lconn);- return (bool)$bind_results;++ return (bool) $bind_results;} catch (Exception $e) {- $this->error("WARNING: Exception caught during bind - ".$e->getMessage());+ $this->error('WARNING: Exception caught during bind - '.$e->getMessage());+return false;}});}- public function test_authed_bind($ldap_url, $check_cert, $start_tls, $username, $password)+ public function test_authed_bind($ldap_url, $check_cert, $start_tls, $username, $password){return $this->timed_boolean_execute(function () use ($ldap_url, $check_cert, $start_tls, $username, $password) {try {$lconn = $this->connect_to_ldap($ldap_url, $check_cert, $start_tls);$bind_results = ldap_bind($lconn, $username, $password);ldap_close($lconn);- if(!$bind_results) {+ if (! $bind_results) {$this->error("WARNING: Failed to bind to $ldap_url as $username");+return false;} else {$this->info("SUCCESS - Able to bind to $ldap_url as $username");- return (bool)$lconn;++ return (bool) $lconn;}} catch (Exception $e) {$this->error("WARNING: Exception caught during Authed bind to $username - ".$e->getMessage());+return false;}});}- public function test_informational_bind($ldap_url, $check_cert, $start_tls, $username, $password,$settings)+ public function test_informational_bind($ldap_url, $check_cert, $start_tls, $username, $password, $settings){return $this->timed_boolean_execute(function () use ($ldap_url, $check_cert, $start_tls, $username, $password, $settings) {try { // TODO - copypasta'ed from test_authed_bind$conn = $this->connect_to_ldap($ldap_url, $check_cert, $start_tls);$bind_results = ldap_bind($conn, $username, $password);- if(!$bind_results) {+ if (! $bind_results) {$this->error("WARNING: Failed to bind to $ldap_url as $username");+return false;}$this->info("SUCCESS - Able to bind to $ldap_url as $username");$cleaned_results = [];try {// This _may_ only work for Active Directory?- $result = ldap_read($conn, '', '(objectClass=*)'/* , ['supportedControl']*/);+ $result = ldap_read($conn, '', '(objectClass=*)'/* , ['supportedControl'] */);$results = ldap_get_entries($conn, $result);$cleaned_results = $this->ldap_results_cleaner($results);- //$this->line(print_r($cleaned_results,true));+ // $this->line(print_r($cleaned_results,true));$default_naming_contexts = $cleaned_results[0]['namingcontexts'];- $this->info("Default Naming Contexts:");- $this->info(implode(", ", $default_naming_contexts));- //okay, great - now how do we display those results? I have no idea.- } catch (\Exception $e) {+ $this->info('Default Naming Contexts:');+ $this->info(implode(', ', $default_naming_contexts));+ // okay, great - now how do we display those results? I have no idea.+ } catch (Exception $e) {$this->error("Unable to get base naming contexts - here's what we *did* get:");$this->line(print_r($cleaned_results, true));}// I don't see why this throws an Exception for Google LDAP, but I guess we ought to try and catch it?$this->debugout("I guess we're trying to do the ldap search here, but sometimes it takes too long?");- $this->debugout("Base DN is: ".$settings->ldap_basedn." and filter is: ".parenthesized_filter($settings->ldap_filter));+ $this->debugout('Base DN is: '.$settings->ldap_basedn.' and filter is: '.parenthesized_filter($settings->ldap_filter));$search_results = ldap_search($conn, $settings->ldap_basedn, parenthesized_filter($settings->ldap_filter));$entries = ldap_get_entries($conn, $search_results);- $this->info("Printing first 10 results: ");+ $this->info('Printing first 10 results: ');$pretty_data = array_slice($this->ldap_results_cleaner($entries), 0, 10);- //print_r($data);+ // print_r($data);$headers = [];foreach ($pretty_data as $row) {- //populate headers+ // populate headersforeach ($row as $key => $value) {- //skip objectsid and objectguid because it junks up output- if ($key == "objectsid" || $key == "objectguid") {+ // skip objectsid and objectguid because it junks up output+ if ($key == 'objectsid' || $key == 'objectguid') {continue;}- if (!in_array($key, $headers)) {+ if (! in_array($key, $headers)) {$headers[] = $key;}}}$table = [];- //repeat again to populate table+ // repeat again to populate tableforeach ($pretty_data as $row) {$newrow = [];foreach ($headers as $header) {if (is_array(@$row[$header])) {- $newrow[] = "[" . implode(", ", $row[$header]) . "]";+ $newrow[] = '['.implode(', ', $row[$header]).']';} else {$newrow[] = @$row[$header];}@@ -565,8 +586,9 @@ class LdapTroubleshooter extends Command}$this->table($headers, $table);- } catch (\Exception $e) {+ } catch (Exception $e) {$this->error("WARNING: Exception caught during Authed bind to $username - ".$e->getMessage());+return false;} finally {ldap_close($conn);@@ -575,53 +597,54 @@ class LdapTroubleshooter extends Command}/***********************************************- *- * This function executes $function - which is expected to be some kind of executable function -+ *+ * This function executes $function - which is expected to be some kind of executable function -* with a timeout set. It respects the timeout by forking execution and setting a strict timer* for which to get back a SIGUSR1 or SIGUSR2 signal from the forked process.- *+ ************************************************/private function timed_boolean_execute($function){- if(!(function_exists('pcntl_sigtimedwait') && function_exists('posix_getpid') && function_exists('pcntl_fork') && function_exists('posix_kill') && function_exists('pcntl_wifsignaled'))) {+ if (! (function_exists('pcntl_sigtimedwait') && function_exists('posix_getpid') && function_exists('pcntl_fork') && function_exists('posix_kill') && function_exists('pcntl_wifsignaled'))) {// POSIX functions needed for forking aren't present, just run the function inline (ignoring timeout)$this->line('WARNING: Unable to execute POSIX fork() commands, timeout may not be respected');+return $function();} else {$parent_pid = posix_getpid();$pid = pcntl_fork();- switch($pid) {+ switch ($pid) {case 0:- //we're the 'child'- if($function()) {- //SUCCESS = SIGUSR1+ // we're the 'child'+ if ($function()) {+ // SUCCESS = SIGUSR1posix_kill($parent_pid, SIGUSR1);} else {- //FAILURE = SIGUSR2+ // FAILURE = SIGUSR2posix_kill($parent_pid, SIGUSR2);}exit();- break; //yes I know we don't need it.+ break; // yes I know we don't need it.case -1:- //couldn't fork- $this->error("COULD NOT FORK - assuming failure");+ // couldn't fork+ $this->error('COULD NOT FORK - assuming failure');+return false;- break; //I still know that we don't need it+ break; // I still know that we don't need itdefault:- //we remain the 'parent', $pid is the PID of the forked process.+ // we remain the 'parent', $pid is the PID of the forked process.$siginfo = [];- $exit_status = pcntl_sigtimedwait ([SIGUSR1, SIGUSR2], $siginfo, $this->option('timeout'));+ $exit_status = pcntl_sigtimedwait([SIGUSR1, SIGUSR2], $siginfo, $this->option('timeout'));if ($exit_status == SIGUSR1) {return true;} else {- posix_kill($pid, SIGKILL); //make sure we don't have processes hanging around that might try and send signals during later executions, confusing us+ posix_kill($pid, SIGKILL); // make sure we don't have processes hanging around that might try and send signals during later executions, confusing us+return false;}- break; //Yeah I get it already, shush.+ break; // Yeah I get it already, shush.}}}--}diff --git a/app/Console/Commands/MergeUsersByUsername.php b/app/Console/Commands/MergeUsersByUsername.phpindex 0c5e966ab9..8d43ae7b6d 100644--- a/app/Console/Commands/MergeUsersByUsername.php+++ b/app/Console/Commands/MergeUsersByUsername.php@@ -44,19 +44,15 @@ class MergeUsersByUsername extends Command$users = User::where('username', 'LIKE', '%@%')->whereNull('deleted_at')->get();$this->info($users->count().' total non-deleted users whose usernames contain a @ symbol.');-foreach ($users as $user) {$parts = explode('@', trim($user->username));$this->info('Checking against username '.trim($parts[0]).'.');-$bad_users = User::where('username', '=', trim($parts[0]))->whereNull('deleted_at')- ->with('assets', 'manager', 'userlog', 'licenses', 'consumables', 'accessories', 'managedLocations','uploads', 'acceptances')+ ->with('assets', 'manager', 'userlog', 'licenses', 'consumables', 'accessories', 'managedLocations', 'uploads', 'acceptances')->get();--foreach ($bad_users as $bad_user) {$this->info($bad_user->username.' ('.$bad_user->id.') will be merged into '.$user->username.' ('.$user->id.') ');@@ -125,7 +121,6 @@ class MergeUsersByUsername extends Commandevent(new UserMerged($bad_user, $user, null));-}}}diff --git a/app/Console/Commands/MigrateLicenseSeatQuantitiesInActionLogs.php b/app/Console/Commands/MigrateLicenseSeatQuantitiesInActionLogs.phpindex b649f7ee96..f1bdff48ab 100644--- a/app/Console/Commands/MigrateLicenseSeatQuantitiesInActionLogs.php+++ b/app/Console/Commands/MigrateLicenseSeatQuantitiesInActionLogs.php@@ -5,7 +5,6 @@ namespace App\Console\Commands;use App\Enums\ActionType;use Illuminate\Console\Command;use Illuminate\Support\Facades\DB;-use Illuminate\Support\Facades\Log;use Illuminate\Support\Str;class MigrateLicenseSeatQuantitiesInActionLogs extends Command@@ -51,9 +50,9 @@ class MigrateLicenseSeatQuantitiesInActionLogs extends Commandif ($this->option('no-interaction') || $this->confirm('Update quantities in the action log?')) {$query->chunk(50, function ($logs) {$logs->each(function ($log) {- $quantityFromNote = Str::between($log->note, "ed ", " seats");+ $quantityFromNote = Str::between($log->note, 'ed ', ' seats');- if (!is_numeric($quantityFromNote)) {+ if (! is_numeric($quantityFromNote)) {$this->error('Could not parse quantity from ID: {id}', ['id' => $log->id]);}diff --git a/app/Console/Commands/MoveUploadsToNewDisk.php b/app/Console/Commands/MoveUploadsToNewDisk.phpindex 3491d0fd00..29f1f75532 100644--- a/app/Console/Commands/MoveUploadsToNewDisk.php+++ b/app/Console/Commands/MoveUploadsToNewDisk.php@@ -3,8 +3,8 @@namespace App\Console\Commands;use Illuminate\Console\Command;-use Illuminate\Support\Facades\Storage;use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Storage;class MoveUploadsToNewDisk extends Command{@@ -47,30 +47,29 @@ class MoveUploadsToNewDisk extends Command}$delete_local = $this->argument('delete_local');- $public_uploads['accessories'] = glob('public/uploads/accessories'."/*.*");- $public_uploads['assets'] = glob('public/uploads/assets'."/*.*");- $public_uploads['avatars'] = glob('public/uploads/avatars'."/*.*");- $public_uploads['categories'] = glob('public/uploads/categories'."/*.*");- $public_uploads['companies'] = glob('public/uploads/companies'."/*.*");- $public_uploads['components'] = glob('public/uploads/components'."/*.*");- $public_uploads['consumables'] = glob('public/uploads/consumables'."/*.*");- $public_uploads['departments'] = glob('public/uploads/departments'."/*.*");- $public_uploads['locations'] = glob('public/uploads/locations'."/*.*");- $public_uploads['manufacturers'] = glob('public/uploads/manufacturers'."/*.*");- $public_uploads['suppliers'] = glob('public/uploads/suppliers'."/*.*");- $public_uploads['assetmodels'] = glob('public/uploads/models'."/*.*");-+ $public_uploads['accessories'] = glob('public/uploads/accessories'.'/*.*');+ $public_uploads['assets'] = glob('public/uploads/assets'.'/*.*');+ $public_uploads['avatars'] = glob('public/uploads/avatars'.'/*.*');+ $public_uploads['categories'] = glob('public/uploads/categories'.'/*.*');+ $public_uploads['companies'] = glob('public/uploads/companies'.'/*.*');+ $public_uploads['components'] = glob('public/uploads/components'.'/*.*');+ $public_uploads['consumables'] = glob('public/uploads/consumables'.'/*.*');+ $public_uploads['departments'] = glob('public/uploads/departments'.'/*.*');+ $public_uploads['locations'] = glob('public/uploads/locations'.'/*.*');+ $public_uploads['manufacturers'] = glob('public/uploads/manufacturers'.'/*.*');+ $public_uploads['suppliers'] = glob('public/uploads/suppliers'.'/*.*');+ $public_uploads['assetmodels'] = glob('public/uploads/models'.'/*.*');// iterate filesforeach ($public_uploads as $public_type => $public_upload) {$type_count = 0;- $this->info('- There are ' . count($public_upload) . ' PUBLIC ' . $public_type . ' files.');+ $this->info('- There are '.count($public_upload).' PUBLIC '.$public_type.' files.');for ($i = 0; $i < count($public_upload); $i++) {$type_count++;$filename = basename($public_upload[$i]);- try {+ try {Storage::disk('public')->put('uploads/'.$public_type.'/'.$filename, file_get_contents($public_upload[$i]));$new_url = Storage::disk('public')->url('uploads/'.$public_type.'/'.$filename, $filename);$this->info($type_count.'. PUBLIC: '.$filename.' was copied to '.$new_url);@@ -81,49 +80,46 @@ class MoveUploadsToNewDisk extends Command}}- $logos = glob("public/uploads/setting*.*");- $this->info("- There are ".count($logos).' files that might be logos.');+ $logos = glob('public/uploads/setting*.*');+ $this->info('- There are '.count($logos).' files that might be logos.');$type_count = 0;foreach ($logos as $logo) {$this->info($logo);$type_count++;$filename = basename($logo);- Storage::disk('public')->put('uploads/' . $filename, file_get_contents($logo));- $this->info($type_count . '. LOGO: ' . $filename . ' was copied to ' . env('PUBLIC_AWS_URL') . '/uploads/' . $filename);+ Storage::disk('public')->put('uploads/'.$filename, file_get_contents($logo));+ $this->info($type_count.'. LOGO: '.$filename.' was copied to '.env('PUBLIC_AWS_URL').'/uploads/'.$filename);}- $private_uploads['assets'] = glob('storage/private_uploads/assets'."/*.*");- $private_uploads['signatures'] = glob('storage/private_uploads/signatures'."/*.*");- $private_uploads['audits'] = glob('storage/private_uploads/audits'."/*.*");- $private_uploads['assetmodels'] = glob('storage/private_uploads/models'."/*.*");- $private_uploads['imports'] = glob('storage/private_uploads/imports'."/*.*");- $private_uploads['licenses'] = glob('storage/private_uploads/licenses'."/*.*");- $private_uploads['users'] = glob('storage/private_uploads/users'."/*.*");- $private_uploads['backups'] = glob('storage/private_uploads/backups'."/*.*");-+ $private_uploads['assets'] = glob('storage/private_uploads/assets'.'/*.*');+ $private_uploads['signatures'] = glob('storage/private_uploads/signatures'.'/*.*');+ $private_uploads['audits'] = glob('storage/private_uploads/audits'.'/*.*');+ $private_uploads['assetmodels'] = glob('storage/private_uploads/models'.'/*.*');+ $private_uploads['imports'] = glob('storage/private_uploads/imports'.'/*.*');+ $private_uploads['licenses'] = glob('storage/private_uploads/licenses'.'/*.*');+ $private_uploads['users'] = glob('storage/private_uploads/users'.'/*.*');+ $private_uploads['backups'] = glob('storage/private_uploads/backups'.'/*.*');foreach ($private_uploads as $private_type => $private_upload) {- {- $this->info('- There are ' . count($private_upload) . ' PRIVATE ' . $private_type . ' files.');-- $type_count = 0;- for ($x = 0; $x < count($private_upload); $x++) {- $type_count++;- $filename = basename($private_upload[$x]);-- try {- Storage::put($private_type . '/' . $filename, file_get_contents($private_upload[$x]));- $new_url = Storage::url($private_type . '/' . $filename, $filename);- $this->info($type_count . '. PRIVATE: ' . $filename . ' was copied to ' . $new_url);- } catch (\Exception $e) {- Log::debug($e);- $this->error($e);- }++ $this->info('- There are '.count($private_upload).' PRIVATE '.$private_type.' files.');++ $type_count = 0;+ for ($x = 0; $x < count($private_upload); $x++) {+ $type_count++;+ $filename = basename($private_upload[$x]);++ try {+ Storage::put($private_type.'/'.$filename, file_get_contents($private_upload[$x]));+ $new_url = Storage::url($private_type.'/'.$filename, $filename);+ $this->info($type_count.'. PRIVATE: '.$filename.' was copied to '.$new_url);+ } catch (\Exception $e) {+ Log::debug($e);+ $this->error($e);}}-if ($delete_local == 'true') {$public_delete_count = 0;$private_delete_count = 0;@@ -160,7 +156,7 @@ class MoveUploadsToNewDisk extends Command}}- $this->info($public_delete_count . ' PUBLIC local files and ' . $private_delete_count . ' PRIVATE local files were deleted from your filesystem.');+ $this->info($public_delete_count.' PUBLIC local files and '.$private_delete_count.' PRIVATE local files were deleted from your filesystem.');}}}diff --git a/app/Console/Commands/NormalizeUserNames.php b/app/Console/Commands/NormalizeUserNames.phpindex c3ea5e8ace..ee5bc68368 100644--- a/app/Console/Commands/NormalizeUserNames.php+++ b/app/Console/Commands/NormalizeUserNames.php@@ -2,8 +2,8 @@namespace App\Console\Commands;-use Illuminate\Console\Command;use App\Models\User;+use Illuminate\Console\Command;class NormalizeUserNames extends Command{@@ -40,13 +40,13 @@ class NormalizeUserNames extends Command{$users = User::get();- $this->info($users->count() . ' users');+ $this->info($users->count().' users');- foreach ($users as $user) {- $user->first_name = ucwords(strtolower($user->first_name));- $user->last_name = ucwords(strtolower($user->last_name));- $user->email = strtolower($user->email);- $user->save();+ foreach ($users as $user) {+ $user->first_name = ucwords(strtolower($user->first_name));+ $user->last_name = ucwords(strtolower($user->last_name));+ $user->email = strtolower($user->email);+ $user->save();}}}diff --git a/app/Console/Commands/ObjectImportCommand.php b/app/Console/Commands/ObjectImportCommand.phpindex 97e9060f34..1319e6dbf4 100644--- a/app/Console/Commands/ObjectImportCommand.php+++ b/app/Console/Commands/ObjectImportCommand.php@@ -3,11 +3,10 @@namespace App\Console\Commands;use Illuminate\Console\Command;-use Symfony\Component\Console\Input\InputArgument;-use Symfony\Component\Console\Input\InputOption;use Illuminate\Support\Facades\Log;use Symfony\Component\Console\Helper\ProgressIndicator;-+use Symfony\Component\Console\Input\InputArgument;+use Symfony\Component\Console\Input\InputOption;/*** Class ObjectImportCommand@@ -55,7 +54,7 @@ class ObjectImportCommand extends Command*/public function handle(){- ini_set('max_execution_time', env('IMPORT_TIME_LIMIT', 600)); //600 seconds = 10 minutes+ ini_set('max_execution_time', env('IMPORT_TIME_LIMIT', 600)); // 600 seconds = 10 minutesini_set('memory_limit', env('IMPORT_MEMORY_LIMIT', '500M'));$this->progressIndicator = new ProgressIndicator($this->output);@@ -65,15 +64,15 @@ class ObjectImportCommand extends Command$classString = "App\\Importer\\{$class}Importer";$importer = new $classString($filename);$importer->setCallbacks([$this, 'log'], [$this, 'progress'], [$this, 'errorCallback'])- ->setCreatedBy($this->option('user_id'))- ->setUpdating($this->option('update'))- ->setShouldNotify($this->option('send-welcome'))- ->setUsernameFormat($this->option('username_format'));+ ->setCreatedBy($this->option('user_id'))+ ->setUpdating($this->option('update'))+ ->setShouldNotify($this->option('send-welcome'))+ ->setUsernameFormat($this->option('username_format'));$this->logger = Log::build(['driver' => 'single','path' => $this->option('logfile'),- ]);+ ]);$this->progressIndicator->start('======= Importing Items from '.$filename.' =========');@@ -99,9 +98,11 @@ class ObjectImportCommand extends Command* If a warning message is passed, we'll spit it to the console as well.** @author Daniel Melzter+ ** @since 3.0- * @param string $string- * @param string $level+ *+ * @param string $string+ * @param string $level*/public function log($string, $level = 'info'){@@ -120,7 +121,9 @@ class ObjectImportCommand extends Command* Get the console command arguments.** @author Daniel Melzter+ ** @since 3.0+ ** @return array*/protected function getArguments()@@ -134,20 +137,22 @@ class ObjectImportCommand extends Command* Get the console command options.** @author Daniel Melzter+ ** @since 3.0+ ** @return array*/protected function getOptions(){return [- ['email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null],- ['username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null],- ['logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log')],- ['item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Accessory, License, or User', 'Asset'],- ['web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'],- ['user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1],- ['update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'],- ['send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'],+ ['email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null],+ ['username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null],+ ['logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log')],+ ['item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Accessory, License, or User', 'Asset'],+ ['web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'],+ ['user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1],+ ['update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'],+ ['send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'],];}}diff --git a/app/Console/Commands/PaveIt.php b/app/Console/Commands/PaveIt.phpindex 8c6bc89a51..1223cecff0 100644--- a/app/Console/Commands/PaveIt.php+++ b/app/Console/Commands/PaveIt.php@@ -2,11 +2,10 @@namespace App\Console\Commands;-use App\Models\Asset;use App\Models\CustomField;-use Illuminate\Support\Facades\Schema;-use Illuminate\Support\Facades\DB;use Illuminate\Console\Command;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Schema;class PaveIt extends Command{@@ -42,9 +41,9 @@ class PaveIt extends Commandpublic function handle(){- if (!$this->option('force')) {+ if (! $this->option('force')) {$confirmation = $this->confirm("\n****************************************************\nTHIS WILL DELETE ALL OF THE DATA IN YOUR DATABASE. \nThere is NO undo. This WILL destroy ALL of your data, \nINCLUDING ANY non-Snipe-IT tables you have in this database. \n****************************************************\n\nDo you wish to continue? No backsies! ");- if (!$confirmation) {+ if (! $confirmation) {$this->error('ABORTING');exit(-1);}@@ -79,16 +78,16 @@ class PaveIt extends Commandforeach ($tables as $table_obj) {$table = $table_obj['name'];if (in_array($table, $except_tables)) {- $this->info($table. ' is SKIPPED.');+ $this->info($table.' is SKIPPED.');} else {\DB::statement('truncate '.$table);- $this->info($table. ' is TRUNCATED.');+ $this->info($table.' is TRUNCATED.');}}// Leave in the demo oauth keys so we don't have to reset them every day in the demosDB::statement('delete from oauth_clients WHERE id > 2');DB::statement('delete from oauth_access_tokens WHERE user_id > 2');-+}-}\ No newline at end of file+}diff --git a/app/Console/Commands/Purge.php b/app/Console/Commands/Purge.phpindex 4db7bac147..9fe9f39228 100644--- a/app/Console/Commands/Purge.php+++ b/app/Console/Commands/Purge.php@@ -149,13 +149,13 @@ class Purge extends Command$filenames = Actionlog::where('action_type', 'uploaded')->where('item_id', $user->id)->pluck('filename');- foreach($filenames as $filename) {+ foreach ($filenames as $filename) {try {- if (Storage::exists($rel_path . '/' . $filename)) {- Storage::delete($rel_path . '/' . $filename);+ if (Storage::exists($rel_path.'/'.$filename)) {+ Storage::delete($rel_path.'/'.$filename);}} catch (\Exception $e) {- Log::info('An error occurred while deleting files: ' . $e->getMessage());+ Log::info('An error occurred while deleting files: '.$e->getMessage());}}$this->info('- User "'.$user->username.'" deleted.');diff --git a/app/Console/Commands/PurgeEulaPDFs.php b/app/Console/Commands/PurgeEulaPDFs.phpindex a06b27d182..ab2edad79a 100644--- a/app/Console/Commands/PurgeEulaPDFs.php+++ b/app/Console/Commands/PurgeEulaPDFs.php@@ -35,7 +35,7 @@ class PurgeEulaPDFs extends Command$before = $this->option('older-than-days');- if (($before=='') || (!is_numeric($before))) {+ if (($before == '') || (! is_numeric($before))) {return $this->error('ERROR: You must pass a valid number for --older-than-days (example: snipeit:purge-eula-pdfs --older-than-days=365.)');}@@ -43,35 +43,32 @@ class PurgeEulaPDFs extends Command$signature_path = 'private_uploads/signatures/';$eula_path = 'private_uploads/eula-pdfs/';- if (!Storage::exists($eula_path)) {+ if (! Storage::exists($eula_path)) {$this->fail('The storage directory "'.$eula_path.'" does not exist. No EULA files will be deleted.');}- if (!Storage::exists($signature_path)) {+ if (! Storage::exists($signature_path)) {$this->fail('The storage directory "'.$signature_path.'" does not exist. No signature files will be deleted.');}-if ($this->option('dryrun')) {$this->info('This script is being run with the --dryrun option. No files or records will be deleted.');}- $acceptances = CheckoutAcceptance::HasFiles()->where('updated_at','<', $interval_date)->with('assignedTo')->get();+ $acceptances = CheckoutAcceptance::HasFiles()->where('updated_at', '<', $interval_date)->with('assignedTo')->get();- if (!$this->option('force')) {+ if (! $this->option('force')) {if ($this->confirm("\n****************************************************\nTHIS WILL DELETE ALL OF THE SIGNATURES AND EULA PDF FILES SINCE $interval_date. \nThere is NO undo! \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) {}}--if ($acceptances->count() == 0) {return $this->warn('There are no item acceptances with signatures or EULA PDFs from before '.$interval_date);}- $this->info(number_format($acceptances->count()) . ' EULA PDFs from before '.$interval_date.' will be purged');+ $this->info(number_format($acceptances->count()).' EULA PDFs from before '.$interval_date.' will be purged');- if (!$this->option('with-output')) {+ if (! $this->option('with-output')) {$this->info('Run this command with the --with-output option to see the full list in the console.');} else {$this->table(@@ -86,7 +83,7 @@ class PurgeEulaPDFs extends Commandtrans('general.filename'),],- $acceptances->map(fn($acceptance) => [+ $acceptances->map(fn ($acceptance) => [trans('general.user') => $acceptance->assignedTo->display_name,trans('general.type') => $acceptance->display_checkoutable_type,trans('general.item') => $acceptance->checkoutable_type::find($acceptance->checkoutable_id)->display_name,@@ -99,31 +96,28 @@ class PurgeEulaPDFs extends Command);}--foreach ($acceptances as $acceptance) {$signature_file = $signature_path.$acceptance->signature_filename;$eula_file = $eula_path.$acceptance->stored_eula_file;if (Storage::exists($signature_file)) {- if (!$this->option('dryrun')) {+ if (! $this->option('dryrun')) {Storage::delete($signature_file);}} else {- $this->error('The file "'. $signature_file.'" does not exist.');+ $this->error('The file "'.$signature_file.'" does not exist.');}-if (Storage::exists($eula_file)) {- if (!$this->option('dryrun')) {+ if (! $this->option('dryrun')) {Storage::delete($eula_file);}} else {$this->error('The file "'.$eula_file.'" does not exist.');}- if (!$this->option('dryrun')) {+ if (! $this->option('dryrun')) {$acceptance->delete();}}diff --git a/app/Console/Commands/ReEncodeCustomFieldNames.php b/app/Console/Commands/ReEncodeCustomFieldNames.phpindex 4e2752b319..24a646ce8d 100644--- a/app/Console/Commands/ReEncodeCustomFieldNames.php+++ b/app/Console/Commands/ReEncodeCustomFieldNames.php@@ -82,10 +82,10 @@ class ReEncodeCustomFieldNames extends Commandif ($field->db_column == $field->convertUnicodeDbSlug() && \Schema::hasColumn('assets', $field->convertUnicodeDbSlug())) {$this->info('-- ✓ This field exists on the assets table and the value for db_column matches in the custom_fields table.');- /**- * There is a mismatch between the fieldname on the assets table and- * what $field->convertUnicodeDbSlug() is *now* expecting.- */+ /**+ * There is a mismatch between the fieldname on the assets table and+ * what $field->convertUnicodeDbSlug() is *now* expecting.+ */} else {if ($field->db_column != $field->convertUnicodeDbSlug()) {@@ -96,7 +96,6 @@ class ReEncodeCustomFieldNames extends Command}-/** Make sure the custom_field_columns array has the ID */if (array_key_exists($field->id, $custom_field_columns)) {@@ -114,7 +113,6 @@ class ReEncodeCustomFieldNames extends Command$field->db_column = $field->convertUnicodeDbSlug();$field->save();-} else {$this->warn('-- ✘ WARNING: There is no field on the assets table ending in '.$field->id.'. This may require more in-depth investigation and may mean the schema was altered manually.');}diff --git a/app/Console/Commands/RegenerateAssetTags.php b/app/Console/Commands/RegenerateAssetTags.phpindex a49d3d0774..f6842a122e 100644--- a/app/Console/Commands/RegenerateAssetTags.php+++ b/app/Console/Commands/RegenerateAssetTags.php@@ -4,8 +4,8 @@ namespace App\Console\Commands;use App\Models\Asset;use App\Models\Setting;-use Illuminate\Support\Facades\Artisan;use Illuminate\Console\Command;+use Illuminate\Support\Facades\Artisan;class RegenerateAssetTags extends Command{diff --git a/app/Console/Commands/RemoveExplicitEols.php b/app/Console/Commands/RemoveExplicitEols.phpindex f5164c2ee0..4ca5c5d0d2 100644--- a/app/Console/Commands/RemoveExplicitEols.php+++ b/app/Console/Commands/RemoveExplicitEols.php@@ -44,7 +44,7 @@ class RemoveExplicitEols extends Command}$endTime = microtime(true);$executionTime = ($endTime - $startTime);- $this->info('Command executed in ' . round($executionTime, 2) . ' seconds.');+ $this->info('Command executed in '.round($executionTime, 2).' seconds.');}private function updateAssets($assets)@@ -55,6 +55,6 @@ class RemoveExplicitEols extends Command$asset->save();}- $this->info($assets->count() . ' Assets updated successfully');+ $this->info($assets->count().' Assets updated successfully');}}diff --git a/app/Console/Commands/RemoveInvalidUploadDeleteActionLogItems.php b/app/Console/Commands/RemoveInvalidUploadDeleteActionLogItems.phpindex cbcc0e4307..524380ea3b 100644--- a/app/Console/Commands/RemoveInvalidUploadDeleteActionLogItems.php+++ b/app/Console/Commands/RemoveInvalidUploadDeleteActionLogItems.php@@ -38,7 +38,7 @@ class RemoveInvalidUploadDeleteActionLogItems extends Commandreturn 0;}- $this->table(['ID', 'Action Type', 'Item Type', 'Item ID', 'Created At', 'Deleted At'], $invalidLogs->map(fn($log) => [+ $this->table(['ID', 'Action Type', 'Item Type', 'Item ID', 'Created At', 'Deleted At'], $invalidLogs->map(fn ($log) => [$log->id,$log->action_type,$log->item_type,@@ -48,7 +48,7 @@ class RemoveInvalidUploadDeleteActionLogItems extends Command])->toArray());if ($this->confirm("Do you wish to remove {$invalidLogs->count()} log items?")) {- $invalidLogs->each(fn($log) => $log->forceDelete());+ $invalidLogs->each(fn ($log) => $log->forceDelete());}return 0;diff --git a/app/Console/Commands/ResetDemoSettings.php b/app/Console/Commands/ResetDemoSettings.phpindex c069460400..d9b506b308 100644--- a/app/Console/Commands/ResetDemoSettings.php+++ b/app/Console/Commands/ResetDemoSettings.php@@ -2,7 +2,6 @@namespace App\Console\Commands;-use App\Models\Setting;use App\Models\User;use Illuminate\Console\Command;@@ -77,7 +76,6 @@ class ResetDemoSettings extends Command$settings->saml_custom_settings = null;$settings->default_avatar = 'default.png';-$settings->save();if ($user = User::where('username', '=', 'admin')->first()) {@@ -91,5 +89,4 @@ class ResetDemoSettings extends Command\Storage::disk('public')->put('snipe-logo-lg.png', file_get_contents(public_path('img/demo/snipe-logo-lg.png')));}-}diff --git a/app/Console/Commands/RestoreDeletedUsers.php b/app/Console/Commands/RestoreDeletedUsers.phpindex 9d5582a618..5cd90f8379 100644--- a/app/Console/Commands/RestoreDeletedUsers.php+++ b/app/Console/Commands/RestoreDeletedUsers.php@@ -6,9 +6,9 @@ use App\Models\Actionlog;use App\Models\Asset;use App\Models\License;use App\Models\User;+use Illuminate\Console\Command;use Illuminate\Support\Facades\Artisan;use Illuminate\Support\Facades\DB;-use Illuminate\Console\Command;class RestoreDeletedUsers extends Command{@@ -75,7 +75,7 @@ class RestoreDeletedUsers extends CommandDB::table('assets')->where('id', $user_log->item_id)- ->update(['assigned_to' => $user->id, 'assigned_type'=> User::class]);+ ->update(['assigned_to' => $user->id, 'assigned_type' => User::class]);$this->info(' ** Asset '.$user_log->item->id.' ('.$user_log->item->asset_tag.') restored to user '.$user->id.'');} elseif ($user_log->item_type == License::class) {diff --git a/app/Console/Commands/RestoreFromBackup.php b/app/Console/Commands/RestoreFromBackup.phpindex e6a1cafc67..dfef7a97f6 100644--- a/app/Console/Commands/RestoreFromBackup.php+++ b/app/Console/Commands/RestoreFromBackup.php@@ -2,14 +2,17 @@namespace App\Console\Commands;+use enshrined\svgSanitize\Sanitizer;use Illuminate\Console\Command;-use ZipArchive;use Illuminate\Support\Facades\Log;-use enshrined\svgSanitize\Sanitizer;+use ZipArchive;-class SQLStreamer {+class SQLStreamer+{private $input;+private $output;+// embed the prefix here?public ?string $prefix;@@ -18,106 +21,112 @@ class SQLStreamer {public static $buffer_size = 1024 * 1024; // use a 1MB buffer, ought to work fine for most cases?public array $tablenames = [];+private bool $should_guess = false;+private bool $statement_is_permitted = false;- public function __construct($input, $output, string $prefix = null)+ public function __construct($input, $output, ?string $prefix = null){$this->input = $input;$this->output = $output;$this->prefix = $prefix;}- public function parse_sql(string $line): string {+ public function parse_sql(string $line): string+ {// take into account the 'start of line or not' setting as an instance variable?// 'continuation' lines for a permitted statement are PERMITTED.// remove *only* line-feeds & carriage-returns; helpful for regexes against lines from// Windows dumps$line = trim($line, "\r\n");- if($this->statement_is_permitted && $line[0] === ' ') {- return $line . "\n"; //re-add the newline+ if ($this->statement_is_permitted && $line[0] === ' ') {+ return $line."\n"; // re-add the newline}$table_regex = '`?([a-zA-Z0-9_]+)`?';$allowed_statements = ["/^(DROP TABLE (?:IF EXISTS )?)`$table_regex(.*)$/" => false,- "/^(CREATE TABLE )$table_regex(.*)$/" => true, //sets up 'continuation'+ "/^(CREATE TABLE )$table_regex(.*)$/" => true, // sets up 'continuation'"/^(LOCK TABLES )$table_regex(.*)$/" => false,"/^(INSERT INTO )$table_regex(.*)$/" => false,- "/^UNLOCK TABLES/" => false,+ '/^UNLOCK TABLES/' => false,// "/^\\) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;/" => false, // FIXME not sure what to do here?- "/^\\)[a-zA-Z0-9_= ]*;$/" => false,+ '/^\\)[a-zA-Z0-9_= ]*;$/' => false,// ^^^^^^ that bit should *exit* the 'permitted' block- "/^\\(.*\\)[,;]$/" => false, //older MySQL dump style with one set of values per line+ '/^\\(.*\\)[,;]$/' => false, // older MySQL dump style with one set of values per line/* we *could* have made the ^INSERT INTO blah VALUES$ turn on the capturing state, and closed it witha ^(blahblah);$ but it's cleaner to not have to manage the state machine. We're just going toassume that (blahblah), or (blahblah); are values for INSERT and are always acceptable. */- "<^/\*![0-9]{5} SET NAMES '?[a-zA-Z0-9_-]+'? \*/;$>" => false, //using weird delimiters (<,>) for readability. allow quoted or unquoted charsets- "<^/\*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' \*/;$>" => false, //same, now handle zero-values+ "<^/\*![0-9]{5} SET NAMES '?[a-zA-Z0-9_-]+'? \*/;$>" => false, // using weird delimiters (<,>) for readability. allow quoted or unquoted charsets+ "<^/\*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' \*/;$>" => false, // same, now handle zero-values];- foreach($allowed_statements as $statement => $statechange) {-// $this->info("Checking regex: $statement...\n");+ foreach ($allowed_statements as $statement => $statechange) {+ // $this->info("Checking regex: $statement...\n");$matches = [];- if (preg_match($statement,$line,$matches)) {+ if (preg_match($statement, $line, $matches)) {$this->statement_is_permitted = $statechange;// matches are: 1 => first part of the statement, 2 => tablename, 3 => rest of statement// (with of course 0 being "the whole match")if (@$matches[2]) {-// print "Found a tablename! It's: ".$matches[2]."\n";+ // print "Found a tablename! It's: ".$matches[2]."\n";if ($this->should_guess) {@$this->tablenames[$matches[2]] += 1;- continue; //oh? FIXME++ continue; // oh? FIXME} else {- $cleaned_tablename = \DB::getTablePrefix().preg_replace('/^'.$this->prefix.'/','',$matches[2]);- $line = preg_replace($statement,'$1`'.$cleaned_tablename.'`$3' , $line);+ $cleaned_tablename = \DB::getTablePrefix().preg_replace('/^'.$this->prefix.'/', '', $matches[2]);+ $line = preg_replace($statement, '$1`'.$cleaned_tablename.'`$3', $line);}} else {// no explicit tablename in this one, leave the line alone}- //how do we *replace* the tablename?-// print "RETURNING LINE: $line";- return $line . "\n"; //re-add newline++ // how do we *replace* the tablename?+ // print "RETURNING LINE: $line";+ return $line."\n"; // re-add newline}}+// all that is not allowed is denied.- return "";+ return '';}- //this is used in exactly *TWO* places, and in both cases should return a prefix I think?+ // this is used in exactly *TWO* places, and in both cases should return a prefix I think?// first - if you do the --sanitize-only one (which is mostly for testing/development)// next - when you run *without* a guessed prefix, this is run first to figure out the prefix// I think we have to *duplicate* the call to be able to run it again?- public static function guess_prefix($input):string+ public static function guess_prefix($input): string{$parser = new self($input, null);$parser->should_guess = true;$parser->line_aware_piping(); // <----- THIS is doing the heavy lifting!- $check_tables = ['settings' => null, 'migrations' => null /* 'assets' => null */]; //TODO - move to statics?- //can't use 'users' because the 'accessories_checkout' table?+ $check_tables = ['settings' => null, 'migrations' => null /* 'assets' => null */]; // TODO - move to statics?+ // can't use 'users' because the 'accessories_checkout' table?// can't use 'assets' because 'ver1_components_assets'- foreach($check_tables as $check_table => $_ignore) {+ foreach ($check_tables as $check_table => $_ignore) {foreach ($parser->tablenames as $tablename => $_count) {-// print "Comparing $tablename to $check_table\n";- if (str_ends_with($tablename,$check_table)) {-// print "Found one!\n";- $check_tables[$check_table] = substr($tablename,0,-strlen($check_table));+ // print "Comparing $tablename to $check_table\n";+ if (str_ends_with($tablename, $check_table)) {+ // print "Found one!\n";+ $check_tables[$check_table] = substr($tablename, 0, -strlen($check_table));}}}$guessed_prefix = null;foreach ($check_tables as $clean_table => $prefix_guess) {- if(is_null($prefix_guess)) {- print("Couldn't find table $clean_table\n");- die();+ if (is_null($prefix_guess)) {+ echo "Couldn't find table $clean_table\n";+ exit();}- if(is_null($guessed_prefix)) {+ if (is_null($guessed_prefix)) {$guessed_prefix = $prefix_guess;} else {if ($guessed_prefix != $prefix_guess) {- print("Prefix mismatch! Had guessed $guessed_prefix but got $prefix_guess\n");- die();+ echo "Prefix mismatch! Had guessed $guessed_prefix but got $prefix_guess\n";+ exit();}}}@@ -130,7 +139,7 @@ class SQLStreamer {{$bytes_read = 0;if (! $this->input) {- throw new \Exception("No Input available for line_aware_piping");+ throw new \Exception('No Input available for line_aware_piping');}while (($buffer = fgets($this->input, SQLStreamer::$buffer_size)) !== false) {@@ -142,25 +151,24 @@ class SQLStreamer {$bytes_written = fwrite($this->output, $cleaned_buffer);if ($bytes_written === false) {- throw new \Exception("Unable to write to pipe");+ throw new \Exception('Unable to write to pipe');}}}// if we got a newline at the end of this, then the _next_ read is the beginning of a line- if($buffer[strlen($buffer)-1] === "\n") {+ if ($buffer[strlen($buffer) - 1] === "\n") {$this->reading_beginning_of_line = true;} else {$this->reading_beginning_of_line = false;}}+return $bytes_read;}}--class RestoreFromBackup extends Command{/**@@ -202,7 +210,7 @@ class RestoreFromBackup extends Commandpublic function handle(){$dir = getcwd();- if( $dir != base_path() ) { // usually only the case when running via webserver, not via command-line+ if ($dir != base_path()) { // usually only the case when running via webserver, not via command-lineLog::debug("Current working directory is: $dir, changing directory to: ".base_path());chdir(base_path()); // TODO - is this *safe* to change on a running script?!}@@ -221,7 +229,7 @@ class RestoreFromBackup extends Commandreturn $this->error('DB_CONNECTION must be MySQL in order to perform a restore. Detected: '.config('database.default'));}- $za = new ZipArchive();+ $za = new ZipArchive;$errcode = $za->open($filename/* , ZipArchive::RDONLY */); // that constant only exists in PHP 7.4 and higherif ($errcode !== true) {@@ -240,13 +248,12 @@ class RestoreFromBackup extends Commandreturn $this->error('Could not access file: '.$filename.' - '.array_key_exists($errcode, $errors) ? $errors[$errcode] : " Unknown reason: $errcode");}-$private_dirs = ['storage/private_uploads/accessories',- 'storage/private_uploads/assetmodels' => 'storage/private_uploads/models', //this was changed from assetmodels => models Aug 10 2025- 'storage/private_uploads/asset_maintenances' => 'storage/private_uploads/maintenances', //this was changed from asset_maintenances => maintenances Aug 10 2025- 'storage/private_uploads/maintenances', //but let 'maintenances' take precedence- 'storage/private_uploads/models', //and let 'models' take precedence+ 'storage/private_uploads/assetmodels' => 'storage/private_uploads/models', // this was changed from assetmodels => models Aug 10 2025+ 'storage/private_uploads/asset_maintenances' => 'storage/private_uploads/maintenances', // this was changed from asset_maintenances => maintenances Aug 10 2025+ 'storage/private_uploads/maintenances', // but let 'maintenances' take precedence+ 'storage/private_uploads/models', // and let 'models' take precedence'storage/private_uploads/assets', // these are asset _files_, not the pictures.'storage/private_uploads/audits','storage/private_uploads/components',@@ -297,10 +304,10 @@ class RestoreFromBackup extends Command$good_extensions = config('filesystems.allowed_upload_extensions_array');- $private_extensions = array_merge($good_extensions, ["csv", "key"]); //add csv, and 'key'- $public_extensions = array_diff($good_extensions, ["xml"]); //remove xml+ $private_extensions = array_merge($good_extensions, ['csv', 'key']); // add csv, and 'key'+ $public_extensions = array_diff($good_extensions, ['xml']); // remove xml- $sanitizer = new Sanitizer();+ $sanitizer = new Sanitizer;/*** TODO: I _hate_ the "continue 3" thing we keep doing here@@ -315,29 +322,30 @@ class RestoreFromBackup extends Command// print_r($stat_results);$raw_path = $stat_results['name'];- if (strpos($raw_path, '\\') !== false) { //found a backslash, swap it to forward-slash+ if (strpos($raw_path, '\\') !== false) { // found a backslash, swap it to forward-slash$raw_path = strtr($raw_path, '\\', '/');- //print "Translating file: ".$stat_results['name']." to: ".$raw_path."\n";+ // print "Translating file: ".$stat_results['name']." to: ".$raw_path."\n";}// skip macOS resource fork files (?!?!?!)if (strpos($raw_path, '__MACOSX') !== false && strpos($raw_path, '._') !== false) {- //print "SKIPPING macOS Resource fork file: $raw_path\n";+ // print "SKIPPING macOS Resource fork file: $raw_path\n";// $boring_files[] = $raw_path; //stop adding this to the boring files list; it's just confusingcontinue;}if (@pathinfo($raw_path, PATHINFO_EXTENSION) == 'sql') {- Log::debug("Found a sql file!");+ Log::debug('Found a sql file!');$sqlfiles[] = $raw_path;$sqlfile_indices[] = $i;+continue;}if ($raw_path[-1] == '/') {- //last character is '/' - this is a directory, and we don't need it, and we don't need to warn about it+ // last character is '/' - this is a directory, and we don't need it, and we don't need to warn about itcontinue;}- if (in_array(basename($raw_path), [".gitkeep", ".gitignore", ".DS_Store"])) {- //skip these boring files silently without reporting on them; they're stupid+ if (in_array(basename($raw_path), ['.gitkeep', '.gitignore', '.DS_Store'])) {+ // skip these boring files silently without reporting on them; they're stupidcontinue;}$extension = strtolower(pathinfo($raw_path, PATHINFO_EXTENSION));@@ -351,20 +359,21 @@ class RestoreFromBackup extends Commandif (is_int($dir)) {$dir = $destdir;}- $last_pos = strrpos($raw_path, $dir . '/');+ $last_pos = strrpos($raw_path, $dir.'/');if ($last_pos !== false) {- //print("INTERESTING - last_pos is $last_pos when searching $raw_path for $dir - last_pos+strlen(\$dir) is: ".($last_pos+strlen($dir))." and strlen(\$rawpath) is: ".strlen($raw_path)."\n");- //print("We would copy $raw_path to $dir.\n"); //FIXME append to a path?- //the CSV bit, below, is because we store CSV files as "blahcsv" - without an extension- if (!in_array($extension, $allowed_extensions) && !($dir == "storage/private_uploads/imports" && substr($raw_path, -3) == "csv" && $extension == "")) {+ // print("INTERESTING - last_pos is $last_pos when searching $raw_path for $dir - last_pos+strlen(\$dir) is: ".($last_pos+strlen($dir))." and strlen(\$rawpath) is: ".strlen($raw_path)."\n");+ // print("We would copy $raw_path to $dir.\n"); //FIXME append to a path?+ // the CSV bit, below, is because we store CSV files as "blahcsv" - without an extension+ if (! in_array($extension, $allowed_extensions) && ! ($dir == 'storage/private_uploads/imports' && substr($raw_path, -3) == 'csv' && $extension == '')) {$unsafe_files[] = $raw_path;- Log::debug($raw_path . ' from directory ' . $dir . ' is being skipped');+ Log::debug($raw_path.' from directory '.$dir.' is being skipped');} else {if ($dir != $destdir) {Log::debug("Getting ready to save file $raw_path to new directory $destdir");}$interesting_files[$raw_path] = ['dest' => $destdir, 'index' => $i];}+continue 3;}}@@ -378,28 +387,30 @@ class RestoreFromBackup extends Commandforeach ($files as $file) {$has_wildcard = (strpos($file, '*') !== false);if ($has_wildcard) {- $file = substr($file, 0, -1); //trim last character (which should be the wildcard)+ $file = substr($file, 0, -1); // trim last character (which should be the wildcard)}$last_pos = strrpos($raw_path, $file); // no trailing slash!if ($last_pos !== false) {- if (!in_array($extension, $allowed_extensions)) {+ if (! in_array($extension, $allowed_extensions)) {// gathering potentially unsafe files here to return at exit$unsafe_files[] = $raw_path;- Log::debug('Potentially unsafe file ' . $raw_path . ' is being skipped');+ Log::debug('Potentially unsafe file '.$raw_path.' is being skipped');$boring_files[] = $raw_path;+continue 3;}- //print("INTERESTING - last_pos is $last_pos when searching $raw_path for $file - last_pos+strlen(\$file) is: ".($last_pos+strlen($file))." and strlen(\$rawpath) is: ".strlen($raw_path)."\n");- //no wildcards found in $file, process 'normally'- if ($last_pos + strlen($file) == strlen($raw_path) || $has_wildcard) { //again, no trailing slash. or this is a wildcard and we just take it.+ // print("INTERESTING - last_pos is $last_pos when searching $raw_path for $file - last_pos+strlen(\$file) is: ".($last_pos+strlen($file))." and strlen(\$rawpath) is: ".strlen($raw_path)."\n");+ // no wildcards found in $file, process 'normally'+ if ($last_pos + strlen($file) == strlen($raw_path) || $has_wildcard) { // again, no trailing slash. or this is a wildcard and we just take it.// print("FOUND THE EXACT FILE: $file AT: $raw_path!!!\n"); //we *do* care about this, though.$interesting_files[$raw_path] = ['dest' => dirname($file), 'index' => $i];+continue 3;}}}}- $boring_files[] = $raw_path; //if we've gotten to here and haven't continue'ed our way into the next iteration, we don't want this file+ $boring_files[] = $raw_path; // if we've gotten to here and haven't continue'ed our way into the next iteration, we don't want this file} // end of pre-processing the ZIP file for-loop// print_r($interesting_files);exit(-1);@@ -408,12 +419,12 @@ class RestoreFromBackup extends Command}if (strpos($sqlfiles[0], 'db-dumps') === false) {- //return $this->error("SQL backup file is missing 'db-dumps' component of full pathname: ".$sqlfiles[0]);- //older Snipe-IT installs don't have the db-dumps subdirectory component+ // return $this->error("SQL backup file is missing 'db-dumps' component of full pathname: ".$sqlfiles[0]);+ // older Snipe-IT installs don't have the db-dumps subdirectory component}$sql_stat = $za->statIndex($sqlfile_indices[0]);- //$this->info("SQL Stat is: ".print_r($sql_stat,true));+ // $this->info("SQL Stat is: ".print_r($sql_stat,true));$sql_contents = $za->getStream($sql_stat['name']); // maybe copy *THIS* thing?// OKAY, now that we *found* the sql file if we're doing just the guess-prefix thing, we can do that *HERE* I think?@@ -428,27 +439,28 @@ class RestoreFromBackup extends Commandif ($this->option('sql-stdout-only')) {$sql_importer = new SQLStreamer($sql_contents, STDOUT, $this->option('sanitize-with-prefix'));$bytes_read = $sql_importer->line_aware_piping();+return $this->warn("$bytes_read total bytes read");- //TODO - it'd be nice to dump this message to STDERR so that STDOUT is just pure SQL,+ // TODO - it'd be nice to dump this message to STDERR so that STDOUT is just pure SQL,// which would be good for redirecting to a file, and not having to trim the last line off of it}- //how to invoke the restore?+ // how to invoke the restore?$pipes = [];$env_vars = getenv();$env_vars['MYSQL_PWD'] = config('database.connections.mysql.password');// TODO notes: we are stealing the dump_binary_path (which *probably* also has your copy of the mysql binary in it. But it might not, so we might need to extend this)// we unilaterally prepend a slash to the `mysql` command. This might mean your path could look like /blah/blah/blah//mysql - which should be fine. But maybe in some environments it isn't?- $mysql_binary = config('database.connections.mysql.dump.dump_binary_path').\DIRECTORY_SEPARATOR.'mysql'.(\DIRECTORY_SEPARATOR == '\\' ? ".exe" : "");- if( ! file_exists($mysql_binary) ) {+ $mysql_binary = config('database.connections.mysql.dump.dump_binary_path').\DIRECTORY_SEPARATOR.'mysql'.(\DIRECTORY_SEPARATOR == '\\' ? '.exe' : '');+ if (! file_exists($mysql_binary)) {return $this->error("mysql tool at: '$mysql_binary' does not exist, cannot restore. Please edit DB_DUMP_PATH in your .env to point to a directory that contains the mysqldump and mysql binary");}$proc_results = proc_open("$mysql_binary -h ".escapeshellarg(config('database.connections.mysql.host')).' -u '.escapeshellarg(config('database.connections.mysql.username')).' '.escapeshellarg(config('database.connections.mysql.database')), // yanked -p since we pass via ENV- [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],- $pipes,- null,- $env_vars); // this is not super-duper awesome-secure, but definitely more secure than showing it on the CLI, or dropping temporary files with passwords in them.+ [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],+ $pipes,+ null,+ $env_vars); // this is not super-duper awesome-secure, but definitely more secure than showing it on the CLI, or dropping temporary files with passwords in them.if ($proc_results === false) {return $this->error('Unable to invoke mysql via CLI');}@@ -462,7 +474,7 @@ class RestoreFromBackup extends Command// should we read stdout?// fwrite($pipes[0],config("database.connections.mysql.password")."\n"); //this doesn't work :(- //$sql_contents = fopen($sqlfiles[0], "r"); //NOPE! This isn't a real file yet, silly-billy!+ // $sql_contents = fopen($sqlfiles[0], "r"); //NOPE! This isn't a real file yet, silly-billy!// FIXME - this feels like it wants to go somewhere else?// and it doesn't seem 'right' - if you can't get a stream to the .sql file,@@ -477,7 +489,7 @@ class RestoreFromBackup extends Command}try {- if ( $this->option('sanitize-with-prefix') === null) {+ if ($this->option('sanitize-with-prefix') === null) {// "Legacy" direct-piping$bytes_read = 0;while (($buffer = fgets($sql_contents, SQLStreamer::$buffer_size)) !== false) {@@ -486,7 +498,7 @@ class RestoreFromBackup extends Command$bytes_written = fwrite($pipes[0], $buffer);if ($bytes_written === false) {- throw new Exception("Unable to write to pipe");+ throw new Exception('Unable to write to pipe');}}} else {@@ -494,37 +506,37 @@ class RestoreFromBackup extends Command$bytes_read = $sql_importer->line_aware_piping();}} catch (\Exception $e) {- Log::error("Error during restore!!!! ".$e->getMessage());+ Log::error('Error during restore!!!! '.$e->getMessage());// FIXME - put these back and/or put them in the right places?!$err_out = fgets($pipes[1]);$err_err = fgets($pipes[2]);- Log::error("Error OUTPUT: ".$err_out);+ Log::error('Error OUTPUT: '.$err_out);$this->info($err_out);- Log::error("Error ERROR : ".$err_err);+ Log::error('Error ERROR : '.$err_err);$this->error($err_err);throw $e;}- if (!feof($sql_contents) || $bytes_read == 0) {- return $this->error("Not at end of file for sql file, or zero bytes read. aborting!");+ if (! feof($sql_contents) || $bytes_read == 0) {+ return $this->error('Not at end of file for sql file, or zero bytes read. aborting!');}-+fclose($pipes[0]);fclose($sql_contents);-+$this->line(stream_get_contents($pipes[1]));fclose($pipes[1]);$this->error(stream_get_contents($pipes[2]));fclose($pipes[2]);- //wait, have to do fclose() on all pipes first?+ // wait, have to do fclose() on all pipes first?$close_results = proc_close($proc_results);if ($close_results != 0) {return $this->error('There may have been a problem with the database import: Error number '.$close_results);}- //and now copy the files over too (right?)- //FIXME - we don't prune the filesystem space yet!!!!+ // and now copy the files over too (right?)+ // FIXME - we don't prune the filesystem space yet!!!!if ($this->option('no-progress')) {$bar = null;} else {@@ -532,16 +544,16 @@ class RestoreFromBackup extends Command}foreach ($interesting_files as $pretty_file_name => $file_details) {$ugly_file_name = $za->statIndex($file_details['index'])['name'];- $migrated_file_name = $file_details['dest'] . '/' . basename($pretty_file_name);- if (strcasecmp(substr($pretty_file_name, -4), ".svg") === 0) {+ $migrated_file_name = $file_details['dest'].'/'.basename($pretty_file_name);+ if (strcasecmp(substr($pretty_file_name, -4), '.svg') === 0) {$svg_contents = $za->getFromIndex($file_details['index']);$cleaned_svg = $sanitizer->sanitize($svg_contents);file_put_contents($migrated_file_name, $cleaned_svg);} else {$fp = $za->getStream($ugly_file_name);- //$this->info("Weird problem, here are file details? ".print_r($file_details,true));- if (!is_dir($file_details['dest'])) {- mkdir($file_details['dest'], 0755, true); //0755 is what Laravel uses, so we do that+ // $this->info("Weird problem, here are file details? ".print_r($file_details,true));+ if (! is_dir($file_details['dest'])) {+ mkdir($file_details['dest'], 0755, true); // 0755 is what Laravel uses, so we do that}$migrated_file = fopen($migrated_file_name, 'w');while (($buffer = fgets($fp, SQLStreamer::$buffer_size)) !== false) {@@ -549,7 +561,7 @@ class RestoreFromBackup extends Command}fclose($migrated_file);fclose($fp);- //$this->info("Wrote $ugly_file_name to $pretty_file_name");+ // $this->info("Wrote $ugly_file_name to $pretty_file_name");}if ($bar) {$bar->advance();diff --git a/app/Console/Commands/RotateAppKey.php b/app/Console/Commands/RotateAppKey.phpindex e4529962b2..87b5644cc6 100644--- a/app/Console/Commands/RotateAppKey.php+++ b/app/Console/Commands/RotateAppKey.php@@ -5,10 +5,10 @@ namespace App\Console\Commands;use App\Models\Asset;use App\Models\CustomField;use App\Models\Setting;-use Illuminate\Support\Facades\Artisan;use Illuminate\Console\Command;use Illuminate\Contracts\Encryption\DecryptException;use Illuminate\Encryption\Encrypter;+use Illuminate\Support\Facades\Artisan;class RotateAppKey extends Command{@@ -46,12 +46,13 @@ class RotateAppKey extends Command*/public function handle(){- //make sure they specify only exactly one of --emergency, or a filename. Not neither, and not both.- if ( (!$this->option('emergency') && !$this->argument('previous_key')) || ( $this->option('emergency') && $this->argument('previous_key'))) {- $this->error("Specify only one of --emergency, or an app key value, in order to rotate keys");+ // make sure they specify only exactly one of --emergency, or a filename. Not neither, and not both.+ if ((! $this->option('emergency') && ! $this->argument('previous_key')) || ($this->option('emergency') && $this->argument('previous_key'))) {+ $this->error('Specify only one of --emergency, or an app key value, in order to rotate keys');+return 1;}- if ( $this->option('emergency') ) {+ if ($this->option('emergency')) {$msg = "\n****************************************************\nTHIS WILL MODIFY YOUR APP_KEY AND DE-CRYPT YOUR ENCRYPTED CUSTOM FIELDS AND \nRE-ENCRYPT THEM WITH A NEWLY GENERATED KEY. \n\nThere is NO undo. \n\nMake SURE you have a database backup and a backup of your .env generated BEFORE running this command. \n\nIf you do not save the newly generated APP_KEY to your .env in this process, \nyour encrypted data will no longer be decryptable. \n\nAre you SURE you wish to continue, and have confirmed you have a database backup and an .env backup? ";} else {$msg = "\n****************************************************\nTHIS WILL DE-CRYPT YOUR ENCRYPTED CUSTOM FIELDS AND RE-ENCRYPT THEM WITH YOUR\nAPP_KEY.\n\nThere is NO undo. \n\nMake SURE you have a database backup BEFORE running this command. \n\nAre you SURE you wish to continue, and have confirmed you have a database backup? ";@@ -79,9 +80,9 @@ class RotateAppKey extends Command$new_app_key = config('app.key');}- $this->warn('Your app cipher is: ' . $cipher);- $this->warn('Your old APP_KEY is: ' . $old_app_key);- $this->warn('Your new APP_KEY is: ' . $new_app_key);+ $this->warn('Your app cipher is: '.$cipher);+ $this->warn('Your old APP_KEY is: '.$old_app_key);+ $this->warn('Your new APP_KEY is: '.$new_app_key);// Manually create an old encrypter instance using the old app key// and also create a new encrypter instance so we can re-crypt the field@@ -97,12 +98,13 @@ class RotateAppKey extends Commandforeach ($assets as $asset) {try {$asset->{$field->db_column} = $oldEncrypter->decrypt($asset->{$field->db_column});- $this->line('DECRYPTED: ' . $field->db_column);+ $this->line('DECRYPTED: '.$field->db_column);} catch (DecryptException $e) {- $this->line('Could not decrypt '. $field->db_column.' using "old key" - skipping...');+ $this->line('Could not decrypt '.$field->db_column.' using "old key" - skipping...');+continue;} catch (\Exception $e) {- $this->error("Error decrypting ".$field->db_column.", reason: ".$e->getMessage().". Aborting key rotation");+ $this->error('Error decrypting '.$field->db_column.', reason: '.$e->getMessage().'. Aborting key rotation');throw $e;}$asset->{$field->db_column} = $newEncrypter->encrypt($asset->{$field->db_column});@@ -119,8 +121,8 @@ class RotateAppKey extends Command$setting->ldap_pword = $newEncrypter->encrypt($setting->ldap_pword);$setting->save();$this->warn('LDAP password has been re-encrypted.');- } catch(DecryptException $e) {- $this->warn("Unable to decrypt old LDAP password; skipping");+ } catch (DecryptException $e) {+ $this->warn('Unable to decrypt old LDAP password; skipping');}}} else {diff --git a/app/Console/Commands/SamlClearExpiredNonces.php b/app/Console/Commands/SamlClearExpiredNonces.phpindex f03b55095e..95ea2ffcb8 100644--- a/app/Console/Commands/SamlClearExpiredNonces.php+++ b/app/Console/Commands/SamlClearExpiredNonces.php@@ -2,8 +2,8 @@namespace App\Console\Commands;-use Illuminate\Console\Command;use App\Models\SamlNonce;+use Illuminate\Console\Command;class SamlClearExpiredNonces extends Command{@@ -38,7 +38,8 @@ class SamlClearExpiredNonces extends Command*/public function handle(){- SamlNonce::where('not_valid_after','<=',now())->delete();+ SamlNonce::where('not_valid_after', '<=', now())->delete();+return 0;}}diff --git a/app/Console/Commands/SendAcceptanceReminder.php b/app/Console/Commands/SendAcceptanceReminder.phpindex 172a88f104..5e4ea97057 100644--- a/app/Console/Commands/SendAcceptanceReminder.php+++ b/app/Console/Commands/SendAcceptanceReminder.php@@ -9,10 +9,7 @@ use App\Models\CheckoutAcceptance;use App\Models\Component;use App\Models\Consumable;use App\Models\LicenseSeat;-use App\Models\Setting;use App\Models\User;-use App\Notifications\CheckoutAssetNotification;-use App\Notifications\CurrentInventory;use Illuminate\Console\Command;use Illuminate\Database\Eloquent\Relations\MorphTo;use Illuminate\Support\Facades\Mail;@@ -54,11 +51,11 @@ class SendAcceptanceReminder extends Command->with(['checkoutable' => function (MorphTo $morph) {$morph->morphWith([- Asset::class => ['model.category', 'assignedTo', 'adminuser', 'company', 'checkouts'],- Accessory::class => ['category', 'company', 'checkouts'],+ Asset::class => ['model.category', 'assignedTo', 'adminuser', 'company', 'checkouts'],+ Accessory::class => ['category', 'company', 'checkouts'],LicenseSeat::class => ['user', 'license', 'checkouts'],- Component::class => ['assignedTo', 'company', 'checkouts'],- Consumable::class => ['company', 'checkouts'],+ Component::class => ['assignedTo', 'company', 'checkouts'],+ Consumable::class => ['company', 'checkouts'],]);},'assignedTo',@@ -74,15 +71,15 @@ class SendAcceptanceReminder extends Command$count = 0;$unacceptedAssetGroups = $pending- ->map(function($acceptance) {+ ->map(function ($acceptance) {return ['assetItem' => $acceptance->checkoutable, 'acceptance' => $acceptance];})- ->groupBy(function($item) {+ ->groupBy(function ($item) {return $item['acceptance']->assignedTo ? $item['acceptance']->assignedTo->id : '';});- $no_email_list= [];+ $no_email_list = [];- foreach($unacceptedAssetGroups as $unacceptedAssetGroup) {+ foreach ($unacceptedAssetGroups as $unacceptedAssetGroup) {// The [0] is weird, but it allows for the item_count to work and grabs the appropriate info for each user.// Collapsing and flattening the collection doesn't work above.$acceptance = $unacceptedAssetGroup[0]['acceptance'];@@ -90,7 +87,7 @@ class SendAcceptanceReminder extends Command$locale = $acceptance->assignedTo?->locale;$email = $acceptance->assignedTo?->email;- if(!$email){+ if (! $email) {$no_email_list[] = ['id' => $acceptance->assignedTo?->id,'name' => $acceptance->assignedTo?->display_name,@@ -116,12 +113,11 @@ class SendAcceptanceReminder extends Command$rows[] = [$user['id'], $user['name']];}- if (!empty($rows)) {- $this->info("The following users do not have an email address:");+ if (! empty($rows)) {+ $this->info('The following users do not have an email address:');$this->table($headers, $rows);}return 0;}-}diff --git a/app/Console/Commands/SendExpectedCheckinAlerts.php b/app/Console/Commands/SendExpectedCheckinAlerts.phpindex 5836084152..bcc980e1cf 100644--- a/app/Console/Commands/SendExpectedCheckinAlerts.php+++ b/app/Console/Commands/SendExpectedCheckinAlerts.php@@ -2,6 +2,7 @@namespace App\Console\Commands;+use App\Helpers\Helper;use App\Models\Asset;use App\Models\Recipients\AlertRecipient;use App\Models\Setting;@@ -10,7 +11,6 @@ use App\Notifications\ExpectedCheckinNotification;use Carbon\Carbon;use Illuminate\Console\Command;use Illuminate\Support\Facades\Notification;-use App\Helpers\Helper;class SendExpectedCheckinAlerts extends Command{@@ -49,7 +49,7 @@ class SendExpectedCheckinAlerts extends Command$interval_date = $today->copy()->addDays($interval);$count = 0;- if (!$this->option('with-output')) {+ if (! $this->option('with-output')) {$this->info('Run this command with the --with-output option to see the full list in the console.');}@@ -57,9 +57,8 @@ class SendExpectedCheckinAlerts extends Command$this->info($assets->count().' assets must be checked on or before '.Helper::getFormattedDateObject($interval_date, 'date', false));-foreach ($assets as $asset) {- if ($asset->assignedTo && (isset($asset->assignedTo->email)) && ($asset->assignedTo->email!='') && $asset->checkedOutToUser()) {+ if ($asset->assignedTo && (isset($asset->assignedTo->email)) && ($asset->assignedTo->email != '') && $asset->checkedOutToUser()) {$asset->assignedTo->notify((new ExpectedCheckinNotification($asset)));$count++;}@@ -76,13 +75,13 @@ class SendExpectedCheckinAlerts extends Commandtrans('general.purchase_date'),trans('admin/hardware/form.expected_checkin'),],- $assets->map(fn($assets) => [+ $assets->map(fn ($assets) => [trans('general.id') => $assets->id,trans('admin/hardware/form.tag') => $assets->asset_tag,trans('admin/hardware/form.model') => $assets->model->name,trans('general.model_no') => $assets->model->model_number,trans('general.purchase_date') => $assets->purchase_date_formatted,- trans('admin/hardware/form.eol_date') => $assets->expected_checkin_formattedDate ? $assets->expected_checkin_formattedDate . ' (' . $assets->expected_checkin_diff_for_humans . ')' : '',+ trans('admin/hardware/form.eol_date') => $assets->expected_checkin_formattedDate ? $assets->expected_checkin_formattedDate.' ('.$assets->expected_checkin_diff_for_humans.')' : '',]));}@@ -96,7 +95,7 @@ class SendExpectedCheckinAlerts extends CommandNotification::send($recipients, new ExpectedCheckinAdminNotification($assets));}-+$this->info('Sent checkin reminders to to '.$count.' users.');}diff --git a/app/Console/Commands/SendExpirationAlerts.php b/app/Console/Commands/SendExpirationAlerts.phpindex 146fedd101..d2905fc426 100644--- a/app/Console/Commands/SendExpirationAlerts.php+++ b/app/Console/Commands/SendExpirationAlerts.php@@ -2,7 +2,6 @@namespace App\Console\Commands;-use App\Helpers\Helper;use App\Mail\ExpiringAssetsMail;use App\Mail\ExpiringLicenseMail;use App\Models\Asset;@@ -15,7 +14,7 @@ class SendExpirationAlerts extends Command{/*** The name and signature of the console command.- *+ ** @var string*/protected $signature = 'snipeit:expiring-alerts {--expired-licenses}';@@ -49,8 +48,8 @@ class SendExpirationAlerts extends Command// Send a rollup to the admin, if settings dictate$recipients = collect(explode(',', $settings->alert_email))- ->map(fn($item) => trim($item)) // Trim each email- ->filter(fn($item) => !empty($item))+ ->map(fn ($item) => trim($item)) // Trim each email+ ->filter(fn ($item) => ! empty($item))->all();// Expiring Assets$assets = Asset::getExpiringWarrantyOrEol($alert_interval);@@ -72,23 +71,22 @@ class SendExpirationAlerts extends Commandtrans('admin/hardware/form.eol_date'),trans('admin/hardware/form.warranty_expires'),],- $assets->map(fn($item) =>- [- trans('general.id') => $item->id,+ $assets->map(fn ($item) => [+ trans('general.id') => $item->id,trans('admin/hardware/form.tag') => $item->asset_tag,trans('admin/hardware/form.model') => $item->model->name,trans('general.model_no') => $item->model->model_number,trans('general.purchase_date') => $item->purchase_date_formatted,- trans('admin/hardware/form.eol_rate') => $item->model->eol,- trans('admin/hardware/form.eol_date') => $item->eol_date ? $item->eol_formatted_date .' ('.$item->eol_diff_for_humans.')' : '',- trans('admin/hardware/form.warranty_expires') => $item->warranty_expires ? $item->warranty_expires_formatted_date .' ('.$item->warranty_expires_diff_for_humans.')' : '',- ])- );+ trans('admin/hardware/form.eol_rate') => $item->model->eol,+ trans('admin/hardware/form.eol_date') => $item->eol_date ? $item->eol_formatted_date.' ('.$item->eol_diff_for_humans.')' : '',+ trans('admin/hardware/form.warranty_expires') => $item->warranty_expires ? $item->warranty_expires_formatted_date.' ('.$item->warranty_expires_diff_for_humans.')' : '',+ ])+ );}// Expiring licenses$licenses = License::query()->ExpiringLicenses($alert_interval, $this->option('expired-licenses'))- ->with('manufacturer','category')+ ->with('manufacturer', 'category')->orderBy('expiration_date', 'ASC')->orderBy('termination_date', 'ASC')->get();@@ -104,14 +102,14 @@ class SendExpirationAlerts extends Commandtrans('mail.expires'),trans('admin/licenses/form.termination_date'),trans('mail.terminates')],- $licenses->map(fn($item) => [+ $licenses->map(fn ($item) => [trans('general.id') => $item->id,trans('general.name') => $item->name,trans('general.purchase_date') => $item->purchase_date_formatted,trans('admin/licenses/form.expiration') => $item->expires_formatted_date,trans('mail.expires') => $item->expires_formatted_date ? $item->expires_diff_for_humans : '',trans('admin/licenses/form.termination_date') => $item->terminates_formatted_date,- trans('mail.terminates') => $item->terminates_diff_for_humans+ trans('mail.terminates') => $item->terminates_diff_for_humans,]));}@@ -120,12 +118,10 @@ class SendExpirationAlerts extends Command$this->info(trans_choice('mail.assets_warrantee_alert', $assets->count(), ['count' => $assets->count(), 'threshold' => $alert_interval]));$this->info(trans_choice('mail.license_expiring_alert', $licenses->count(), ['count' => $licenses->count(), 'threshold' => $alert_interval]));--} else {if ($settings->alert_email == '') {$this->error('Could not send email. No alert email configured in settings');- } elseif (1 != $settings->alerts_enabled) {+ } elseif ($settings->alerts_enabled != 1) {$this->info('Alerts are disabled in the settings. No mail will be sent');}}diff --git a/app/Console/Commands/SendInventoryAlerts.php b/app/Console/Commands/SendInventoryAlerts.phpindex f099597d9b..40d92ec153 100644--- a/app/Console/Commands/SendInventoryAlerts.php+++ b/app/Console/Commands/SendInventoryAlerts.php@@ -59,7 +59,7 @@ class SendInventoryAlerts extends Command} else {if ($settings->alert_email == '') {$this->error('Could not send email. No alert email configured in settings');- } elseif (1 != $settings->alerts_enabled) {+ } elseif ($settings->alerts_enabled != 1) {$this->info('Alerts are disabled in the settings. No mail will be sent');}}diff --git a/app/Console/Commands/SendUpcomingAuditReport.php b/app/Console/Commands/SendUpcomingAuditReport.phpindex 5112acb482..21b5c5b8d0 100644--- a/app/Console/Commands/SendUpcomingAuditReport.php+++ b/app/Console/Commands/SendUpcomingAuditReport.php@@ -49,12 +49,11 @@ class SendUpcomingAuditReport extends Command$assets_query = Asset::whereNull('deleted_at')->dueOrOverdueForAudit($settings)->orderBy('assets.next_audit_date', 'asc')->with('supplier');$asset_count = $assets_query->count();- $this->info(number_format($asset_count) . ' assets must be audited on or before ' . $interval_date);- if (!$this->option('with-output')) {+ $this->info(number_format($asset_count).' assets must be audited on or before '.$interval_date);+ if (! $this->option('with-output')) {$this->info('Run this command with the --with-output option to see the full list in the console.');}-if ($asset_count > 0) {$assets_for_email = $assets_query->limit(30)->get();@@ -63,22 +62,19 @@ class SendUpcomingAuditReport extends Commandif ($settings->alert_email != '') {$recipients = collect(explode(',', $settings->alert_email))- ->map(fn($item) => trim($item))- ->filter(fn($item) => !empty($item))+ ->map(fn ($item) => trim($item))+ ->filter(fn ($item) => ! empty($item))->all();Mail::to($recipients)->send(new SendUpcomingAuditMail($assets_for_email, $settings->audit_warning_days, $asset_count));- $this->info('Audit notification sent to: ' . $settings->alert_email);+ $this->info('Audit notification sent to: '.$settings->alert_email);} else {$this->info('There is no admin alert email set so no email will be sent.');}--if ($this->option('with-output')) {-// Get the full list if the user wants output in the console$assets_for_output = $assets_query->limit(null)->get();@@ -93,7 +89,7 @@ class SendUpcomingAuditReport extends Commandtrans('mail.assigned_to'),],- $assets_for_output->map(fn($item) => [+ $assets_for_output->map(fn ($item) => [trans('general.id') => $item->id,trans('general.name') => $item->display_name,trans('general.last_audit') => $item->last_audit_formatted_date,@@ -106,10 +102,8 @@ class SendUpcomingAuditReport extends Command}} else {- $this->info('There are no assets due for audit in the next ' . $interval . ' days.');+ $this->info('There are no assets due for audit in the next '.$interval.' days.');}--}}diff --git a/app/Console/Commands/SyncAssetCounters.php b/app/Console/Commands/SyncAssetCounters.phpindex 2e2bb18f3b..5a90a47278 100644--- a/app/Console/Commands/SyncAssetCounters.php+++ b/app/Console/Commands/SyncAssetCounters.php@@ -63,16 +63,14 @@ class SyncAssetCounters extends Command}- } else {- $this->info('No assets to sync');- }- });-+ } else {+ $this->info('No assets to sync');+ }+ });$bar->finish();$time_elapsed_secs = microtime(true) - $start;$this->info("\nSync of ".$assets_count.' assets executed in '.$time_elapsed_secs.' seconds');-}}diff --git a/app/Console/Commands/SyncAssetLocations.php b/app/Console/Commands/SyncAssetLocations.phpindex f510176bce..992f8ba096 100644--- a/app/Console/Commands/SyncAssetLocations.php+++ b/app/Console/Commands/SyncAssetLocations.php@@ -3,6 +3,8 @@namespace App\Console\Commands;use App\Models\Asset;+use App\Models\Location;+use App\Models\User;use Illuminate\Console\Command;class SyncAssetLocations extends Command@@ -57,7 +59,7 @@ class SyncAssetLocations extends Command$bar->advance();}- $assigned_user_assets = Asset::where('assigned_type', \App\Models\User::class)->whereNotNull('assigned_to')->whereNull('deleted_at')->get();+ $assigned_user_assets = Asset::where('assigned_type', User::class)->whereNotNull('assigned_to')->whereNull('deleted_at')->get();$output['info'][] = 'There are '.$assigned_user_assets->count().' assets checked out to users.';foreach ($assigned_user_assets as $assigned_user_asset) {if (($assigned_user_asset->assignedTo) && ($assigned_user_asset->assignedTo->userLoc)) {@@ -73,7 +75,7 @@ class SyncAssetLocations extends Command$bar->advance();}- $assigned_location_assets = Asset::where('assigned_type', \App\Models\Location::class)+ $assigned_location_assets = Asset::where('assigned_type', Location::class)->whereNotNull('assigned_to')->whereNull('deleted_at')->get();$output['info'][] = 'There are '.$assigned_location_assets->count().' assets checked out to locations.';@@ -90,13 +92,13 @@ class SyncAssetLocations extends Command}// Assigned to assets- $assigned_asset_assets = Asset::where('assigned_type', \App\Models\Asset::class)+ $assigned_asset_assets = Asset::where('assigned_type', Asset::class)->whereNotNull('assigned_to')->whereNull('deleted_at')->get();$output['info'][] = 'Asset-assigned assets: '.$assigned_asset_assets->count();foreach ($assigned_asset_assets as $assigned_asset_asset) {- // Check to make sure there aren't any invalid relationships+ // Check to make sure there aren't any invalid relationshipsif ($assigned_asset_asset->assetLoc()) {$assigned_asset_asset->location_id = $assigned_asset_asset->assetLoc()->id;$output['info'][] = 'Setting Asset Assigned asset '.$assigned_asset_asset->assetLoc()->id.' ('.$assigned_asset_asset->asset_tag.') location to: '.$assigned_asset_asset->assetLoc()->id;diff --git a/app/Console/Commands/SystemBackup.php b/app/Console/Commands/SystemBackup.phpindex fda95794d7..f859845222 100644--- a/app/Console/Commands/SystemBackup.php+++ b/app/Console/Commands/SystemBackup.php@@ -37,13 +37,13 @@ class SystemBackup extends Command*/public function handle(){- ini_set('max_execution_time', env('BACKUP_TIME_LIMIT', 600)); //600 seconds = 10 minutes+ ini_set('max_execution_time', env('BACKUP_TIME_LIMIT', 600)); // 600 seconds = 10 minutesif ($this->option('filename')) {$filename = $this->option('filename');// Make sure the filename ends in .zip- if (!ends_with($filename, '.zip')) {+ if (! ends_with($filename, '.zip')) {$filename = $filename.'.zip';}diff --git a/app/Console/Commands/TestLocationsFMCS.php b/app/Console/Commands/TestLocationsFMCS.phpindex 70eface2de..ebe76fd692 100644--- a/app/Console/Commands/TestLocationsFMCS.php+++ b/app/Console/Commands/TestLocationsFMCS.php@@ -47,5 +47,4 @@ class TestLocationsFMCS extends Command$this->table($header, $mismatched);}-}diff --git a/app/Console/Commands/ToggleCustomfieldEncryption.php b/app/Console/Commands/ToggleCustomfieldEncryption.phpindex 2ba07f7bd1..7dbf0f256c 100644--- a/app/Console/Commands/ToggleCustomfieldEncryption.php+++ b/app/Console/Commands/ToggleCustomfieldEncryption.php@@ -17,7 +17,6 @@ class ToggleCustomfieldEncryption extends Commandprotected $signature = 'snipeit:customfield-encryption{fieldname : the db_column_name of the field}';-/*** The console command description.*@@ -61,15 +60,15 @@ class ToggleCustomfieldEncryption extends Command$field->field_encrypted = 1;$field->save();- // This field is already encrypted. Do nothing.+ // This field is already encrypted. Do nothing.} else {- $this->error('The custom field ' . $field->db_column.' is already encrypted. No action was taken.');+ $this->error('The custom field '.$field->db_column.' is already encrypted. No action was taken.');}});- // No matching column name found+ // No matching column name found} else {- $this->error('No matching results for unencrypted custom fields with db_column name: ' . $fieldname.'. Please check the fieldname.');+ $this->error('No matching results for unencrypted custom fields with db_column name: '.$fieldname.'. Please check the fieldname.');}}diff --git a/app/Console/Commands/Version.php b/app/Console/Commands/Version.phpindex 0a10f4f541..4d78743484 100644--- a/app/Console/Commands/Version.php+++ b/app/Console/Commands/Version.php@@ -87,7 +87,7 @@ class Version extends Command$app_version = 'v'."$maj.".($min + 1).".$patch";} elseif ($use_type == 'patch') {$app_version = 'v'."$maj.$min.".($patch + 1);- // If nothing is passed, leave the version as it is, just increment the build+ // If nothing is passed, leave the version as it is, just increment the build} else {$app_version = 'v'."$maj.$min.".$patch;}diff --git a/app/Console/Kernel.php b/app/Console/Kernel.phpindex ca85459b67..9c7d299174 100644--- a/app/Console/Kernel.php+++ b/app/Console/Kernel.php@@ -2,9 +2,6 @@namespace App\Console;-use App\Console\Commands\ImportLocations;-use App\Console\Commands\ReEncodeCustomFieldNames;-use App\Console\Commands\RestoreDeletedUsers;use App\Models\Setting;use Illuminate\Console\Scheduling\Schedule;use Illuminate\Foundation\Console\Kernel as ConsoleKernel;@@ -14,12 +11,11 @@ class Kernel extends ConsoleKernel/*** Define the application's command schedule.*- * @param \Illuminate\Console\Scheduling\Schedule $schedule* @return void*/protected function schedule(Schedule $schedule){- if(Setting::getSettings()?->alerts_enabled === 1) {+ if (Setting::getSettings()?->alerts_enabled === 1) {$schedule->command('snipeit:inventory-alerts')->daily();$schedule->command('snipeit:expiring-alerts')->daily();$schedule->command('snipeit:expected-checkin')->daily();