From 4ed8ff557644d80752842df72c6893a41324a0ec Mon Sep 17 00:00:00 2001 From: snipe Date: Wed, 22 Jun 2016 12:27:41 -0700 Subject: [PATCH] Formatting fixes for coding standards --- app/Console/Commands/AssetImportCommand.php | 845 +++++---- app/Console/Commands/CreateAdmin.php | 46 +- app/Console/Commands/DisableLDAP.php | 1 - app/Console/Commands/LicenseImportCommand.php | 599 +++--- app/Console/Commands/ObjectImportCommand.php | 1642 +++++++++-------- app/Console/Commands/PaveIt.php | 136 +- app/Console/Commands/Purge.php | 4 +- app/Console/Commands/SendExpirationAlerts.php | 185 +- app/Console/Commands/SendInventoryAlerts.php | 19 +- app/Console/Commands/SystemBackup.php | 68 +- app/Console/Commands/Versioning.php | 15 +- .../Controllers/AccessoriesController.php | 2 +- .../Controllers/AssetModelsController.php | 8 +- app/Http/Controllers/AssetsController.php | 54 +- app/Http/Controllers/CategoriesController.php | 17 +- .../Controllers/CustomFieldsController.php | 3 +- .../Controllers/DepreciationsController.php | 1 - app/Http/Controllers/GroupsController.php | 2 +- app/Http/Controllers/LicensesController.php | 20 +- app/Http/Controllers/LocationsController.php | 2 +- app/Http/Controllers/ReportsController.php | 2 +- app/Http/Controllers/SettingsController.php | 6 +- app/Http/Controllers/UsersController.php | 77 +- app/Http/Controllers/ViewAssetsController.php | 6 +- app/Http/Middleware/CheckForSetup.php | 24 +- app/Http/Middleware/CheckPermissions.php | 1 - app/Http/Requests/AssetRequest.php | 4 +- app/Http/routes.php | 24 +- app/Models/Accessory.php | 2 +- app/Models/Asset.php | 29 +- app/Models/Company.php | 2 +- app/Models/Group.php | 3 - app/Models/Setting.php | 19 +- app/Models/User.php | 7 +- 34 files changed, 1940 insertions(+), 1935 deletions(-) diff --git a/app/Console/Commands/AssetImportCommand.php b/app/Console/Commands/AssetImportCommand.php index 103a5226cf..851a3c216f 100644 --- a/app/Console/Commands/AssetImportCommand.php +++ b/app/Console/Commands/AssetImportCommand.php @@ -1,5 +1,6 @@ argument('filename'); + /** + * Execute the console command. + * + * @return mixed + */ + public function fire() + { + $filename = $this->argument('filename'); - if (!$this->option('testrun')=='true') { - $this->comment('======= Importing Assets from '.$filename.' ========='); - } else { - $this->comment('====== TEST ONLY Asset Import for '.$filename.' ===='); - $this->comment('============== NO DATA WILL BE WRITTEN =============='); - } - - if (! ini_get("auto_detect_line_endings")) { - ini_set("auto_detect_line_endings", '1'); - } - - $csv = Reader::createFromPath($this->argument('filename')); - $csv->setNewline("\r\n"); - $csv->setOffset(1); - $duplicates = ''; - - // Loop through the records - $nbInsert = $csv->each(function ($row) use ($duplicates) { - $status_id = 1; - - // Let's just map some of these entries to more user friendly words - - // User's name - if (array_key_exists('0',$row)) { - $user_name = trim($row[0]); - } else { - $user_name = ''; - } - - // User's email - if (array_key_exists('1',$row)) { - $user_email = trim($row[1]); - } else { - $user_email = ''; - } - - // User's email - if (array_key_exists('2',$row)) { - $user_username = trim($row[2]); - } else { - $user_username = ''; - } - - // Asset Name - if (array_key_exists('3',$row)) { - $user_asset_asset_name = trim($row[3]); - } else { - $user_asset_asset_name = ''; - } - - // Asset Category - if (array_key_exists('4',$row)) { - $user_asset_category = trim($row[4]); - } else { - $user_asset_category = ''; - } - - // Asset Name - if (array_key_exists('5',$row)) { - $user_asset_name = trim($row[5]); - } else { - $user_asset_name = ''; - } - - // Asset Manufacturer - if (array_key_exists('6',$row)) { - $user_asset_mfgr = trim($row[6]); - } else { - $user_asset_mfgr = ''; - } - - // Asset model number - if (array_key_exists('7',$row)) { - $user_asset_modelno = trim($row[7]); - } else { - $user_asset_modelno = ''; - } - - // Asset serial number - if (array_key_exists('8',$row)) { - $user_asset_serial = trim($row[8]); - } else { - $user_asset_serial = ''; - } - - // Asset tag - if (array_key_exists('9',$row)) { - $user_asset_tag = trim($row[9]); - } else { - $user_asset_tag = ''; - } - - // Asset location - if (array_key_exists('10',$row)) { - $user_asset_location = trim($row[10]); - } else { - $user_asset_location = ''; - } - - // Asset notes - if (array_key_exists('11',$row)) { - $user_asset_notes = trim($row[11]); - } else { - $user_asset_notes = ''; - } - - // Asset purchase date - if (array_key_exists('12',$row)) { - if ($row[12]!='') { - $user_asset_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12])); - } else { - $user_asset_purchase_date = ''; - } - } else { - $user_asset_purchase_date = ''; - } - - // Asset purchase cost - if (array_key_exists('13',$row)) { - if ($row[13]!='') { - $user_asset_purchase_cost = trim($row[13]); - } else { - $user_asset_purchase_cost = ''; - } - } else { - $user_asset_purchase_cost = ''; - } - - // Asset Company Name - if (array_key_exists('14',$row)) { - if ($row[14]!='') { - $user_asset_company_name = trim($row[14]); - } else { - $user_asset_company_name= ''; - } - } else { - $user_asset_company_name = ''; - } - - - // A number was given instead of a name - if (is_numeric($user_name)) { - $this->comment('User '.$user_name.' is not a name - assume this user already exists'); - $user_username = ''; - $first_name = ''; - $last_name = ''; - - // No name was given - } elseif ($user_name=='') { - $this->comment('No user data provided - skipping user creation, just adding asset'); - $first_name = ''; - $last_name = ''; - //$user_username = ''; - - } else { - $user_email_array = User::generateFormattedNameFromFullName($this->option('email_format'), $user_name); - $first_name = $user_email_array['first_name']; - $last_name = $user_email_array['last_name']; - - if ($user_email=='') { - $user_email = $user_email_array['username'].'@'.config('app.domain'); - } - - if ($user_username=='') { - if ($this->option('username_format')=='email') { - $user_username = $user_email; - } else { - $user_name_array = User::generateFormattedNameFromFullName($this->option('username_format'), $user_name); - $user_username = $user_name_array['username']; - } - - } - - } - - $this->comment('Full Name: '.$user_name); - $this->comment('First Name: '.$first_name); - $this->comment('Last Name: '.$last_name); - $this->comment('Username: '.$user_username); - $this->comment('Email: '.$user_email); - $this->comment('Category Name: '.$user_asset_category); - $this->comment('Item: '.$user_asset_name); - $this->comment('Manufacturer ID: '.$user_asset_mfgr); - $this->comment('Model No: '.$user_asset_modelno); - $this->comment('Serial No: '.$user_asset_serial); - $this->comment('Asset Tag: '.$user_asset_tag); - $this->comment('Location: '.$user_asset_location); - $this->comment('Purchase Date: '.$user_asset_purchase_date); - $this->comment('Purchase Cost: '.$user_asset_purchase_cost); - $this->comment('Notes: '.$user_asset_notes); - $this->comment('Company Name: '.$user_asset_company_name); - - $this->comment('------------- Action Summary ----------------'); - - if ($user_username!='') { - if ($user = User::MatchEmailOrUsername($user_username, $user_email) - ->whereNotNull('username')->first()) { - $this->comment('User '.$user_username.' already exists'); - } else { - $user = new \App\Models\User; - $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); - - $user->first_name = $first_name; - $user->last_name = $last_name; - $user->username = $user_username; - $user->email = $user_email; - $user->permissions = '{user":1}'; - $user->password = bcrypt($password); - $user->activated = 1; - if ($user->save()) { - $this->comment('User '.$first_name.' created'); - } else { - $this->error('ERROR CREATING User '.$first_name.' '.$last_name); - $this->error($user->getErrors()); - } - - } - } else { - $user = new User; - } - - // Check for the location match and create it if it doesn't exist - if ($location = Location::where('name', e($user_asset_location))->first()) { - $this->comment('Location '.$user_asset_location.' already exists'); - } else { - - $location = new Location(); - - if ($user_asset_location!='') - { - $location->name = e($user_asset_location); - $location->address = ''; - $location->city = ''; - $location->state = ''; - $location->country = ''; - $location->user_id = 1; - - if (!$this->option('testrun')=='true') { - - if ($location->save()) { - $this->comment('Location '.$user_asset_location.' was created'); - } else { - $this->error('Something went wrong! Location '.$user_asset_location.' was NOT created'); - $this->error($location->getErrors()); - } - - } - else - { - $this->comment('Location '.$user_asset_location.' was (not) created - test run only'); - } - } - else - { - $this->comment('No location given, so none created.'); - } - - } - - if (e($user_asset_category)=='') { - $category_name = 'Unnamed Category'; + if (!$this->option('testrun')=='true') { + $this->comment('======= Importing Assets from '.$filename.' ========='); } else { - $category_name = e($user_asset_category); + $this->comment('====== TEST ONLY Asset Import for '.$filename.' ===='); + $this->comment('============== NO DATA WILL BE WRITTEN =============='); } - // Check for the category match and create it if it doesn't exist - if ($category = Category::where('name', e($category_name))->where('category_type', 'asset')->first()) { - $this->comment('Category '.$category_name.' already exists'); + if (! ini_get("auto_detect_line_endings")) { + ini_set("auto_detect_line_endings", '1'); + } - } else { - $category = new Category(); - $category->name = e($category_name); - $category->category_type = 'asset'; - $category->user_id = 1; + $csv = Reader::createFromPath($this->argument('filename')); + $csv->setNewline("\r\n"); + $csv->setOffset(1); + $duplicates = ''; - if ($category->save()) { - $this->comment('Category '.$user_asset_category.' was created'); + // Loop through the records + $nbInsert = $csv->each(function ($row) use ($duplicates) { + $status_id = 1; + + // Let's just map some of these entries to more user friendly words + + // User's name + if (array_key_exists('0', $row)) { + $user_name = trim($row[0]); } else { - $this->error('Something went wrong! Category '.$user_asset_category.' was NOT created'); - $this->error($category->getErrors()); - } - - } - - // Check for the manufacturer match and create it if it doesn't exist - if ($manufacturer = Manufacturer::where('name', e($user_asset_mfgr))->first()) { - $this->comment('Manufacturer '.$user_asset_mfgr.' already exists'); - } else { - $manufacturer = new Manufacturer(); - $manufacturer->name = e($user_asset_mfgr); - $manufacturer->user_id = 1; - - if ($manufacturer->save()) { - $this->comment('Manufacturer '.$user_asset_mfgr.' was created'); - } else { - $this->error('Something went wrong! Manufacturer '.$user_asset_mfgr.' was NOT created: '. $manufacturer->getErrors()->first()); - } - - } - - // Check for the asset model match and create it if it doesn't exist - if ($asset_model = AssetModel::where('name', e($user_asset_name))->where('modelno', e($user_asset_modelno))->where('category_id', $category->id)->where('manufacturer_id', $manufacturer->id)->first()) { - $this->comment('The Asset Model '.$user_asset_name.' with model number '.$user_asset_modelno.' already exists'); - } else { - $asset_model = new AssetModel(); - $asset_model->name = e($user_asset_name); - $asset_model->manufacturer_id = $manufacturer->id; - $asset_model->modelno = e($user_asset_modelno); - $asset_model->category_id = $category->id; - $asset_model->user_id = 1; - - if ($asset_model->save()) { - $this->comment('Asset Model '.$user_asset_name.' with model number '.$user_asset_modelno.' was created'); - } else { - $this->error('Something went wrong! Asset Model '.$user_asset_name.' was NOT created: '.$asset_model->getErrors()->first()); - } - - } - - // Check for the asset company match and create it if it doesn't exist - if ($user_asset_company_name!='') { - if ($company = Company::where('name', e($user_asset_company_name))->first()) { - $this->comment('Company '.$user_asset_company_name.' already exists'); - } else { - $company = new Company(); - $company->name = e($user_asset_company_name); - - if ($company->save()) { - $this->comment('Company '.$user_asset_company_name.' was created'); - } else { - $this->error('Something went wrong! Company '.$user_asset_company_name.' was NOT created: '.$company->getErrors()->first()); - } + $user_name = ''; } - } else { - $company = new Company(); - } + // User's email + if (array_key_exists('1', $row)) { + $user_email = trim($row[1]); + } else { + $user_email = ''; + } - // Check for the asset match and create it if it doesn't exist - if ($asset = Asset::where('asset_tag', e($user_asset_tag))->first()) { - $this->comment('The Asset with asset tag '.$user_asset_tag.' already exists'); - } else { - $asset = new Asset(); - $asset->name = e($user_asset_asset_name); - if ($user_asset_purchase_date!='') { - $asset->purchase_date = $user_asset_purchase_date; - } else { - $asset->purchase_date = null; - } - if ($user_asset_purchase_cost!='') { - $asset->purchase_cost = ParseFloat(e($user_asset_purchase_cost)); - } else { - $asset->purchase_cost = 0.00; - } - $asset->serial = e($user_asset_serial); - $asset->asset_tag = e($user_asset_tag); - $asset->model_id = $asset_model->id; - $asset->assigned_to = $user->id; - $asset->rtd_location_id = $location->id; - $asset->user_id = 1; - $asset->status_id = $status_id; - $asset->company_id = $company->id; - if ($user_asset_purchase_date!='') { - $asset->purchase_date = $user_asset_purchase_date; - } else { - $asset->purchase_date = null; - } - $asset->notes = e($user_asset_notes); + // User's email + if (array_key_exists('2', $row)) { + $user_username = trim($row[2]); + } else { + $user_username = ''; + } - if ($asset->save()) { - $this->comment('Asset '.$user_asset_name.' with serial number '.$user_asset_serial.' was created'); - } else { - $this->error('Something went wrong! Asset '.$user_asset_name.' was NOT created: '.$asset->getErrors()->first()); - } + // Asset Name + if (array_key_exists('3', $row)) { + $user_asset_asset_name = trim($row[3]); + } else { + $user_asset_asset_name = ''; + } - } + // Asset Category + if (array_key_exists('4', $row)) { + $user_asset_category = trim($row[4]); + } else { + $user_asset_category = ''; + } + + // Asset Name + if (array_key_exists('5', $row)) { + $user_asset_name = trim($row[5]); + } else { + $user_asset_name = ''; + } + + // Asset Manufacturer + if (array_key_exists('6', $row)) { + $user_asset_mfgr = trim($row[6]); + } else { + $user_asset_mfgr = ''; + } + + // Asset model number + if (array_key_exists('7', $row)) { + $user_asset_modelno = trim($row[7]); + } else { + $user_asset_modelno = ''; + } + + // Asset serial number + if (array_key_exists('8', $row)) { + $user_asset_serial = trim($row[8]); + } else { + $user_asset_serial = ''; + } + + // Asset tag + if (array_key_exists('9', $row)) { + $user_asset_tag = trim($row[9]); + } else { + $user_asset_tag = ''; + } + + // Asset location + if (array_key_exists('10', $row)) { + $user_asset_location = trim($row[10]); + } else { + $user_asset_location = ''; + } + + // Asset notes + if (array_key_exists('11', $row)) { + $user_asset_notes = trim($row[11]); + } else { + $user_asset_notes = ''; + } + + // Asset purchase date + if (array_key_exists('12', $row)) { + if ($row[12]!='') { + $user_asset_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12])); + } else { + $user_asset_purchase_date = ''; + } + } else { + $user_asset_purchase_date = ''; + } + + // Asset purchase cost + if (array_key_exists('13', $row)) { + if ($row[13]!='') { + $user_asset_purchase_cost = trim($row[13]); + } else { + $user_asset_purchase_cost = ''; + } + } else { + $user_asset_purchase_cost = ''; + } + + // Asset Company Name + if (array_key_exists('14', $row)) { + if ($row[14]!='') { + $user_asset_company_name = trim($row[14]); + } else { + $user_asset_company_name= ''; + } + } else { + $user_asset_company_name = ''; + } + + + // A number was given instead of a name + if (is_numeric($user_name)) { + $this->comment('User '.$user_name.' is not a name - assume this user already exists'); + $user_username = ''; + $first_name = ''; + $last_name = ''; + + // No name was given + } elseif ($user_name=='') { + $this->comment('No user data provided - skipping user creation, just adding asset'); + $first_name = ''; + $last_name = ''; + //$user_username = ''; + + } else { + $user_email_array = User::generateFormattedNameFromFullName($this->option('email_format'), $user_name); + $first_name = $user_email_array['first_name']; + $last_name = $user_email_array['last_name']; + + if ($user_email=='') { + $user_email = $user_email_array['username'].'@'.config('app.domain'); + } + + if ($user_username=='') { + if ($this->option('username_format')=='email') { + $user_username = $user_email; + } else { + $user_name_array = User::generateFormattedNameFromFullName($this->option('username_format'), $user_name); + $user_username = $user_name_array['username']; + } + + } + + } + + $this->comment('Full Name: '.$user_name); + $this->comment('First Name: '.$first_name); + $this->comment('Last Name: '.$last_name); + $this->comment('Username: '.$user_username); + $this->comment('Email: '.$user_email); + $this->comment('Category Name: '.$user_asset_category); + $this->comment('Item: '.$user_asset_name); + $this->comment('Manufacturer ID: '.$user_asset_mfgr); + $this->comment('Model No: '.$user_asset_modelno); + $this->comment('Serial No: '.$user_asset_serial); + $this->comment('Asset Tag: '.$user_asset_tag); + $this->comment('Location: '.$user_asset_location); + $this->comment('Purchase Date: '.$user_asset_purchase_date); + $this->comment('Purchase Cost: '.$user_asset_purchase_cost); + $this->comment('Notes: '.$user_asset_notes); + $this->comment('Company Name: '.$user_asset_company_name); + + $this->comment('------------- Action Summary ----------------'); + + if ($user_username!='') { + if ($user = User::MatchEmailOrUsername($user_username, $user_email) + ->whereNotNull('username')->first()) { + $this->comment('User '.$user_username.' already exists'); + } else { + $user = new \App\Models\User; + $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); + + $user->first_name = $first_name; + $user->last_name = $last_name; + $user->username = $user_username; + $user->email = $user_email; + $user->permissions = '{user":1}'; + $user->password = bcrypt($password); + $user->activated = 1; + if ($user->save()) { + $this->comment('User '.$first_name.' created'); + } else { + $this->error('ERROR CREATING User '.$first_name.' '.$last_name); + $this->error($user->getErrors()); + } + + } + } else { + $user = new User; + } + + // Check for the location match and create it if it doesn't exist + if ($location = Location::where('name', e($user_asset_location))->first()) { + $this->comment('Location '.$user_asset_location.' already exists'); + } else { + + $location = new Location(); + + if ($user_asset_location!='') { + $location->name = e($user_asset_location); + $location->address = ''; + $location->city = ''; + $location->state = ''; + $location->country = ''; + $location->user_id = 1; + + if (!$this->option('testrun')=='true') { + + if ($location->save()) { + $this->comment('Location '.$user_asset_location.' was created'); + } else { + $this->error('Something went wrong! Location '.$user_asset_location.' was NOT created'); + $this->error($location->getErrors()); + } + + } else { + $this->comment('Location '.$user_asset_location.' was (not) created - test run only'); + } + } else { + $this->comment('No location given, so none created.'); + } + + } + + if (e($user_asset_category)=='') { + $category_name = 'Unnamed Category'; + } else { + $category_name = e($user_asset_category); + } + + // Check for the category match and create it if it doesn't exist + if ($category = Category::where('name', e($category_name))->where('category_type', 'asset')->first()) { + $this->comment('Category '.$category_name.' already exists'); + + } else { + $category = new Category(); + $category->name = e($category_name); + $category->category_type = 'asset'; + $category->user_id = 1; + + if ($category->save()) { + $this->comment('Category '.$user_asset_category.' was created'); + } else { + $this->error('Something went wrong! Category '.$user_asset_category.' was NOT created'); + $this->error($category->getErrors()); + } + + } + + // Check for the manufacturer match and create it if it doesn't exist + if ($manufacturer = Manufacturer::where('name', e($user_asset_mfgr))->first()) { + $this->comment('Manufacturer '.$user_asset_mfgr.' already exists'); + } else { + $manufacturer = new Manufacturer(); + $manufacturer->name = e($user_asset_mfgr); + $manufacturer->user_id = 1; + + if ($manufacturer->save()) { + $this->comment('Manufacturer '.$user_asset_mfgr.' was created'); + } else { + $this->error('Something went wrong! Manufacturer '.$user_asset_mfgr.' was NOT created: '. $manufacturer->getErrors()->first()); + } + + } + + // Check for the asset model match and create it if it doesn't exist + if ($asset_model = AssetModel::where('name', e($user_asset_name))->where('modelno', e($user_asset_modelno))->where('category_id', $category->id)->where('manufacturer_id', $manufacturer->id)->first()) { + $this->comment('The Asset Model '.$user_asset_name.' with model number '.$user_asset_modelno.' already exists'); + } else { + $asset_model = new AssetModel(); + $asset_model->name = e($user_asset_name); + $asset_model->manufacturer_id = $manufacturer->id; + $asset_model->modelno = e($user_asset_modelno); + $asset_model->category_id = $category->id; + $asset_model->user_id = 1; + + if ($asset_model->save()) { + $this->comment('Asset Model '.$user_asset_name.' with model number '.$user_asset_modelno.' was created'); + } else { + $this->error('Something went wrong! Asset Model '.$user_asset_name.' was NOT created: '.$asset_model->getErrors()->first()); + } + + } + + // Check for the asset company match and create it if it doesn't exist + if ($user_asset_company_name!='') { + if ($company = Company::where('name', e($user_asset_company_name))->first()) { + $this->comment('Company '.$user_asset_company_name.' already exists'); + } else { + $company = new Company(); + $company->name = e($user_asset_company_name); + + if ($company->save()) { + $this->comment('Company '.$user_asset_company_name.' was created'); + } else { + $this->error('Something went wrong! Company '.$user_asset_company_name.' was NOT created: '.$company->getErrors()->first()); + } + } + + } else { + $company = new Company(); + } + + // Check for the asset match and create it if it doesn't exist + if ($asset = Asset::where('asset_tag', e($user_asset_tag))->first()) { + $this->comment('The Asset with asset tag '.$user_asset_tag.' already exists'); + } else { + $asset = new Asset(); + $asset->name = e($user_asset_asset_name); + if ($user_asset_purchase_date!='') { + $asset->purchase_date = $user_asset_purchase_date; + } else { + $asset->purchase_date = null; + } + if ($user_asset_purchase_cost!='') { + $asset->purchase_cost = ParseFloat(e($user_asset_purchase_cost)); + } else { + $asset->purchase_cost = 0.00; + } + $asset->serial = e($user_asset_serial); + $asset->asset_tag = e($user_asset_tag); + $asset->model_id = $asset_model->id; + $asset->assigned_to = $user->id; + $asset->rtd_location_id = $location->id; + $asset->user_id = 1; + $asset->status_id = $status_id; + $asset->company_id = $company->id; + if ($user_asset_purchase_date!='') { + $asset->purchase_date = $user_asset_purchase_date; + } else { + $asset->purchase_date = null; + } + $asset->notes = e($user_asset_notes); + + if ($asset->save()) { + $this->comment('Asset '.$user_asset_name.' with serial number '.$user_asset_serial.' was created'); + } else { + $this->error('Something went wrong! Asset '.$user_asset_name.' was NOT created: '.$asset->getErrors()->first()); + } + + } - $this->comment('====================================='); + $this->comment('====================================='); - return true; + return true; - }); + }); - } + } - /** - * Get the console command arguments. - * - * @return array - */ - protected function getArguments() - { - return array( - array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), - ); - } - - - /** - * Get the console command options. - * - * @return array - */ - protected function getOptions() - { - return array( - array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null), - array('username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null), - array('testrun', null, InputOption::VALUE_REQUIRED, 'Test the output without writing to the database or not.', null), - ); - } + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return array( + array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), + ); + } + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return array( + array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null), + array('username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null), + array('testrun', null, InputOption::VALUE_REQUIRED, 'Test the output without writing to the database or not.', null), + ); + } } diff --git a/app/Console/Commands/CreateAdmin.php b/app/Console/Commands/CreateAdmin.php index 1859638c34..89b564091e 100644 --- a/app/Console/Commands/CreateAdmin.php +++ b/app/Console/Commands/CreateAdmin.php @@ -46,32 +46,32 @@ class CreateAdmin extends Command $show_in_list = $this->argument('show_in_list'); if (($first_name=='') || ($last_name=='') || ($username=='') || ($email=='') || ($password=='')) { - $this->info('ERROR: All fields are required.'); + $this->info('ERROR: All fields are required.'); } else { - $user = new \App\Models\User; - $user->first_name = $first_name; - $user->last_name = $last_name; - $user->username = $username; - $user->email = $email; - $user->permissions = '{"admin":1,"user":1,"superuser":1,"reports.view":1, "licenses.keys":1}'; - $user->password = bcrypt($password); - $user->activated = 1; + $user = new \App\Models\User; + $user->first_name = $first_name; + $user->last_name = $last_name; + $user->username = $username; + $user->email = $email; + $user->permissions = '{"admin":1,"user":1,"superuser":1,"reports.view":1, "licenses.keys":1}'; + $user->password = bcrypt($password); + $user->activated = 1; - if ($show_in_list == 'false') { - $user->show_in_list = 0; - } - if ($user->save()) { - $this->info('New user created'); - $user->groups()->attach(1); - } else { - $this->info('Admin user was not created'); - $errors = $user->getErrors(); - - foreach ($errors->all() as $error) { - $this->info('ERROR:'. $error); + if ($show_in_list == 'false') { + $user->show_in_list = 0; } + if ($user->save()) { + $this->info('New user created'); + $user->groups()->attach(1); + } else { + $this->info('Admin user was not created'); + $errors = $user->getErrors(); - } + foreach ($errors->all() as $error) { + $this->info('ERROR:'. $error); + } + + } } } @@ -81,5 +81,5 @@ class CreateAdmin extends Command // return array( // array('username', InputArgument::REQUIRED, 'Username'), // ); - // } + // } } diff --git a/app/Console/Commands/DisableLDAP.php b/app/Console/Commands/DisableLDAP.php index 2e2196d0f1..8e9d8c8d69 100644 --- a/app/Console/Commands/DisableLDAP.php +++ b/app/Console/Commands/DisableLDAP.php @@ -5,7 +5,6 @@ namespace App\Console\Commands; use Illuminate\Console\Command; use App\Models\Setting; - class DisableLDAP extends Command { /** diff --git a/app/Console/Commands/LicenseImportCommand.php b/app/Console/Commands/LicenseImportCommand.php index 0171b6c9c8..ffa55ff007 100644 --- a/app/Console/Commands/LicenseImportCommand.php +++ b/app/Console/Commands/LicenseImportCommand.php @@ -10,375 +10,374 @@ use App\Models\Supplier; use App\Models\License; use App\Models\LicenseSeat; -class LicenseImportCommand extends Command { +class LicenseImportCommand extends Command +{ - /** - * The console command name. - * - * @var string - */ - protected $name = 'snipeit:license-import'; + /** + * The console command name. + * + * @var string + */ + protected $name = 'snipeit:license-import'; - /** - * The console command description. - * - * @var string - */ - protected $description = 'Import Licenses from CSV'; + /** + * The console command description. + * + * @var string + */ + protected $description = 'Import Licenses from CSV'; - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } + /** + * Create a new command instance. + * + * @return void + */ + public function __construct() + { + parent::__construct(); + } - /** - * Execute the console command. - * - * @return mixed - */ - public function fire() - { - $filename = $this->argument('filename'); + /** + * Execute the console command. + * + * @return mixed + */ + public function fire() + { + $filename = $this->argument('filename'); - if (!$this->option('testrun')=='true') { - $this->comment('======= Importing Licenses from '.$filename.' ========='); - } else { - $this->comment('====== TEST ONLY License Import for '.$filename.' ===='); - $this->comment('============== NO DATA WILL BE WRITTEN =============='); - } + if (!$this->option('testrun')=='true') { + $this->comment('======= Importing Licenses from '.$filename.' ========='); + } else { + $this->comment('====== TEST ONLY License Import for '.$filename.' ===='); + $this->comment('============== NO DATA WILL BE WRITTEN =============='); + } - if (! ini_get("auto_detect_line_endings")) { - ini_set("auto_detect_line_endings", '1'); - } + if (! ini_get("auto_detect_line_endings")) { + ini_set("auto_detect_line_endings", '1'); + } - $csv = Reader::createFromPath($this->argument('filename')); - $csv->setNewline("\r\n"); - $csv->setOffset(1); - $duplicates = ''; + $csv = Reader::createFromPath($this->argument('filename')); + $csv->setNewline("\r\n"); + $csv->setOffset(1); + $duplicates = ''; - // Loop through the records - $nbInsert = $csv->each(function ($row) use ($duplicates) { - $status_id = 1; + // Loop through the records + $nbInsert = $csv->each(function ($row) use ($duplicates) { + $status_id = 1; - // Let's just map some of these entries to more user friendly words + // Let's just map some of these entries to more user friendly words - if (array_key_exists('0',$row)) { - $user_name = trim($row[0]); - } else { - $user_name = ''; - } + if (array_key_exists('0', $row)) { + $user_name = trim($row[0]); + } else { + $user_name = ''; + } - if (array_key_exists('1',$row)) { - $user_email = trim($row[1]); - } else { - $user_email = ''; - } + if (array_key_exists('1', $row)) { + $user_email = trim($row[1]); + } else { + $user_email = ''; + } - if (array_key_exists('2',$row)) { - $user_username = trim($row[2]); - } else { - $user_username = ''; - } + if (array_key_exists('2', $row)) { + $user_username = trim($row[2]); + } else { + $user_username = ''; + } - if (array_key_exists('3',$row)) { - $user_license_name = trim($row[3]); - } else { - $user_license_name = ''; - } + if (array_key_exists('3', $row)) { + $user_license_name = trim($row[3]); + } else { + $user_license_name = ''; + } - if (array_key_exists('4',$row)) { - $user_license_serial = trim($row[4]); - } else { - $user_license_serial = ''; - } + if (array_key_exists('4', $row)) { + $user_license_serial = trim($row[4]); + } else { + $user_license_serial = ''; + } - if (array_key_exists('5',$row)) { - $user_licensed_to_name = trim($row[5]); - } else { - $user_licensed_to_name = ''; - } + if (array_key_exists('5', $row)) { + $user_licensed_to_name = trim($row[5]); + } else { + $user_licensed_to_name = ''; + } - if (array_key_exists('6',$row)) { - $user_licensed_to_email = trim($row[6]); - } else { - $user_licensed_to_email = ''; - } + if (array_key_exists('6', $row)) { + $user_licensed_to_email = trim($row[6]); + } else { + $user_licensed_to_email = ''; + } - if (array_key_exists('7',$row)) { - $user_license_seats = trim($row[7]); - } else { - $user_license_seats = ''; - } + if (array_key_exists('7', $row)) { + $user_license_seats = trim($row[7]); + } else { + $user_license_seats = ''; + } - if (array_key_exists('8',$row)) { - $user_license_reassignable = trim($row[8]); - if ($user_license_reassignable!='') { - if ((strtolower($user_license_reassignable)=='yes') || (strtolower($user_license_reassignable)=='true') || ($user_license_reassignable=='1')) { - $user_license_reassignable = 1; - } - } else { - $user_license_reassignable = 0; - } - } else { - $user_license_reassignable = 0; - } + if (array_key_exists('8', $row)) { + $user_license_reassignable = trim($row[8]); + if ($user_license_reassignable!='') { + if ((strtolower($user_license_reassignable)=='yes') || (strtolower($user_license_reassignable)=='true') || ($user_license_reassignable=='1')) { + $user_license_reassignable = 1; + } + } else { + $user_license_reassignable = 0; + } + } else { + $user_license_reassignable = 0; + } - if (array_key_exists('9',$row)) { - $user_license_supplier = trim($row[9]); - } else { - $user_license_supplier = ''; - } + if (array_key_exists('9', $row)) { + $user_license_supplier = trim($row[9]); + } else { + $user_license_supplier = ''; + } - if (array_key_exists('10',$row)) { - $user_license_maintained = trim($row[10]); + if (array_key_exists('10', $row)) { + $user_license_maintained = trim($row[10]); - if ($user_license_maintained!='') { - if ((strtolower($user_license_maintained)=='yes') || (strtolower($user_license_maintained)=='true') || ($user_license_maintained=='1')) { - $user_license_maintained = 1; - } - } else { - $user_license_maintained = 0; - } + if ($user_license_maintained!='') { + if ((strtolower($user_license_maintained)=='yes') || (strtolower($user_license_maintained)=='true') || ($user_license_maintained=='1')) { + $user_license_maintained = 1; + } + } else { + $user_license_maintained = 0; + } - } else { - $user_license_maintained = ''; - } + } else { + $user_license_maintained = ''; + } - if (array_key_exists('11',$row)) { - $user_license_notes = trim($row[11]); - } else { - $user_license_notes = ''; - } + if (array_key_exists('11', $row)) { + $user_license_notes = trim($row[11]); + } else { + $user_license_notes = ''; + } - if (array_key_exists('12',$row)) { - if ($row[12]!='') { - $user_license_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12])); - } else { - $user_license_purchase_date = ''; - } - } else { - $user_license_purchase_date = 0; - } + if (array_key_exists('12', $row)) { + if ($row[12]!='') { + $user_license_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12])); + } else { + $user_license_purchase_date = ''; + } + } else { + $user_license_purchase_date = 0; + } - // A number was given instead of a name - if (is_numeric($user_name)) { - $this->comment('User '.$user_name.' is not a name - assume this user already exists'); - $user_username = ''; - // No name was given + // A number was given instead of a name + if (is_numeric($user_name)) { + $this->comment('User '.$user_name.' is not a name - assume this user already exists'); + $user_username = ''; + // No name was given - } elseif ($user_name=='') { - $this->comment('No user data provided - skipping user creation, just adding license'); - $first_name = ''; - $last_name = ''; - $user_username = ''; + } elseif ($user_name=='') { + $this->comment('No user data provided - skipping user creation, just adding license'); + $first_name = ''; + $last_name = ''; + $user_username = ''; - } else { + } else { - $name = explode(" ", $user_name); - $first_name = $name[0]; - $email_last_name = ''; - $email_prefix = $first_name; + $name = explode(" ", $user_name); + $first_name = $name[0]; + $email_last_name = ''; + $email_prefix = $first_name; - if (!array_key_exists(1, $name)) { - $last_name=''; - $email_last_name = $last_name; - $email_prefix = $first_name; - } else { - $last_name = str_replace($first_name,'',$user_name); + if (!array_key_exists(1, $name)) { + $last_name=''; + $email_last_name = $last_name; + $email_prefix = $first_name; + } else { + $last_name = str_replace($first_name, '', $user_name); - if ($this->option('email_format')=='filastname') { - $email_last_name.=str_replace(' ','',$last_name); - $email_prefix = $first_name[0].$email_last_name; + if ($this->option('email_format')=='filastname') { + $email_last_name.=str_replace(' ', '', $last_name); + $email_prefix = $first_name[0].$email_last_name; - } elseif ($this->option('email_format')=='firstname.lastname') { - $email_last_name.=str_replace(' ','',$last_name); - $email_prefix = $first_name.'.'.$email_last_name; + } elseif ($this->option('email_format')=='firstname.lastname') { + $email_last_name.=str_replace(' ', '', $last_name); + $email_prefix = $first_name.'.'.$email_last_name; - } elseif ($this->option('email_format')=='firstname') { - $email_last_name.=str_replace(' ','',$last_name); - $email_prefix = $first_name; - } + } elseif ($this->option('email_format')=='firstname') { + $email_last_name.=str_replace(' ', '', $last_name); + $email_prefix = $first_name; + } - } + } - $user_username = $email_prefix; + $user_username = $email_prefix; - // Generate an email based on their name if no email address is given - if ($user_email=='') { - if ($first_name=='Unknown') { - $status_id = 7; - } - $email = strtolower($email_prefix).'@'.$this->option('domain'); - $user_email = str_replace("'",'',$email); - } - } + // Generate an email based on their name if no email address is given + if ($user_email=='') { + if ($first_name=='Unknown') { + $status_id = 7; + } + $email = strtolower($email_prefix).'@'.$this->option('domain'); + $user_email = str_replace("'", '', $email); + } + } - $this->comment('Full Name: '.$user_name); - $this->comment('First Name: '.$first_name); - $this->comment('Last Name: '.$last_name); - $this->comment('Username: '.$user_username); - $this->comment('Email: '.$user_email); - $this->comment('License Name: '.$user_license_name); - $this->comment('Serial No: '.$user_license_serial); - $this->comment('Licensed To Name: '.$user_licensed_to_name); - $this->comment('Licensed To Email: '.$user_licensed_to_email); - $this->comment('Seats: '.$user_license_seats); - $this->comment('Reassignable: '.$user_license_reassignable); - $this->comment('Supplier: '.$user_license_supplier); - $this->comment('Maintained: '.$user_license_maintained); - $this->comment('Notes: '.$user_license_notes); - $this->comment('Purchase Date: '.$user_license_purchase_date); + $this->comment('Full Name: '.$user_name); + $this->comment('First Name: '.$first_name); + $this->comment('Last Name: '.$last_name); + $this->comment('Username: '.$user_username); + $this->comment('Email: '.$user_email); + $this->comment('License Name: '.$user_license_name); + $this->comment('Serial No: '.$user_license_serial); + $this->comment('Licensed To Name: '.$user_licensed_to_name); + $this->comment('Licensed To Email: '.$user_licensed_to_email); + $this->comment('Seats: '.$user_license_seats); + $this->comment('Reassignable: '.$user_license_reassignable); + $this->comment('Supplier: '.$user_license_supplier); + $this->comment('Maintained: '.$user_license_maintained); + $this->comment('Notes: '.$user_license_notes); + $this->comment('Purchase Date: '.$user_license_purchase_date); - $this->comment('------------- Action Summary ----------------'); + $this->comment('------------- Action Summary ----------------'); - if ($user_username!='') { - if ($user = User::where('username', $user_username)->whereNotNull('username')->first()) { - $this->comment('User '.$user_username.' already exists'); - } else { + if ($user_username!='') { + if ($user = User::where('username', $user_username)->whereNotNull('username')->first()) { + $this->comment('User '.$user_username.' already exists'); + } else { - $user = new \App\Models\User; - $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); + $user = new \App\Models\User; + $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); - $user->first_name = $first_name; - $user->last_name = $last_name; - $user->username = $user_username; - $user->email = $user_email; - $user->permissions = '{user":1}'; - $user->password = bcrypt($password); - $user->activated = 1; - if ($user->save()) { - $this->comment('User '.$first_name.' created'); - } else { - $this->error('ERROR CREATING User '.$first_name.' '.$last_name); - $this->error($user->getErrors()); - } + $user->first_name = $first_name; + $user->last_name = $last_name; + $user->username = $user_username; + $user->email = $user_email; + $user->permissions = '{user":1}'; + $user->password = bcrypt($password); + $user->activated = 1; + if ($user->save()) { + $this->comment('User '.$first_name.' created'); + } else { + $this->error('ERROR CREATING User '.$first_name.' '.$last_name); + $this->error($user->getErrors()); + } - $this->comment('User '.$first_name.' created'); - } - } else { - $user = new User; - $user->user_id = null; - } + $this->comment('User '.$first_name.' created'); + } + } else { + $user = new User; + $user->user_id = null; + } - // Check for the supplier match and create it if it doesn't exist - if ($supplier = Supplier::where('name', $user_license_supplier)->first()) { - $this->comment('Supplier '.$user_license_supplier.' already exists'); - } else { - $supplier = new Supplier(); - $supplier->name = e($user_license_supplier); - $supplier->user_id = 1; + // Check for the supplier match and create it if it doesn't exist + if ($supplier = Supplier::where('name', $user_license_supplier)->first()) { + $this->comment('Supplier '.$user_license_supplier.' already exists'); + } else { + $supplier = new Supplier(); + $supplier->name = e($user_license_supplier); + $supplier->user_id = 1; - if ($supplier->save()) { - $this->comment('Supplier '.$user_license_supplier.' was created'); - } else { - $this->comment('Something went wrong! Supplier '.$user_license_supplier.' was NOT created'); - } + if ($supplier->save()) { + $this->comment('Supplier '.$user_license_supplier.' was created'); + } else { + $this->comment('Something went wrong! Supplier '.$user_license_supplier.' was NOT created'); + } - } + } - // Add the license - $license = new License(); - $license->name = e($user_license_name); - if ($user_license_purchase_date!='') { - $license->purchase_date = $user_license_purchase_date; - } else { - $license->purchase_date = null; - } - $license->serial = e($user_license_serial); - $license->seats = e($user_license_seats); - $license->supplier_id = $supplier->id; - $license->user_id = 1; - if ($user_license_purchase_date!='') { - $license->purchase_date = $user_license_purchase_date; - } else { - $license->purchase_date = null; - } - $license->license_name = $user_licensed_to_name; - $license->license_email = $user_licensed_to_email; - $license->notes = e($user_license_notes); + // Add the license + $license = new License(); + $license->name = e($user_license_name); + if ($user_license_purchase_date!='') { + $license->purchase_date = $user_license_purchase_date; + } else { + $license->purchase_date = null; + } + $license->serial = e($user_license_serial); + $license->seats = e($user_license_seats); + $license->supplier_id = $supplier->id; + $license->user_id = 1; + if ($user_license_purchase_date!='') { + $license->purchase_date = $user_license_purchase_date; + } else { + $license->purchase_date = null; + } + $license->license_name = $user_licensed_to_name; + $license->license_email = $user_licensed_to_email; + $license->notes = e($user_license_notes); - if ($license->save()) { - $this->comment('License '.$user_license_name.' with serial number '.$user_license_serial.' was created'); + if ($license->save()) { + $this->comment('License '.$user_license_name.' with serial number '.$user_license_serial.' was created'); - $license_seat_created = 0; + $license_seat_created = 0; - for ($x = 0; $x < $user_license_seats; $x++) { - // Create the license seat entries - $license_seat = new LicenseSeat(); - $license_seat->license_id = $license->id; + for ($x = 0; $x < $user_license_seats; $x++) { + // Create the license seat entries + $license_seat = new LicenseSeat(); + $license_seat->license_id = $license->id; - // Only assign the first seat to the user - if ($x==0) { - $license_seat->assigned_to = $user->id; - } else { - $license_seat->assigned_to = null; - } + // Only assign the first seat to the user + if ($x==0) { + $license_seat->assigned_to = $user->id; + } else { + $license_seat->assigned_to = null; + } - if ($license_seat->save()) { - $license_seat_created++; - } - } + if ($license_seat->save()) { + $license_seat_created++; + } + } - if ($license_seat_created > 0) { - $this->comment($license_seat_created.' seats were created'); - } else { - $this->comment('Something went wrong! NO seats for '.$user_license_name.' were created'); - } + if ($license_seat_created > 0) { + $this->comment($license_seat_created.' seats were created'); + } else { + $this->comment('Something went wrong! NO seats for '.$user_license_name.' were created'); + } } else { - $this->comment('Something went wrong! License '.$user_license_name.' was NOT created'); - } + $this->comment('Something went wrong! License '.$user_license_name.' was NOT created'); + } - $this->comment('====================================='); + $this->comment('====================================='); - return true; + return true; - }); + }); - } + } - /** - * Get the console command arguments. - * - * @return array - */ - protected function getArguments() - { - return array( - array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), - ); - } - - - /** - * Get the console command options. - * - * @return array - */ - protected function getOptions() - { - return array( - array('domain', null, InputOption::VALUE_REQUIRED, 'Email domain for generated email addresses.', null), - array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null), - array('testrun', null, InputOption::VALUE_REQUIRED, 'Test the output without writing to the database or not.', null), - ); - } + /** + * Get the console command arguments. + * + * @return array + */ + protected function getArguments() + { + return array( + array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), + ); + } + /** + * Get the console command options. + * + * @return array + */ + protected function getOptions() + { + return array( + array('domain', null, InputOption::VALUE_REQUIRED, 'Email domain for generated email addresses.', null), + array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null), + array('testrun', null, InputOption::VALUE_REQUIRED, 'Test the output without writing to the database or not.', null), + ); + } } diff --git a/app/Console/Commands/ObjectImportCommand.php b/app/Console/Commands/ObjectImportCommand.php index 06360fa8f6..3e1778dadb 100644 --- a/app/Console/Commands/ObjectImportCommand.php +++ b/app/Console/Commands/ObjectImportCommand.php @@ -27,657 +27,662 @@ ini_set('memory_limit', '500M'); /** * Class ObjectImportCommand */ -class ObjectImportCommand extends Command { +class ObjectImportCommand extends Command +{ - /** - * The console command name. - * - * @var string - */ - protected $name = 'snipeit:import'; - - /** - * The console command description. - * - * @var string - */ - protected $description = 'Import Items from CSV'; - - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } - - /** - * Execute the console command. - * - * @return mixed - */ - public function fire() - { - $filename = $this->argument('filename'); - - - if(!$this->option('web-importer')) { - $logFile = $this->option('logfile'); - \Log::useFiles($logFile); - if ($this->option('testrun')) { - $this->comment('====== TEST ONLY Asset Import for '.$filename.' ===='); - $this->comment('============== NO DATA WILL BE WRITTEN =============='); - } else { - - $this->comment('======= Importing Assets from '.$filename.' ========='); - } - } - - if (! ini_get("auto_detect_line_endings")) { - ini_set("auto_detect_line_endings", '1'); - } - - $csv = Reader::createFromPath($this->argument('filename')); - $csv->setNewline("\r\n"); - $results = $csv->fetchAssoc(); - $newarray = null; - - foreach ($results as $index => $arraytoNormalize) - { - $internalnewarray = array_change_key_case($arraytoNormalize); - $newarray[$index] = $internalnewarray; - } - - - - $this->locations = Location::All(['name', 'id']); - $this->categories = Category::All(['name', 'category_type', 'id']); - $this->manufacturers = Manufacturer::All(['name', 'id']); - $this->asset_models = AssetModel::All(['name','modelno','category_id','manufacturer_id', 'id']); - $this->companies = Company::All(['name', 'id']); - $this->status_labels = Statuslabel::All(['name', 'id']); - $this->suppliers = Supplier::All(['name', 'id']); - $this->assets = Asset::all(['asset_tag']); - $this->accessories = Accessory::All(['name']); - $this->consumables = Consumable::All(['name']); - $this->customfields = CustomField::All(['name']); - $bar = null; - if(!$this->option('web-importer')) { - $bar = $this->output->createProgressBar(count($newarray)); - } - // Loop through the records - DB::transaction(function() use (&$newarray, $bar){ - Model::unguard(); - $item_type = strtolower($this->option('item-type')); - - - - foreach( $newarray as $row ) { - - // Let's just map some of these entries to more user friendly words - - // Fetch general items here, fetch item type specific items in respective methods - /** @var Asset, License, Accessory, or Consumable $item_type */ - - $item_category = $this->array_smart_fetch($row, "category"); - $item_company_name = $this->array_smart_fetch($row, "company"); - $item_location = $this->array_smart_fetch($row, "location"); - - $item_status_name = $this->array_smart_fetch($row, "status"); - - $item["item_name"] = $this->array_smart_fetch($row, "item name"); - if ($this->array_smart_fetch($row, "purchase date")!='') { - $item["purchase_date"] = date("Y-m-d 00:00:01", strtotime($this->array_smart_fetch($row, "purchase date"))); - } else { - $item["purchase_date"] = null; - } - - $item["purchase_cost"] = $this->array_smart_fetch($row, "purchase cost"); - $item["order_number"] = $this->array_smart_fetch($row, "order number"); - $item["notes"] = $this->array_smart_fetch($row, "notes"); - $item["quantity"] = $this->array_smart_fetch($row, "quantity"); - $item["requestable"] = $this->array_smart_fetch($row, "requestable"); - $item["asset_tag"] = $this->array_smart_fetch($row, "asset tag"); - - - $this->current_assetId = $item["item_name"]; - if($item["asset_tag"] != '') { - $this->current_assetId = $item["asset_tag"]; - } - $this->log('Category: ' . $item_category); - $this->log('Location: ' . $item_location); - $this->log('Purchase Date: ' . $item["purchase_date"]); - $this->log('Purchase Cost: ' . $item["purchase_cost"]); - $this->log('Company Name: ' . $item_company_name); - $this->log('Status: ' . $item_status_name); - - $item["user"] = $this->createOrFetchUser($row); - - $item["location"] = $this->createOrFetchLocation($item_location); - $item["category"] = $this->createOrFetchCategory($item_category, $item_type); - $item["manufacturer"] = $this->createOrFetchManufacturer($row); - $item["company"] = $this->createOrFetchCompany($item_company_name); - - $item["status_label"] = $this->createOrFetchStatusLabel($item_status_name); - - switch ($item_type) { - case "asset": - // ----------------------------- - // CUSTOM FIELDS - // ----------------------------- - // Loop through custom fields in the database and see if we have any matches in the CSV - foreach ($this->customfields as $customfield) { - if ($item['custom_fields'][$customfield->db_column_name()] = $this->array_smart_custom_field_fetch($row, $customfield)) { - $this->log('Custom Field '. $customfield->name.': '.$this->array_smart_custom_field_fetch($row, $customfield)); - } - - } - - $this->createAssetIfNotExists($row, $item); - break; - case "accessory": - $this->createAccessoryIfNotExists($item); - break; - case 'consumable': - $this->createConsumableIfNotExists($item); - break; - } - - if(!$this->option('web-importer')) { - $bar->advance(); - } - $this->log('------------- Action Summary ----------------'); - - } - }); - if(!$this->option('web-importer')) { - $bar->finish(); - } - - - $this->log('====================================='); - if(!$this->option('web-importer')) - { - if(!empty($this->errors)) { - $this->comment("The following Errors were encountered."); - foreach($this->errors as $asset => $error) - { - $this->comment('Error: Item: ' . $asset . 'failed validation: ' . json_encode($error)); - } - } else { - $this->comment("All Items imported successfully!"); - } - } else { - if(empty($this->errors)) - return 0; - else { - $this->comment(json_encode($this->errors)); //Send a big string to the - return 1; - } - } - $this->comment(""); - - return 2; - } - // Tracks the current item for error messages - private $current_assetId; - - // An array of errors encountered while parsing - private $errors; - - public function jsonError($field, $errorString) - { - $this->errors[$this->current_assetId][$field] = $errorString; - if($this->option('verbose')) - parent::error($field . $errorString); - } - - /** - * Log a message to file, configurable by the --log-file parameter. - * 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 - */ - private function log($string, $level = 'info') - { - if($this->option('web-importer')) - return; - if($level === 'warning') - { - \Log::warning($string); - $this->comment($string); - } - else { - \Log::Info($string); - if($this->option('verbose')) { - $this->comment($string); - } - } - } - - /** - * Check to see if the given key exists in the array, and trim excess white space before returning it - * - * @author Daniel Melzter - * @since 3.0 - * @param $array array - * @param $key string - * @param $default string - * @return string - */ - public function array_smart_fetch(Array $array, $key, $default = '') { - return array_key_exists($key,$array) ? e(trim($array[ $key ])) : $default; - } - - - /** - * Figure out the fieldname of the custom field - * - * @author A. Gianotto - * @since 3.0 - * @param $array array - * @return string - */ - public function array_smart_custom_field_fetch(Array $array, $key) { - $index_name = strtolower($key->name); - return array_key_exists($index_name,$array) ? e(trim($array[$index_name])) : ''; - } - - - - private $asset_models; /** - * Select the asset model if it exists, otherwise create it. - * - * @author Daniel Melzter - * @since 3.0 + * The console command name. + * + * @var string + */ + protected $name = 'snipeit:import'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Import Items from CSV'; + + /** + * Create a new command instance. + * + * @return void + */ + public function __construct() + { + parent::__construct(); + } + + /** + * Execute the console command. + * + * @return mixed + */ + public function fire() + { + $filename = $this->argument('filename'); + + + if (!$this->option('web-importer')) { + $logFile = $this->option('logfile'); + \Log::useFiles($logFile); + if ($this->option('testrun')) { + $this->comment('====== TEST ONLY Asset Import for '.$filename.' ===='); + $this->comment('============== NO DATA WILL BE WRITTEN =============='); + } else { + + $this->comment('======= Importing Assets from '.$filename.' ========='); + } + } + + if (! ini_get("auto_detect_line_endings")) { + ini_set("auto_detect_line_endings", '1'); + } + + $csv = Reader::createFromPath($this->argument('filename')); + $csv->setNewline("\r\n"); + $results = $csv->fetchAssoc(); + $newarray = null; + + foreach ($results as $index => $arraytoNormalize) { + $internalnewarray = array_change_key_case($arraytoNormalize); + $newarray[$index] = $internalnewarray; + } + + + + $this->locations = Location::All(['name', 'id']); + $this->categories = Category::All(['name', 'category_type', 'id']); + $this->manufacturers = Manufacturer::All(['name', 'id']); + $this->asset_models = AssetModel::All(['name','modelno','category_id','manufacturer_id', 'id']); + $this->companies = Company::All(['name', 'id']); + $this->status_labels = Statuslabel::All(['name', 'id']); + $this->suppliers = Supplier::All(['name', 'id']); + $this->assets = Asset::all(['asset_tag']); + $this->accessories = Accessory::All(['name']); + $this->consumables = Consumable::All(['name']); + $this->customfields = CustomField::All(['name']); + $bar = null; + if (!$this->option('web-importer')) { + $bar = $this->output->createProgressBar(count($newarray)); + } + // Loop through the records + DB::transaction(function () use (&$newarray, $bar) { + Model::unguard(); + $item_type = strtolower($this->option('item-type')); + + + + foreach ($newarray as $row) { + + // Let's just map some of these entries to more user friendly words + + // Fetch general items here, fetch item type specific items in respective methods + /** @var Asset, License, Accessory, or Consumable $item_type */ + + $item_category = $this->array_smart_fetch($row, "category"); + $item_company_name = $this->array_smart_fetch($row, "company"); + $item_location = $this->array_smart_fetch($row, "location"); + + $item_status_name = $this->array_smart_fetch($row, "status"); + + $item["item_name"] = $this->array_smart_fetch($row, "item name"); + if ($this->array_smart_fetch($row, "purchase date")!='') { + $item["purchase_date"] = date("Y-m-d 00:00:01", strtotime($this->array_smart_fetch($row, "purchase date"))); + } else { + $item["purchase_date"] = null; + } + + $item["purchase_cost"] = $this->array_smart_fetch($row, "purchase cost"); + $item["order_number"] = $this->array_smart_fetch($row, "order number"); + $item["notes"] = $this->array_smart_fetch($row, "notes"); + $item["quantity"] = $this->array_smart_fetch($row, "quantity"); + $item["requestable"] = $this->array_smart_fetch($row, "requestable"); + $item["asset_tag"] = $this->array_smart_fetch($row, "asset tag"); + + + $this->current_assetId = $item["item_name"]; + if ($item["asset_tag"] != '') { + $this->current_assetId = $item["asset_tag"]; + } + $this->log('Category: ' . $item_category); + $this->log('Location: ' . $item_location); + $this->log('Purchase Date: ' . $item["purchase_date"]); + $this->log('Purchase Cost: ' . $item["purchase_cost"]); + $this->log('Company Name: ' . $item_company_name); + $this->log('Status: ' . $item_status_name); + + $item["user"] = $this->createOrFetchUser($row); + + $item["location"] = $this->createOrFetchLocation($item_location); + $item["category"] = $this->createOrFetchCategory($item_category, $item_type); + $item["manufacturer"] = $this->createOrFetchManufacturer($row); + $item["company"] = $this->createOrFetchCompany($item_company_name); + + $item["status_label"] = $this->createOrFetchStatusLabel($item_status_name); + + switch ($item_type) { + case "asset": + // ----------------------------- + // CUSTOM FIELDS + // ----------------------------- + // Loop through custom fields in the database and see if we have any matches in the CSV + foreach ($this->customfields as $customfield) { + if ($item['custom_fields'][$customfield->db_column_name()] = $this->array_smart_custom_field_fetch($row, $customfield)) { + $this->log('Custom Field '. $customfield->name.': '.$this->array_smart_custom_field_fetch($row, $customfield)); + } + + } + + $this->createAssetIfNotExists($row, $item); + break; + case "accessory": + $this->createAccessoryIfNotExists($item); + break; + case 'consumable': + $this->createConsumableIfNotExists($item); + break; + } + + if (!$this->option('web-importer')) { + $bar->advance(); + } + $this->log('------------- Action Summary ----------------'); + + } + }); + if (!$this->option('web-importer')) { + $bar->finish(); + } + + + $this->log('====================================='); + if (!$this->option('web-importer')) { + if (!empty($this->errors)) { + $this->comment("The following Errors were encountered."); + foreach ($this->errors as $asset => $error) { + $this->comment('Error: Item: ' . $asset . 'failed validation: ' . json_encode($error)); + } + } else { + $this->comment("All Items imported successfully!"); + } + } else { + if (empty($this->errors)) { + return 0; + } else { + $this->comment(json_encode($this->errors)); //Send a big string to the + return 1; + } + } + $this->comment(""); + + return 2; + } + // Tracks the current item for error messages + private $current_assetId; + + // An array of errors encountered while parsing + private $errors; + + public function jsonError($field, $errorString) + { + $this->errors[$this->current_assetId][$field] = $errorString; + if ($this->option('verbose')) { + parent::error($field . $errorString); + } + } + + /** + * Log a message to file, configurable by the --log-file parameter. + * 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 + */ + private function log($string, $level = 'info') + { + if ($this->option('web-importer')) { + return; + } + if ($level === 'warning') { + \Log::warning($string); + $this->comment($string); + } else { + \Log::Info($string); + if ($this->option('verbose')) { + $this->comment($string); + } + } + } + + /** + * Check to see if the given key exists in the array, and trim excess white space before returning it + * + * @author Daniel Melzter + * @since 3.0 + * @param $array array + * @param $key string + * @param $default string + * @return string + */ + public function array_smart_fetch(array $array, $key, $default = '') + { + return array_key_exists($key, $array) ? e(trim($array[ $key ])) : $default; + } + + + /** + * Figure out the fieldname of the custom field + * + * @author A. Gianotto + * @since 3.0 + * @param $array array + * @return string + */ + public function array_smart_custom_field_fetch(array $array, $key) + { + $index_name = strtolower($key->name); + return array_key_exists($index_name, $array) ? e(trim($array[$index_name])) : ''; + } + + + + private $asset_models; + /** + * Select the asset model if it exists, otherwise create it. + * + * @author Daniel Melzter + * @since 3.0 * @param array * @param $category Category * @param $manufacturer Manufacturer * @return Model * @internal param $asset_modelno string */ - public function createOrFetchAssetModel(array $row, $category, $manufacturer) - { + public function createOrFetchAssetModel(array $row, $category, $manufacturer) + { - $asset_model_name = $this->array_smart_fetch($row, "model name"); - $asset_modelno = $this->array_smart_fetch($row, "model number"); - if(empty($asset_model_name)) - $asset_model_name='Unknown'; - if(empty($asset_modelno)) - $asset_modelno=''; - $this->log('Model Name: ' . $asset_model_name); - $this->log('Model No: ' . $asset_modelno); + $asset_model_name = $this->array_smart_fetch($row, "model name"); + $asset_modelno = $this->array_smart_fetch($row, "model number"); + if (empty($asset_model_name)) { + $asset_model_name='Unknown'; + } + if (empty($asset_modelno)) { + $asset_modelno=''; + } + $this->log('Model Name: ' . $asset_model_name); + $this->log('Model No: ' . $asset_modelno); - foreach ($this->asset_models as $tempmodel) { - if ((strcasecmp($tempmodel->name, $asset_model_name) == 0) - && $tempmodel->modelno == $asset_modelno - && $tempmodel->category_id == $category->id - && $tempmodel->manufacturer_id == $manufacturer->id ) - { - $this->log('A matching model ' . $asset_model_name . ' with model number ' . $asset_modelno . ' already exists'); - return $tempmodel; - } - } - $asset_model = new AssetModel(); - $asset_model->name = $asset_model_name; - $asset_model->manufacturer_id = $manufacturer->id; - $asset_model->modelno = $asset_modelno; - $asset_model->category_id = $category->id; - $asset_model->user_id = $this->option('user_id'); + foreach ($this->asset_models as $tempmodel) { + if ((strcasecmp($tempmodel->name, $asset_model_name) == 0) + && $tempmodel->modelno == $asset_modelno + && $tempmodel->category_id == $category->id + && $tempmodel->manufacturer_id == $manufacturer->id ) { + $this->log('A matching model ' . $asset_model_name . ' with model number ' . $asset_modelno . ' already exists'); + return $tempmodel; + } + } + $asset_model = new AssetModel(); + $asset_model->name = $asset_model_name; + $asset_model->manufacturer_id = $manufacturer->id; + $asset_model->modelno = $asset_modelno; + $asset_model->category_id = $category->id; + $asset_model->user_id = $this->option('user_id'); - if(!$this->option('testrun')) { - if ($asset_model->save()) { - $this->asset_models->add($asset_model); - $this->log('Asset Model ' . $asset_model_name . ' with model number ' . $asset_modelno . ' was created'); - return $asset_model; - } else { + if (!$this->option('testrun')) { + if ($asset_model->save()) { + $this->asset_models->add($asset_model); + $this->log('Asset Model ' . $asset_model_name . ' with model number ' . $asset_modelno . ' was created'); + return $asset_model; + } else { $this->jsonError('Asset Model', $asset_model->getErrors()); - return $asset_model; - } - } else { - $this->asset_models->add($asset_model); - return $asset_model; - } + return $asset_model; + } + } else { + $this->asset_models->add($asset_model); + return $asset_model; + } - } + } - private $categories; + private $categories; - /** - * Finds a category with the same name and item type in the database, otherwise creates it - * - * @author Daniel Melzter - * @since 3.0 - * @param $asset_category string - * @param $item_type string - * @return Category - */ - public function createOrFetchCategory($asset_category, $item_type) - { - if (empty($asset_category)) - $asset_category = 'Unnamed Category'; + /** + * Finds a category with the same name and item type in the database, otherwise creates it + * + * @author Daniel Melzter + * @since 3.0 + * @param $asset_category string + * @param $item_type string + * @return Category + */ + public function createOrFetchCategory($asset_category, $item_type) + { + if (empty($asset_category)) { + $asset_category = 'Unnamed Category'; + } - foreach($this->categories as $tempcategory) { - if( (strcasecmp($tempcategory->name, $asset_category) == 0) && $tempcategory->category_type === $item_type) { - $this->log('Category ' . $asset_category . ' already exists'); - return $tempcategory; - } - } + foreach ($this->categories as $tempcategory) { + if ((strcasecmp($tempcategory->name, $asset_category) == 0) && $tempcategory->category_type === $item_type) { + $this->log('Category ' . $asset_category . ' already exists'); + return $tempcategory; + } + } - $category = new Category(); + $category = new Category(); - $category->name = $asset_category; - $category->category_type = $item_type; - $category->user_id = $this->option('user_id'); + $category->name = $asset_category; + $category->category_type = $item_type; + $category->user_id = $this->option('user_id'); - if(!$this->option('testrun')) { - if ($category->save()) { - $this->categories->add($category); - $this->log('Category ' . $asset_category . ' was created'); - return $category; - } else { + if (!$this->option('testrun')) { + if ($category->save()) { + $this->categories->add($category); + $this->log('Category ' . $asset_category . ' was created'); + return $category; + } else { $this->jsonError('Category', $category->getErrors()); return $category; - } - } else { - $this->categories->add($category); - return $category; - } + } + } else { + $this->categories->add($category); + return $category; + } - } + } - private $companies; + private $companies; - /** - * Fetch an existing company, or create new if it doesn't exist - * - * @author Daniel Melzter - * @since 3.0 - * @param $asset_company_name string - * @return Company - */ - public function createOrFetchCompany($asset_company_name) - { - foreach ($this->companies as $tempcompany) { - if (strcasecmp($tempcompany->name, $asset_company_name) == 0) { - $this->log('A matching Company ' . $asset_company_name . ' already exists'); - return $tempcompany; - } - } + /** + * Fetch an existing company, or create new if it doesn't exist + * + * @author Daniel Melzter + * @since 3.0 + * @param $asset_company_name string + * @return Company + */ + public function createOrFetchCompany($asset_company_name) + { + foreach ($this->companies as $tempcompany) { + if (strcasecmp($tempcompany->name, $asset_company_name) == 0) { + $this->log('A matching Company ' . $asset_company_name . ' already exists'); + return $tempcompany; + } + } - $company = new Company(); - $company->name = $asset_company_name; + $company = new Company(); + $company->name = $asset_company_name; - if(!$this->option('testrun')) { - if ($company->save()) { - $this->companies->add($company); - $this->log('Company ' . $asset_company_name . ' was created'); - return $company; - } else { + if (!$this->option('testrun')) { + if ($company->save()) { + $this->companies->add($company); + $this->log('Company ' . $asset_company_name . ' was created'); + return $company; + } else { $this->log('Company', $company->getErrors()); - } - } else { - $this->companies->add($company); - return $company; - } - } - private $status_labels; - /** - * Fetch the existing status label or create new if it doesn't exist. - * - * @author Daniel Melzter - * @since 3.0 - * @param string $asset_statuslabel_name - * @return Company - */ - public function createOrFetchStatusLabel($asset_statuslabel_name) - { - if(empty($asset_statuslabel_name)) - return; - foreach ($this->status_labels as $tempstatus) { - if (strcasecmp($tempstatus->name, $asset_statuslabel_name) == 0 ) { - $this->log('A matching Status ' . $asset_statuslabel_name . ' already exists'); - return $tempstatus; - } - } - $status = new Statuslabel(); - $status->name = $asset_statuslabel_name; + } + } else { + $this->companies->add($company); + return $company; + } + } + private $status_labels; + /** + * Fetch the existing status label or create new if it doesn't exist. + * + * @author Daniel Melzter + * @since 3.0 + * @param string $asset_statuslabel_name + * @return Company + */ + public function createOrFetchStatusLabel($asset_statuslabel_name) + { + if (empty($asset_statuslabel_name)) { + return; + } + foreach ($this->status_labels as $tempstatus) { + if (strcasecmp($tempstatus->name, $asset_statuslabel_name) == 0) { + $this->log('A matching Status ' . $asset_statuslabel_name . ' already exists'); + return $tempstatus; + } + } + $status = new Statuslabel(); + $status->name = $asset_statuslabel_name; - if(!$this->option('testrun')) { - if ($status->save()) { - $this->status_labels->add($status); - $this->log('Status ' . $asset_statuslabel_name . ' was created'); - return $status; - } else { + if (!$this->option('testrun')) { + if ($status->save()) { + $this->status_labels->add($status); + $this->log('Status ' . $asset_statuslabel_name . ' was created'); + return $status; + } else { $this->jsonError('Status', $status->getErrors()); - return $status; - } - } else { - $this->status_labels->add($status); - return $status; - } - } + return $status; + } + } else { + $this->status_labels->add($status); + return $status; + } + } - private $manufacturers; + private $manufacturers; - /** - * Finds a manufacturer with matching name, otherwise create it. - * - * @author Daniel Melzter - * @since 3.0 - * @param $row array - * @return Manufacturer - * @internal param $asset_mfgr string - */ + /** + * Finds a manufacturer with matching name, otherwise create it. + * + * @author Daniel Melzter + * @since 3.0 + * @param $row array + * @return Manufacturer + * @internal param $asset_mfgr string + */ - public function createOrFetchManufacturer(array $row) - { - $asset_mfgr = $this->array_smart_fetch($row, "manufacturer"); + public function createOrFetchManufacturer(array $row) + { + $asset_mfgr = $this->array_smart_fetch($row, "manufacturer"); - if(empty($asset_mfgr)) { - $asset_mfgr='Unknown'; - } - $this->log('Manufacturer ID: ' . $asset_mfgr); + if (empty($asset_mfgr)) { + $asset_mfgr='Unknown'; + } + $this->log('Manufacturer ID: ' . $asset_mfgr); - foreach ($this->manufacturers as $tempmanufacturer) { - if (strcasecmp($tempmanufacturer->name, $asset_mfgr) == 0 ) { - $this->log('Manufacturer ' . $asset_mfgr . ' already exists') ; - return $tempmanufacturer; - } - } + foreach ($this->manufacturers as $tempmanufacturer) { + if (strcasecmp($tempmanufacturer->name, $asset_mfgr) == 0) { + $this->log('Manufacturer ' . $asset_mfgr . ' already exists') ; + return $tempmanufacturer; + } + } - //Otherwise create a manufacturer. + //Otherwise create a manufacturer. - $manufacturer = new Manufacturer(); - $manufacturer->name = $asset_mfgr; - $manufacturer->user_id = $this->option('user_id'); + $manufacturer = new Manufacturer(); + $manufacturer->name = $asset_mfgr; + $manufacturer->user_id = $this->option('user_id'); - if (!$this->option('testrun')) { - if ($manufacturer->save()) { - $this->manufacturers->add($manufacturer); - $this->log('Manufacturer ' . $manufacturer->name . ' was created'); - return $manufacturer; - } else { + if (!$this->option('testrun')) { + if ($manufacturer->save()) { + $this->manufacturers->add($manufacturer); + $this->log('Manufacturer ' . $manufacturer->name . ' was created'); + return $manufacturer; + } else { $this->jsonError('Manufacturer', $manufacturer->getErrors()); - return $manufacturer; - } + return $manufacturer; + } - } else { - $this->manufacturers->add($manufacturer); - return $manufacturer; - } - } + } else { + $this->manufacturers->add($manufacturer); + return $manufacturer; + } + } - /** - * @var + /** + * @var */ - private $locations; - /** - * Checks the DB to see if a location with the same name exists, otherwise create it - * - * @author Daniel Melzter - * @since 3.0 - * @param $asset_location string - * @return Location - */ - public function createOrFetchLocation($asset_location) - { - foreach($this->locations as $templocation) { - if( strcasecmp($templocation->name, $asset_location) == 0 ) { - $this->log('Location ' . $asset_location . ' already exists'); - return $templocation; - } - } - // No matching locations in the collection, create a new one. - $location = new Location(); - - if (!empty($asset_location)) { - $location->name = $asset_location; - $location->address = ''; - $location->city = ''; - $location->state = ''; - $location->country = ''; - $location->user_id = $this->option('user_id'); - - if (!$this->option('testrun')) { - if ($location->save()) { - $this->locations->add($location); - $this->log('Location ' . $asset_location . ' was created'); - return $location; - } else { - $this->log('Location', $location->getErrors()) ; - return $location; - } - } else { - $this->locations->add($location); - return $location; - } - } else { - $this->log('No location given, so none created.'); - return $location; - } - - } - - private $suppliers; - - /** - * Fetch an existing supplier or create new if it doesn't exist - * - * @author Daniel Melzter - * @since 3.0 - * @param $row array - * @return Supplier + private $locations; + /** + * Checks the DB to see if a location with the same name exists, otherwise create it + * + * @author Daniel Melzter + * @since 3.0 + * @param $asset_location string + * @return Location */ - public function createOrFetchSupplier(array $row) - { - $supplier_name = $this->array_smart_fetch($row, "supplier"); - if(empty($supplier_name)) - $supplier_name='Unknown'; - foreach ($this->suppliers as $tempsupplier) { - if (strcasecmp($tempsupplier->name, $supplier_name) == 0) { - $this->log('A matching Company ' . $supplier_name . ' already exists'); - return $tempsupplier; - } - } + public function createOrFetchLocation($asset_location) + { + foreach ($this->locations as $templocation) { + if (strcasecmp($templocation->name, $asset_location) == 0) { + $this->log('Location ' . $asset_location . ' already exists'); + return $templocation; + } + } + // No matching locations in the collection, create a new one. + $location = new Location(); - $supplier = new Supplier(); - $supplier->name = $supplier_name; - $supplier->user_id = $this->option('user_id'); + if (!empty($asset_location)) { + $location->name = $asset_location; + $location->address = ''; + $location->city = ''; + $location->state = ''; + $location->country = ''; + $location->user_id = $this->option('user_id'); - if(!$this->option('testrun')) { - if ($supplier->save()) { - $this->suppliers->add($supplier); - $this->log('Supplier ' . $supplier_name . ' was created'); - return $supplier; - } else { + if (!$this->option('testrun')) { + if ($location->save()) { + $this->locations->add($location); + $this->log('Location ' . $asset_location . ' was created'); + return $location; + } else { + $this->log('Location', $location->getErrors()) ; + return $location; + } + } else { + $this->locations->add($location); + return $location; + } + } else { + $this->log('No location given, so none created.'); + return $location; + } + + } + + private $suppliers; + + /** + * Fetch an existing supplier or create new if it doesn't exist + * + * @author Daniel Melzter + * @since 3.0 + * @param $row array + * @return Supplier + */ + public function createOrFetchSupplier(array $row) + { + $supplier_name = $this->array_smart_fetch($row, "supplier"); + if (empty($supplier_name)) { + $supplier_name='Unknown'; + } + foreach ($this->suppliers as $tempsupplier) { + if (strcasecmp($tempsupplier->name, $supplier_name) == 0) { + $this->log('A matching Company ' . $supplier_name . ' already exists'); + return $tempsupplier; + } + } + + $supplier = new Supplier(); + $supplier->name = $supplier_name; + $supplier->user_id = $this->option('user_id'); + + if (!$this->option('testrun')) { + if ($supplier->save()) { + $this->suppliers->add($supplier); + $this->log('Supplier ' . $supplier_name . ' was created'); + return $supplier; + } else { $this->log('Supplier', $supplier->getErrors()); return $supplier; - } - } else { - $this->suppliers->add($supplier); - return $supplier; - } - } + } + } else { + $this->suppliers->add($supplier); + return $supplier; + } + } - /** - * Finds the user matching given data, or creates a new one if there is no match - * - * @author Daniel Melzter - * @since 3.0 - * @param $row array - * @return User Model w/ matching name - * @internal param string $user_username Username extracted from CSV - * @internal param string $user_email Email extracted from CSV - * @internal param string $first_name - * @internal param string $last_name - */ - public function createOrFetchUser($row) - { - $user_name = $this->array_smart_fetch($row, "name"); - $user_email = $this->array_smart_fetch($row, "email"); - $user_username = $this->array_smart_fetch($row, "username"); + /** + * Finds the user matching given data, or creates a new one if there is no match + * + * @author Daniel Melzter + * @since 3.0 + * @param $row array + * @return User Model w/ matching name + * @internal param string $user_username Username extracted from CSV + * @internal param string $user_email Email extracted from CSV + * @internal param string $first_name + * @internal param string $last_name + */ + public function createOrFetchUser($row) + { + $user_name = $this->array_smart_fetch($row, "name"); + $user_email = $this->array_smart_fetch($row, "email"); + $user_username = $this->array_smart_fetch($row, "username"); - // A number was given instead of a name - if (is_numeric($user_name)) { - $this->log('User '.$user_name.' is not a name - assume this user already exists'); - $user_username = ''; + // A number was given instead of a name + if (is_numeric($user_name)) { + $this->log('User '.$user_name.' is not a name - assume this user already exists'); + $user_username = ''; $first_name = ''; - $last_name = ''; + $last_name = ''; - // No name was given - } elseif (empty($user_name)) { - $this->log('No user data provided - skipping user creation, just adding asset'); - $first_name = ''; - $last_name = ''; - //$user_username = ''; - } else { - $user_email_array = User::generateFormattedNameFromFullName(Setting::getSettings()->email_format, $user_name); - $first_name = $user_email_array['first_name']; - $last_name = $user_email_array['last_name']; + // No name was given + } elseif (empty($user_name)) { + $this->log('No user data provided - skipping user creation, just adding asset'); + $first_name = ''; + $last_name = ''; + //$user_username = ''; + } else { + $user_email_array = User::generateFormattedNameFromFullName(Setting::getSettings()->email_format, $user_name); + $first_name = $user_email_array['first_name']; + $last_name = $user_email_array['last_name']; - if ($user_email=='') { - $user_email = $user_email_array['username'].'@'.Setting::getSettings()->email_domain; - } + if ($user_email=='') { + $user_email = $user_email_array['username'].'@'.Setting::getSettings()->email_domain; + } - if ($user_username=='') { - if ($this->option('username_format')=='email') { - $user_username = $user_email; - } else { - $user_name_array = User::generateFormattedNameFromFullName(Setting::getSettings()->username_format, $user_name); - $user_username = $user_name_array['username']; - } + if ($user_username=='') { + if ($this->option('username_format')=='email') { + $user_username = $user_email; + } else { + $user_name_array = User::generateFormattedNameFromFullName(Setting::getSettings()->username_format, $user_name); + $user_username = $user_name_array['username']; + } - } + } - } - $this->log("--- User Data ---"); - $this->log('Full Name: ' . $user_name); - $this->log('First Name: ' . $first_name); - $this->log('Last Name: ' . $last_name); - $this->log('Username: ' . $user_username); - $this->log('Email: ' . $user_email); - $this->log('--- End User Data ---'); + } + $this->log("--- User Data ---"); + $this->log('Full Name: ' . $user_name); + $this->log('First Name: ' . $first_name); + $this->log('Last Name: ' . $last_name); + $this->log('Username: ' . $user_username); + $this->log('Email: ' . $user_email); + $this->log('--- End User Data ---'); - if($this->option('testrun')) + if ($this->option('testrun')) { return new User; + } - if (!empty($user_username)) { - if ($user = User::MatchEmailOrUsername($user_username, $user_email) - ->whereNotNull('username')->first()) { + if (!empty($user_username)) { + if ($user = User::MatchEmailOrUsername($user_username, $user_email) + ->whereNotNull('username')->first()) { - $this->log('User '.$user_username.' already exists'); - } else if(( $first_name != '') && ($last_name != '') && ($user_username != '')) { + $this->log('User '.$user_username.' already exists'); + } elseif (( $first_name != '') && ($last_name != '') && ($user_username != '')) { $user = new \App\Models\User; $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); @@ -693,278 +698,283 @@ class ObjectImportCommand extends Command { $this->jsonError('User', $user->getErrors()); } - } else { - $user = new User; - } - } else { - $user = new User; - } - return $user; - } + } else { + $user = new User; + } + } else { + $user = new User; + } + return $user; + } - private $assets; + private $assets; - /** - * Create the asset if it doesn't exist. - * - * @author Daniel Melzter - * @since 3.0 - * @param array $row - * @param array $item - */ - public function createAssetIfNotExists(array $row, array $item ) - { + /** + * Create the asset if it doesn't exist. + * + * @author Daniel Melzter + * @since 3.0 + * @param array $row + * @param array $item + */ + public function createAssetIfNotExists(array $row, array $item) + { $asset_serial = $this->array_smart_fetch($row, "serial number"); $asset_image = $this->array_smart_fetch($row, "image"); $asset_warranty_months = intval($this->array_smart_fetch($row, "warranty months")); - if(empty($asset_warranty_months)) { - $asset_warranty_months = null; + if (empty($asset_warranty_months)) { + $asset_warranty_months = null; } // Check for the asset model match and create it if it doesn't exist $asset_model = $this->createOrFetchAssetModel($row, $item["category"], $item["manufacturer"]); - $supplier = $this->createOrFetchSupplier($row); + $supplier = $this->createOrFetchSupplier($row); $this->log('Serial No: '.$asset_serial); $this->log('Asset Tag: '.$item['asset_tag']); $this->log('Notes: '.$item["notes"]); $this->log('Warranty Months: ' . $asset_warranty_months); - foreach ($this->assets as $tempasset) { - if (strcasecmp($tempasset->asset_tag, $item['asset_tag'] ) == 0 ) { - $this->log('A matching Asset ' . $item['asset_tag'] . ' already exists'); - return; - } - } + foreach ($this->assets as $tempasset) { + if (strcasecmp($tempasset->asset_tag, $item['asset_tag']) == 0) { + $this->log('A matching Asset ' . $item['asset_tag'] . ' already exists'); + return; + } + } - if($item["status_label"]) { - $status_id = $item["status_label"]->id; + if ($item["status_label"]) { + $status_id = $item["status_label"]->id; - } else { - // FIXME: We're already grabbing the list of statuses, we should probably not hardcode here - $this->log("No status field found, defaulting to id 1."); - $status_id = 1; - } + } else { + // FIXME: We're already grabbing the list of statuses, we should probably not hardcode here + $this->log("No status field found, defaulting to id 1."); + $status_id = 1; + } - $asset = new Asset(); - $asset->name = $item["item_name"]; - if ($item["purchase_date"] != '') { - $asset->purchase_date = $item["purchase_date"]; - } else { - $asset->purchase_date = null; - } + $asset = new Asset(); + $asset->name = $item["item_name"]; + if ($item["purchase_date"] != '') { + $asset->purchase_date = $item["purchase_date"]; + } else { + $asset->purchase_date = null; + } - if( array_key_exists('custom_fields', $item)) { - foreach ($item['custom_fields'] as $custom_field => $val) { - $asset->{$custom_field} = $val; - } - } + if (array_key_exists('custom_fields', $item)) { + foreach ($item['custom_fields'] as $custom_field => $val) { + $asset->{$custom_field} = $val; + } + } - if (!empty($item["purchase_cost"])) { - //TODO How to generalize this for not USD? - $purchase_cost = substr($item["purchase_cost"],0,1) === '$' ? substr($item["purchase_cost"],1) : $item["purchase_cost"]; - $asset->purchase_cost = number_format($purchase_cost,2); - $this->log("Asset cost parsed: " . $asset->purchase_cost); - } else { - $asset->purchase_cost = 0.00; - } - $asset->serial = $asset_serial; - $asset->asset_tag = $item['asset_tag']; + if (!empty($item["purchase_cost"])) { + //TODO How to generalize this for not USD? + $purchase_cost = substr($item["purchase_cost"], 0, 1) === '$' ? substr($item["purchase_cost"], 1) : $item["purchase_cost"]; + $asset->purchase_cost = number_format($purchase_cost, 2); + $this->log("Asset cost parsed: " . $asset->purchase_cost); + } else { + $asset->purchase_cost = 0.00; + } + $asset->serial = $asset_serial; + $asset->asset_tag = $item['asset_tag']; $asset->warranty_months = $asset_warranty_months; - if($asset_model) - $asset->model_id = $asset_model->id; - if($item["user"]) - $asset->assigned_to = $item["user"]->id; - if($item["location"]) - $asset->rtd_location_id = $item["location"]->id; - $asset->user_id = $this->option('user_id'); - $this->log("status_id: " . $status_id); - $asset->status_id = $status_id; - if($item["company"]) - $asset->company_id = $item["company"]->id; - $asset->order_number = $item["order_number"]; - if($supplier) - $asset->supplier_id = $supplier->id; - $asset->notes = $item["notes"]; - $asset->image = $asset_image; - $this->assets->add($asset); - if (!$this->option('testrun')) { + if ($asset_model) { + $asset->model_id = $asset_model->id; + } + if ($item["user"]) { + $asset->assigned_to = $item["user"]->id; + } + if ($item["location"]) { + $asset->rtd_location_id = $item["location"]->id; + } + $asset->user_id = $this->option('user_id'); + $this->log("status_id: " . $status_id); + $asset->status_id = $status_id; + if ($item["company"]) { + $asset->company_id = $item["company"]->id; + } + $asset->order_number = $item["order_number"]; + if ($supplier) { + $asset->supplier_id = $supplier->id; + } + $asset->notes = $item["notes"]; + $asset->image = $asset_image; + $this->assets->add($asset); + if (!$this->option('testrun')) { - if ($asset->save()) { - $this->log('Asset ' . $item["item_name"] . ' with serial number ' . $asset_serial . ' was created'); - } else { + if ($asset->save()) { + $this->log('Asset ' . $item["item_name"] . ' with serial number ' . $asset_serial . ' was created'); + } else { $this->jsonError('Asset', $asset->getErrors()); - } + } - } else { - return; - } - } + } else { + return; + } + } - private $accessories; + private $accessories; - /** - * Create an accessory if a duplicate does not exist - * - * @author Daniel Melzter - * @since 3.0 - * @param $item array - */ - public function createAccessoryIfNotExists(array $item ) - { - $this->log("Creating Accessory"); - foreach ($this->accessories as $tempaccessory) { - if (strcasecmp($tempaccessory->name, $item["item_name"] ) == 0 ) { - $this->log('A matching Accessory ' . $item["item_name"] . ' already exists. '); - // FUTURE: Adjust quantity on import maybe? - return; - } - } + /** + * Create an accessory if a duplicate does not exist + * + * @author Daniel Melzter + * @since 3.0 + * @param $item array + */ + public function createAccessoryIfNotExists(array $item) + { + $this->log("Creating Accessory"); + foreach ($this->accessories as $tempaccessory) { + if (strcasecmp($tempaccessory->name, $item["item_name"]) == 0) { + $this->log('A matching Accessory ' . $item["item_name"] . ' already exists. '); + // FUTURE: Adjust quantity on import maybe? + return; + } + } - $accessory = new Accessory(); - $accessory->name = $item["item_name"]; + $accessory = new Accessory(); + $accessory->name = $item["item_name"]; - if (!empty($item["purchase_date"])) { - $accessory->purchase_date = $item["purchase_date"]; - } else { - $accessory->purchase_date = null; - } - if (!empty($item["purchase_cost"])) { - $accessory->purchase_cost = number_format(e($item["purchase_cost"]),2); - } else { - $accessory->purchase_cost = 0.00; - } - if($item["location"]) - $accessory->location_id = $item["location"]->id; - $accessory->user_id = $this->option('user_id'); - if($item["company"]) - $accessory->company_id = $item["company"]->id; - $accessory->order_number = $item["order_number"]; - if($item["category"]) - $accessory->category_id = $item["category"]->id; + if (!empty($item["purchase_date"])) { + $accessory->purchase_date = $item["purchase_date"]; + } else { + $accessory->purchase_date = null; + } + if (!empty($item["purchase_cost"])) { + $accessory->purchase_cost = number_format(e($item["purchase_cost"]), 2); + } else { + $accessory->purchase_cost = 0.00; + } + if ($item["location"]) { + $accessory->location_id = $item["location"]->id; + } + $accessory->user_id = $this->option('user_id'); + if ($item["company"]) { + $accessory->company_id = $item["company"]->id; + } + $accessory->order_number = $item["order_number"]; + if ($item["category"]) { + $accessory->category_id = $item["category"]->id; + } - //TODO: Implement + //TODO: Implement // $accessory->notes = e($item_notes); - $accessory->requestable = filter_var($item["requestable"], FILTER_VALIDATE_BOOLEAN); + $accessory->requestable = filter_var($item["requestable"], FILTER_VALIDATE_BOOLEAN); - //Must have at least zero of the item if we import it. - if($item["quantity"] > -1) { - $accessory->qty = $item["quantity"]; - } else { - $accessory->qty = 1; - } + //Must have at least zero of the item if we import it. + if ($item["quantity"] > -1) { + $accessory->qty = $item["quantity"]; + } else { + $accessory->qty = 1; + } - if (!$this->option('testrun')) { - if ($accessory->save()) { - $this->log('Accessory ' . $item["item_name"] . ' was created'); - // $this->comment('Accessory ' . $item["item_name"] . ' was created'); + if (!$this->option('testrun')) { + if ($accessory->save()) { + $this->log('Accessory ' . $item["item_name"] . ' was created'); + // $this->comment('Accessory ' . $item["item_name"] . ' was created'); - } else { - $this->jsonError('Accessory', $accessory->getErrors()) ; - } - } else { - $this->log('TEST RUN - Accessory ' . $item["item_name"] . ' not created'); - } - } + } else { + $this->jsonError('Accessory', $accessory->getErrors()) ; + } + } else { + $this->log('TEST RUN - Accessory ' . $item["item_name"] . ' not created'); + } + } - private $consumables; + private $consumables; - /** - * Create a consumable if a duplicate does not exist - * - * @author Daniel Melzter - * @since 3.0 - * @param $item array - */ - public function createConsumableIfNotExists(array $item) - { - $this->log("Creating Consumable"); - foreach($this->consumables as $tempconsumable) { - if(strcasecmp($tempconsumable->name, $item["item_name"]) == 0) { - $this->log("A matching consumable " . $item["item_name"] . " already exists"); - //TODO: Adjust quantity if different maybe? - return; - } - } + /** + * Create a consumable if a duplicate does not exist + * + * @author Daniel Melzter + * @since 3.0 + * @param $item array + */ + public function createConsumableIfNotExists(array $item) + { + $this->log("Creating Consumable"); + foreach ($this->consumables as $tempconsumable) { + if (strcasecmp($tempconsumable->name, $item["item_name"]) == 0) { + $this->log("A matching consumable " . $item["item_name"] . " already exists"); + //TODO: Adjust quantity if different maybe? + return; + } + } - $consumable = new Consumable(); - $consumable->name = $item["item_name"]; + $consumable = new Consumable(); + $consumable->name = $item["item_name"]; - if(!empty($item["purchase_date"])) { - $consumable->purchase_date = $item["purchase_date"]; - } else { - $consumable->purchase_date = null; - } + if (!empty($item["purchase_date"])) { + $consumable->purchase_date = $item["purchase_date"]; + } else { + $consumable->purchase_date = null; + } - if(!empty($item["purchase_cost"])) { - $consumable->purchase_cost = number_format(e($item["purchase_cost"]),2); - } else { - $consumable->purchase_cost = 0.00; - } - $consumable->location_id = $item["location"]->id; - $consumable->user_id = $this->option('user_id'); - $consumable->company_id = $item["company"]->id; - $consumable->order_number = $item["order_number"]; - $consumable->category_id = $item["category"]->id; - // TODO:Implement - //$consumable->notes= e($item_notes); - $consumable->requestable = filter_var($item["requestable"], FILTER_VALIDATE_BOOLEAN); + if (!empty($item["purchase_cost"])) { + $consumable->purchase_cost = number_format(e($item["purchase_cost"]), 2); + } else { + $consumable->purchase_cost = 0.00; + } + $consumable->location_id = $item["location"]->id; + $consumable->user_id = $this->option('user_id'); + $consumable->company_id = $item["company"]->id; + $consumable->order_number = $item["order_number"]; + $consumable->category_id = $item["category"]->id; + // TODO:Implement + //$consumable->notes= e($item_notes); + $consumable->requestable = filter_var($item["requestable"], FILTER_VALIDATE_BOOLEAN); - if($item["quantity"] > -1) { - $consumable->qty = $item["quantity"]; - } else { - $consumable->qty = 1; - } + if ($item["quantity"] > -1) { + $consumable->qty = $item["quantity"]; + } else { + $consumable->qty = 1; + } - if(!$this->option("testrun")) { - if($consumable->save()) { - $this->log("Consumable " . $item["item_name"] . ' was created'); - // $this->comment("Consumable " . $item["item_name"] . ' was created'); + if (!$this->option("testrun")) { + if ($consumable->save()) { + $this->log("Consumable " . $item["item_name"] . ' was created'); + // $this->comment("Consumable " . $item["item_name"] . ' was created'); - } else { - $this->jsonError('Consumable', $consumable->getErrors()); - } - } else { - $this->log('TEST RUN - Consumable ' . $item['item_name'] . ' not created'); - } - } + } else { + $this->jsonError('Consumable', $consumable->getErrors()); + } + } else { + $this->log('TEST RUN - Consumable ' . $item['item_name'] . ' not created'); + } + } - /** - * Get the console command arguments. - * - * @author Daniel Melzter - * @since 3.0 - * @return array - */ - protected function getArguments() - { - return array( - array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), - ); - } + /** + * Get the console command arguments. + * + * @author Daniel Melzter + * @since 3.0 + * @return array + */ + protected function getArguments() + { + return array( + array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), + ); + } - /** - * Get the console command options. - * - * @author Daniel Melzter - * @since 3.0 - * @return array - */ - protected function getOptions() - { - return array( - array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null), - array('username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null), - array('testrun', null, InputOption::VALUE_NONE, 'If set, will parse and output data without adding to database', null), - array('logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log') ), - array('item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Or Accessory', 'Asset'), + /** + * Get the console command options. + * + * @author Daniel Melzter + * @since 3.0 + * @return array + */ + protected function getOptions() + { + return array( + array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null), + array('username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null), + array('testrun', null, InputOption::VALUE_NONE, 'If set, will parse and output data without adding to database', null), + array('logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log') ), + array('item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Or Accessory', 'Asset'), array('web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'), array('user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1) - ); - - } - - + ); + } } diff --git a/app/Console/Commands/PaveIt.php b/app/Console/Commands/PaveIt.php index 12b3428927..21392d7e37 100644 --- a/app/Console/Commands/PaveIt.php +++ b/app/Console/Commands/PaveIt.php @@ -55,76 +55,74 @@ class PaveIt extends Command */ public function handle() { - if ($this->confirm("\n****************************************************\nTHIS WILL DELETE ALL OF THE DATA IN YOUR DATABASE. \nThere is NO undo. This WILL destroy ALL of your data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) - { - if( $this->option('soft')) - { - Accessory::getQuery()->delete(); - Asset::getQuery()->delete(); - Category::getQuery()->delete(); - Company::getQuery()->delete(); - Component::getQuery()->delete(); - Consumable::getQuery()->delete(); - Depreciation::getQuery()->delete(); - License::getQuery()->delete(); - LicenseSeat::getQuery()->delete(); - Location::getQuery()->delete(); - Manufacturer::getQuery()->delete(); - AssetModel::getQuery()->delete(); - Statuslabel::getQuery()->delete(); - Supplier::getQuery()->delete(); - Group::getQuery()->delete(); + if ($this->confirm("\n****************************************************\nTHIS WILL DELETE ALL OF THE DATA IN YOUR DATABASE. \nThere is NO undo. This WILL destroy ALL of your data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) { + if ($this->option('soft')) { + Accessory::getQuery()->delete(); + Asset::getQuery()->delete(); + Category::getQuery()->delete(); + Company::getQuery()->delete(); + Component::getQuery()->delete(); + Consumable::getQuery()->delete(); + Depreciation::getQuery()->delete(); + License::getQuery()->delete(); + LicenseSeat::getQuery()->delete(); + Location::getQuery()->delete(); + Manufacturer::getQuery()->delete(); + AssetModel::getQuery()->delete(); + Statuslabel::getQuery()->delete(); + Supplier::getQuery()->delete(); + Group::getQuery()->delete(); - DB::statement('delete from accessories_users'); - DB::statement('delete from asset_logs'); - DB::statement('delete from asset_maintenances'); - DB::statement('delete from asset_uploads'); - DB::statement('delete from consumables_users'); - DB::statement('delete from custom_field_custom_fieldset'); - DB::statement('delete from custom_fields'); - DB::statement('delete from custom_fieldsets'); - DB::statement('delete from components_assets'); - DB::statement('delete from password_resets'); - DB::statement('delete from requested_assets'); - DB::statement('delete from requests'); - DB::statement('delete from throttle'); - DB::statement('delete from users_groups'); - DB::statement('delete from users WHERE id!=1'); - } else { - \DB::statement('drop table IF EXISTS accessories_users'); - \DB::statement('drop table IF EXISTS accessories'); - \DB::statement('drop table IF EXISTS asset_logs'); - \DB::statement('drop table IF EXISTS asset_maintenances'); - \DB::statement('drop table IF EXISTS asset_uploads'); - \DB::statement('drop table IF EXISTS assets'); - \DB::statement('drop table IF EXISTS categories'); - \DB::statement('drop table IF EXISTS companies'); - \DB::statement('drop table IF EXISTS consumables_users'); - \DB::statement('drop table IF EXISTS consumables'); - \DB::statement('drop table IF EXISTS custom_field_custom_fieldset'); - \DB::statement('drop table IF EXISTS custom_fields'); - \DB::statement('drop table IF EXISTS custom_fieldsets'); - \DB::statement('drop table IF EXISTS depreciations'); - \DB::statement('drop table IF EXISTS groups'); - \DB::statement('drop table IF EXISTS history'); - \DB::statement('drop table IF EXISTS components'); - \DB::statement('drop table IF EXISTS components_assets'); - \DB::statement('drop table IF EXISTS license_seats'); - \DB::statement('drop table IF EXISTS licenses'); - \DB::statement('drop table IF EXISTS locations'); - \DB::statement('drop table IF EXISTS manufacturers'); - \DB::statement('drop table IF EXISTS models'); - \DB::statement('drop table IF EXISTS migrations'); - \DB::statement('drop table IF EXISTS password_resets'); - \DB::statement('drop table IF EXISTS requested_assets'); - \DB::statement('drop table IF EXISTS requests'); - \DB::statement('drop table IF EXISTS settings'); - \DB::statement('drop table IF EXISTS status_labels'); - \DB::statement('drop table IF EXISTS suppliers'); - \DB::statement('drop table IF EXISTS throttle'); - \DB::statement('drop table IF EXISTS users_groups'); - \DB::statement('drop table IF EXISTS users'); - } + DB::statement('delete from accessories_users'); + DB::statement('delete from asset_logs'); + DB::statement('delete from asset_maintenances'); + DB::statement('delete from asset_uploads'); + DB::statement('delete from consumables_users'); + DB::statement('delete from custom_field_custom_fieldset'); + DB::statement('delete from custom_fields'); + DB::statement('delete from custom_fieldsets'); + DB::statement('delete from components_assets'); + DB::statement('delete from password_resets'); + DB::statement('delete from requested_assets'); + DB::statement('delete from requests'); + DB::statement('delete from throttle'); + DB::statement('delete from users_groups'); + DB::statement('delete from users WHERE id!=1'); + } else { + \DB::statement('drop table IF EXISTS accessories_users'); + \DB::statement('drop table IF EXISTS accessories'); + \DB::statement('drop table IF EXISTS asset_logs'); + \DB::statement('drop table IF EXISTS asset_maintenances'); + \DB::statement('drop table IF EXISTS asset_uploads'); + \DB::statement('drop table IF EXISTS assets'); + \DB::statement('drop table IF EXISTS categories'); + \DB::statement('drop table IF EXISTS companies'); + \DB::statement('drop table IF EXISTS consumables_users'); + \DB::statement('drop table IF EXISTS consumables'); + \DB::statement('drop table IF EXISTS custom_field_custom_fieldset'); + \DB::statement('drop table IF EXISTS custom_fields'); + \DB::statement('drop table IF EXISTS custom_fieldsets'); + \DB::statement('drop table IF EXISTS depreciations'); + \DB::statement('drop table IF EXISTS groups'); + \DB::statement('drop table IF EXISTS history'); + \DB::statement('drop table IF EXISTS components'); + \DB::statement('drop table IF EXISTS components_assets'); + \DB::statement('drop table IF EXISTS license_seats'); + \DB::statement('drop table IF EXISTS licenses'); + \DB::statement('drop table IF EXISTS locations'); + \DB::statement('drop table IF EXISTS manufacturers'); + \DB::statement('drop table IF EXISTS models'); + \DB::statement('drop table IF EXISTS migrations'); + \DB::statement('drop table IF EXISTS password_resets'); + \DB::statement('drop table IF EXISTS requested_assets'); + \DB::statement('drop table IF EXISTS requests'); + \DB::statement('drop table IF EXISTS settings'); + \DB::statement('drop table IF EXISTS status_labels'); + \DB::statement('drop table IF EXISTS suppliers'); + \DB::statement('drop table IF EXISTS throttle'); + \DB::statement('drop table IF EXISTS users_groups'); + \DB::statement('drop table IF EXISTS users'); + } } } } diff --git a/app/Console/Commands/Purge.php b/app/Console/Commands/Purge.php index 24a1ab3d42..de7b518fb5 100644 --- a/app/Console/Commands/Purge.php +++ b/app/Console/Commands/Purge.php @@ -53,7 +53,7 @@ class Purge extends Command public function handle() { $force = $this->option('force'); - if (($this->confirm("\n****************************************************\nTHIS WILL PURGE ALL SOFT-DELETED ITEMS IN YOUR SYSTEM. \nThere is NO undo. This WILL permanently destroy \nALL of your deleted data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) || $force == 'true') { + if (($this->confirm("\n****************************************************\nTHIS WILL PURGE ALL SOFT-DELETED ITEMS IN YOUR SYSTEM. \nThere is NO undo. This WILL permanently destroy \nALL of your deleted data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) || $force == 'true') { /** * Delete assets @@ -140,7 +140,7 @@ class Purge extends Command $supplier->forceDelete(); } - $users = User::whereNotNull('deleted_at')->where('show_in_list','!=','0')->withTrashed()->get(); + $users = User::whereNotNull('deleted_at')->where('show_in_list', '!=', '0')->withTrashed()->get(); $this->info($users->count().' users purged.'); $user_assoc = 0; foreach ($users as $user) { diff --git a/app/Console/Commands/SendExpirationAlerts.php b/app/Console/Commands/SendExpirationAlerts.php index b5c1170bdb..83a95ead86 100644 --- a/app/Console/Commands/SendExpirationAlerts.php +++ b/app/Console/Commands/SendExpirationAlerts.php @@ -1,6 +1,7 @@ alert_interval); - $this->info(count($expiring_assets).' expiring assets'); + // Expiring Assets + $expiring_assets = Asset::getExpiringWarrantee(Setting::getSettings()->alert_interval); + $this->info(count($expiring_assets).' expiring assets'); - $asset_data['count'] = count($expiring_assets); - $asset_data['email_content'] =''; - $now = date("Y-m-d"); + $asset_data['count'] = count($expiring_assets); + $asset_data['email_content'] =''; + $now = date("Y-m-d"); - foreach ($expiring_assets as $asset) { + foreach ($expiring_assets as $asset) { - $expires = $asset->warrantee_expires(); - $difference = round(abs(strtotime($expires) - strtotime($now))/86400); + $expires = $asset->warrantee_expires(); + $difference = round(abs(strtotime($expires) - strtotime($now))/86400); - if ($difference > 30) { - $asset_data['email_content'] .= ''; - } else { - $asset_data['email_content'] .= ''; - } - $asset_data['email_content'] .= ''; - $asset_data['email_content'] .= $asset->showAssetName().''.e($asset->asset_tag).''; - $asset_data['email_content'] .= ''.e($asset->warrantee_expires()).''; - $asset_data['email_content'] .= ''.$difference.' days'; + if ($difference > 30) { + $asset_data['email_content'] .= ''; + } else { + $asset_data['email_content'] .= ''; + } + $asset_data['email_content'] .= ''; + $asset_data['email_content'] .= $asset->showAssetName().''.e($asset->asset_tag).''; + $asset_data['email_content'] .= ''.e($asset->warrantee_expires()).''; + $asset_data['email_content'] .= ''.$difference.' days'; $asset_data['email_content'] .= ''.($asset->supplier ? e($asset->supplier->name) : '').''; $asset_data['email_content'] .= ''.($asset->assigneduser ? e($asset->assigneduser->fullName()) : '').''; - $asset_data['email_content'] .= ''; - } + $asset_data['email_content'] .= ''; + } - // Expiring licenses - $expiring_licenses = License::getExpiringLicenses(Setting::getSettings()->alert_interval); - $this->info(count($expiring_licenses).' expiring licenses'); + // Expiring licenses + $expiring_licenses = License::getExpiringLicenses(Setting::getSettings()->alert_interval); + $this->info(count($expiring_licenses).' expiring licenses'); - $license_data['count'] = count($expiring_licenses); - $license_data['email_content'] = ''; + $license_data['count'] = count($expiring_licenses); + $license_data['email_content'] = ''; - foreach ($expiring_licenses as $license) { - $expires = $license->expiration_date; - $difference = round(abs(strtotime($expires) - strtotime($now))/86400); + foreach ($expiring_licenses as $license) { + $expires = $license->expiration_date; + $difference = round(abs(strtotime($expires) - strtotime($now))/86400); - if ($difference > 30) { - $license_data['email_content'] .= ''; - } else { - $license_data['email_content'] .= ''; - } - $license_data['email_content'] .= ''; - $license_data['email_content'] .= $license->name.''; - $license_data['email_content'] .= ''.$license->expiration_date.''; - $license_data['email_content'] .= ''.$difference.' days'; - $license_data['email_content'] .= ''; - } + if ($difference > 30) { + $license_data['email_content'] .= ''; + } else { + $license_data['email_content'] .= ''; + } + $license_data['email_content'] .= ''; + $license_data['email_content'] .= $license->name.''; + $license_data['email_content'] .= ''.$license->expiration_date.''; + $license_data['email_content'] .= ''.$difference.' days'; + $license_data['email_content'] .= ''; + } - if ((Setting::getSettings()->alert_email!='') && (Setting::getSettings()->alerts_enabled==1)) { + if ((Setting::getSettings()->alert_email!='') && (Setting::getSettings()->alerts_enabled==1)) { - if (count($expiring_assets) > 0) { - \Mail::send('emails.expiring-assets-report', $asset_data, function ($m) { - $m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name); - $m->subject('Expiring Assets Report'); - }); + if (count($expiring_assets) > 0) { + \Mail::send('emails.expiring-assets-report', $asset_data, function ($m) { + $m->to(explode(',', Setting::getSettings()->alert_email), Setting::getSettings()->site_name); + $m->subject('Expiring Assets Report'); + }); - } + } - if (count($expiring_licenses) > 0) { - \Mail::send('emails.expiring-licenses-report', $license_data, function ($m) { - $m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name); - $m->subject('Expiring Licenses Report'); - }); + if (count($expiring_licenses) > 0) { + \Mail::send('emails.expiring-licenses-report', $license_data, function ($m) { + $m->to(explode(',', Setting::getSettings()->alert_email), Setting::getSettings()->site_name); + $m->subject('Expiring Licenses Report'); + }); - } + } - } else { + } else { - if (Setting::getSettings()->alert_email=='') { - echo "Could not send email. No alert email configured in settings. \n"; - } elseif (Setting::getSettings()->alerts_enabled!=1) { - echo "Alerts are disabled in the settings. No mail will be sent. \n"; - } - - } - - - - - } + if (Setting::getSettings()->alert_email=='') { + echo "Could not send email. No alert email configured in settings. \n"; + } elseif (Setting::getSettings()->alerts_enabled!=1) { + echo "Alerts are disabled in the settings. No mail will be sent. \n"; + } + } + } } diff --git a/app/Console/Commands/SendInventoryAlerts.php b/app/Console/Commands/SendInventoryAlerts.php index 415c535a97..75318cd5ff 100644 --- a/app/Console/Commands/SendInventoryAlerts.php +++ b/app/Console/Commands/SendInventoryAlerts.php @@ -48,22 +48,21 @@ class SendInventoryAlerts extends Command $data['count'] = count($data['data']); if (count($data['data']) > 0) { - \Mail::send('emails.low-inventory', $data, function ($m) { - $m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name); - $m->subject('Low Inventory Report'); - }); + \Mail::send('emails.low-inventory', $data, function ($m) { + $m->to(explode(',', Setting::getSettings()->alert_email), Setting::getSettings()->site_name); + $m->subject('Low Inventory Report'); + }); - } + } } else { if (Setting::getSettings()->alert_email=='') { - echo "Could not send email. No alert email configured in settings. \n"; - } elseif (Setting::getSettings()->alerts_enabled!=1) { - echo "Alerts are disabled in the settings. No mail will be sent. \n"; - } + echo "Could not send email. No alert email configured in settings. \n"; + } elseif (Setting::getSettings()->alerts_enabled!=1) { + echo "Alerts are disabled in the settings. No mail will be sent. \n"; + } } } - } diff --git a/app/Console/Commands/SystemBackup.php b/app/Console/Commands/SystemBackup.php index 389368608c..26b1c0c750 100644 --- a/app/Console/Commands/SystemBackup.php +++ b/app/Console/Commands/SystemBackup.php @@ -4,44 +4,42 @@ namespace App\Console\Commands; use Illuminate\Console\Command; -class SystemBackup extends Command { +class SystemBackup extends Command +{ - /** - * The console command name. - * - * @var string - */ - protected $name = 'snipeit:backup'; + /** + * The console command name. + * + * @var string + */ + protected $name = 'snipeit:backup'; - /** - * The console command description. - * - * @var string - */ - protected $description = 'This command creates a database dump and zips up all of the uploaded files in the upload directories.'; - - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } - - /** - * Execute the console command. - * - * @return mixed - */ - public function fire() - { - // - $this->call('backup:run'); - - } + /** + * The console command description. + * + * @var string + */ + protected $description = 'This command creates a database dump and zips up all of the uploaded files in the upload directories.'; + /** + * Create a new command instance. + * + * @return void + */ + public function __construct() + { + parent::__construct(); + } + /** + * Execute the console command. + * + * @return mixed + */ + public function fire() + { + // + $this->call('backup:run'); + } } diff --git a/app/Console/Commands/Versioning.php b/app/Console/Commands/Versioning.php index dbae46fc6f..fff73ea238 100644 --- a/app/Console/Commands/Versioning.php +++ b/app/Console/Commands/Versioning.php @@ -6,7 +6,8 @@ use Symfony\Component\Console\Input\InputArgument; use Illuminate\Console\Command; -class Versioning extends Command { +class Versioning extends Command +{ /** * The console command name. @@ -45,14 +46,14 @@ class Versioning extends Command { // The git's output // get the argument passed in the git command - $hash_version = $this->argument('app_version'); + $hash_version = $this->argument('app_version'); - // discard the commit hash - $version = explode('-', $hash_version); - $realVersion = $version[0] . '-' . $version[1]; + // discard the commit hash + $version = explode('-', $hash_version); + $realVersion = $version[0] . '-' . $version[1]; - // save the version array to a variable - $array = var_export(array('app_version' => $realVersion,'hash_version' => $hash_version), true); + // save the version array to a variable + $array = var_export(array('app_version' => $realVersion,'hash_version' => $hash_version), true); // Construct our file content diff --git a/app/Http/Controllers/AccessoriesController.php b/app/Http/Controllers/AccessoriesController.php index b47149a773..a7c73f760a 100755 --- a/app/Http/Controllers/AccessoriesController.php +++ b/app/Http/Controllers/AccessoriesController.php @@ -52,7 +52,7 @@ class AccessoriesController extends Controller public function getCreate(Request $request) { // Show the page - $category_list = Helper::categoryList('accessory'); + $category_list = Helper::categoryList('accessory'); $company_list = Helper::companyList(); $location_list = Helper::locationsList(); return View::make('accessories/edit') diff --git a/app/Http/Controllers/AssetModelsController.php b/app/Http/Controllers/AssetModelsController.php index 77ee7bafeb..1fadcaa3a6 100755 --- a/app/Http/Controllers/AssetModelsController.php +++ b/app/Http/Controllers/AssetModelsController.php @@ -110,10 +110,10 @@ class AssetModelsController extends Controller $image = Input::file('image'); $file_name = str_random(25).".".$image->getClientOriginalExtension(); $path = public_path('uploads/models/'.$file_name); - Image::make($image->getRealPath())->resize(500, null, function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); - })->save($path); + Image::make($image->getRealPath())->resize(500, null, function ($constraint) { + $constraint->aspectRatio(); + $constraint->upsize(); + })->save($path); $model->image = $file_name; } diff --git a/app/Http/Controllers/AssetsController.php b/app/Http/Controllers/AssetsController.php index c3b72d7db1..d79c37e3ff 100755 --- a/app/Http/Controllers/AssetsController.php +++ b/app/Http/Controllers/AssetsController.php @@ -80,16 +80,17 @@ class AssetsController extends Controller * @since [v3.0] * @return Redirect */ - public function getAssetByTag() { + public function getAssetByTag() + { if (Input::get('topsearch')=="true") { $topsearch = true; } else { $topsearch = false; } - if ($asset = Asset::where('asset_tag','=',Input::get('assetTag'))->first()) { + if ($asset = Asset::where('asset_tag', '=', Input::get('assetTag'))->first()) { return redirect()->route('view/hardware', $asset->id)->with('topsearch', $topsearch); } - return redirect()->to('hardware')->with('error',trans('admin/hardware/message.does_not_exist')); + return redirect()->to('hardware')->with('error', trans('admin/hardware/message.does_not_exist')); } @@ -211,8 +212,8 @@ class AssetsController extends Controller if (Input::has('image')) { $image = Input::get('image'); $header = explode(';', $image, 2)[0]; - $extension = substr( $header, strpos($header, '/')+1); - $image = substr( $image, strpos($image, ',')+1); + $extension = substr($header, strpos($header, '/')+1); + $image = substr($image, strpos($image, ',')+1); $file_name = str_random(25).".".$extension; $path = public_path('uploads/assets/'.$file_name); @@ -231,9 +232,8 @@ class AssetsController extends Controller // FIXME: No idea why this is returning a Builder error on db_column_name. // Need to investigate and fix. Using static method for now. $model = AssetModel::find($request->get('model_id')); - if($model->fieldset) - { - foreach($model->fieldset->fields as $field) { + if ($model->fieldset) { + foreach ($model->fieldset->fields as $field) { $asset->{\App\Models\CustomField::name_to_db_name($field->name)} = e($request->input(\App\Models\CustomField::name_to_db_name($field->name))); } } @@ -384,15 +384,15 @@ class AssetsController extends Controller if (Input::has('image')) { $image = $request->input('image'); $header = explode(';', $image, 2)[0]; - $extension = substr( $header, strpos($header, '/')+1); - $image = substr( $image, strpos($image, ',')+1); + $extension = substr($header, strpos($header, '/')+1); + $image = substr($image, strpos($image, ',')+1); $file_name = str_random(25).".".$extension; $path = public_path('uploads/assets/'.$file_name); Image::make($image)->resize(500, 500, function ($constraint) { - $constraint->aspectRatio(); - $constraint->upsize(); + $constraint->aspectRatio(); + $constraint->upsize(); })->save($path); $asset->image = $file_name; } @@ -402,13 +402,12 @@ class AssetsController extends Controller // FIXME: No idea why this is returning a Builder error on db_column_name. // Need to investigate and fix. Using static method for now. $model = AssetModel::find($request->get('model_id')); - if($model->fieldset) - { - foreach($model->fieldset->fields as $field) { + if ($model->fieldset) { + foreach ($model->fieldset->fields as $field) { $asset->{\App\Models\CustomField::name_to_db_name($field->name)} = e($request->input(\App\Models\CustomField::name_to_db_name($field->name))); -// LOG::debug($field->name); -// LOG::debug(\App\Models\CustomField::name_to_db_name($field->name)); -// LOG::debug($field->db_column_name()); + // LOG::debug($field->name); + // LOG::debug(\App\Models\CustomField::name_to_db_name($field->name)); + // LOG::debug($field->db_column_name()); } } @@ -753,7 +752,7 @@ class AssetsController extends Controller if (isset($asset->id,$asset->asset_tag)) { $barcode = new \Com\Tecnick\Barcode\Barcode(); - $barcode_obj = $barcode->getBarcodeObj($settings->alt_barcode, $asset->asset_tag, 250, 20); + $barcode_obj = $barcode->getBarcodeObj($settings->alt_barcode, $asset->asset_tag, 250, 20); return response($barcode_obj->getPngData())->header('Content-type', 'image/png'); } @@ -778,8 +777,9 @@ class AssetsController extends Controller } // Check if the uploads directory exists. If not, try to create it. - if(!file_exists($path)) + if (!file_exists($path)) { mkdir($path, 0755); + } if ($handle = opendir($path)) { /* This is the correct way to loop over the directory. */ @@ -876,19 +876,21 @@ class AssetsController extends Controller return redirect()->to('hardware')->with('error', trans('general.insufficient_permissions')); } - $return = Artisan::call('snipeit:import', - ['filename'=> config('app.private_uploads').'/imports/assets/'.$filename, + $return = Artisan::call( + 'snipeit:import', + ['filename'=> config('app.private_uploads').'/imports/assets/'.$filename, '--email_format'=>'firstname.lastname', '--username_format'=>'firstname.lastname', '--web-importer' => true, '--user_id' => Auth::user()->id - ]); + ] + ); $display_output = Artisan::output(); $file = config('app.private_uploads').'/imports/assets/'.str_replace('.csv', '', $filename).'-output-'.date("Y-m-d-his").'.txt'; file_put_contents($file, $display_output); - if( $return === 0) //Success + if ($return === 0) { //Success return redirect()->to('hardware')->with('success', trans('admin/hardware/message.import.success')); - else if( $return === 1) { // Failure + } elseif ($return === 1) { // Failure return redirect()->back()->with('import_errors', json_decode($display_output))->with('error', trans('admin/hardware/message.import.error')); } dd("Shouldn't be here"); @@ -964,7 +966,7 @@ class AssetsController extends Controller } elseif (isset($asset->id)) { // Restore the asset - Asset::withTrashed()->where('id',$assetId)->restore(); + Asset::withTrashed()->where('id', $assetId)->restore(); return redirect()->route('hardware')->with('success', trans('admin/hardware/message.restore.success')); } else { diff --git a/app/Http/Controllers/CategoriesController.php b/app/Http/Controllers/CategoriesController.php index 7f473b2cb2..8a22a3ba25 100755 --- a/app/Http/Controllers/CategoriesController.php +++ b/app/Http/Controllers/CategoriesController.php @@ -244,7 +244,7 @@ class CategoriesController extends Controller public function getDatatable() { // Grab all the categories - $categories = Category::with('assets', 'accessories', 'consumables','components'); + $categories = Category::with('assets', 'accessories', 'consumables', 'components'); if (Input::has('search')) { $categories = $categories->TextSearch(e(Input::get('search'))); @@ -300,7 +300,8 @@ class CategoriesController extends Controller return $data; } - public function getDataViewAssets($categoryID) { + public function getDataViewAssets($categoryID) + { $category = Category::with('assets.company')->find($categoryID); $category_assets = $category->assets(); @@ -369,7 +370,8 @@ class CategoriesController extends Controller - public function getDataViewAccessories($categoryID) { + public function getDataViewAccessories($categoryID) + { $category = Category::with('accessories.company')->find($categoryID); $category_assets = $category->accessories; @@ -422,7 +424,8 @@ class CategoriesController extends Controller } - public function getDataViewConsumables($categoryID) { + public function getDataViewConsumables($categoryID) + { $category = Category::with('accessories.company')->find($categoryID); $category_assets = $category->consumables; @@ -474,7 +477,8 @@ class CategoriesController extends Controller return $data; } - public function getDataViewComponent($categoryID) { + public function getDataViewComponent($categoryID) + { $category = Category::with('accessories.company')->find($categoryID); $category_assets = $category->components; @@ -525,7 +529,4 @@ class CategoriesController extends Controller $data = array('total' => $count, 'rows' => $rows); return $data; } - - - } diff --git a/app/Http/Controllers/CustomFieldsController.php b/app/Http/Controllers/CustomFieldsController.php index c966b92f6c..12f44e9939 100644 --- a/app/Http/Controllers/CustomFieldsController.php +++ b/app/Http/Controllers/CustomFieldsController.php @@ -260,7 +260,8 @@ class CustomFieldsController extends Controller * @since [v3.0] * @return Array */ - public function postReorder($id) { + public function postReorder($id) + { $fieldset=CustomFieldset::find($id); $fields = array(); diff --git a/app/Http/Controllers/DepreciationsController.php b/app/Http/Controllers/DepreciationsController.php index fd9da487bd..59dc78d08d 100755 --- a/app/Http/Controllers/DepreciationsController.php +++ b/app/Http/Controllers/DepreciationsController.php @@ -11,7 +11,6 @@ use Str; use View; use Auth; - /** * This controller handles all actions related to Depreciations for * the Snipe-IT Asset Management application. diff --git a/app/Http/Controllers/GroupsController.php b/app/Http/Controllers/GroupsController.php index d72dc82c89..7f7781faf6 100755 --- a/app/Http/Controllers/GroupsController.php +++ b/app/Http/Controllers/GroupsController.php @@ -93,7 +93,7 @@ class GroupsController extends Controller $permissions = config('permissions'); $groupPermissions = $group->decodePermissions(); $selected_array = Helper::selectedPermissionsArray($permissions, $groupPermissions); - return View::make('groups/edit', compact('group', 'permissions','selected_array','groupPermissions')); + return View::make('groups/edit', compact('group', 'permissions', 'selected_array', 'groupPermissions')); } /** diff --git a/app/Http/Controllers/LicensesController.php b/app/Http/Controllers/LicensesController.php index 9322ba1526..2c551c9fc1 100755 --- a/app/Http/Controllers/LicensesController.php +++ b/app/Http/Controllers/LicensesController.php @@ -156,16 +156,16 @@ class LicensesController extends Controller $insertedId = $license->id; // Save the license seat data - DB::transaction(function() use (&$insertedId,&$license) { - for ($x=0; $x<$license->seats; $x++) { - $license_seat = new LicenseSeat(); - $license_seat->license_id = $insertedId; - $license_seat->user_id = Auth::user()->id; - $license_seat->assigned_to = null; - $license_seat->notes = null; - $license_seat->save(); - } - }); + DB::transaction(function () use (&$insertedId, &$license) { + for ($x=0; $x<$license->seats; $x++) { + $license_seat = new LicenseSeat(); + $license_seat->license_id = $insertedId; + $license_seat->user_id = Auth::user()->id; + $license_seat->assigned_to = null; + $license_seat->notes = null; + $license_seat->save(); + } + }); // Redirect to the new license page diff --git a/app/Http/Controllers/LocationsController.php b/app/Http/Controllers/LocationsController.php index 8fd076e4ba..4d1ebc4ee8 100755 --- a/app/Http/Controllers/LocationsController.php +++ b/app/Http/Controllers/LocationsController.php @@ -370,7 +370,7 @@ class LocationsController extends Controller public function getDataViewUsers($locationID) { $location = Location::find($locationID); - $users = User::where('location_id','=',$location->id); + $users = User::where('location_id', '=', $location->id); if (Input::has('search')) { $users = $users->TextSearch(e(Input::get('search'))); diff --git a/app/Http/Controllers/ReportsController.php b/app/Http/Controllers/ReportsController.php index 2df5d4b2d7..67adca563d 100644 --- a/app/Http/Controllers/ReportsController.php +++ b/app/Http/Controllers/ReportsController.php @@ -110,7 +110,7 @@ class ReportsController extends Controller ->orderBy('created_at', 'DESC') ->get(); - return View::make('reports/asset', compact('assets'))->with('settings',$settings); + return View::make('reports/asset', compact('assets'))->with('settings', $settings); } /** diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.php index 4627ccb303..09127e6e6d 100755 --- a/app/Http/Controllers/SettingsController.php +++ b/app/Http/Controllers/SettingsController.php @@ -49,7 +49,7 @@ class SettingsController extends Controller $start_settings['db_error'] = $e->getMessage(); } - $protocol = array_key_exists('HTTPS',$_SERVER) && ( $_SERVER['HTTPS'] == "on") ? 'https://' : 'http://'; + $protocol = array_key_exists('HTTPS', $_SERVER) && ( $_SERVER['HTTPS'] == "on") ? 'https://' : 'http://'; $pageURL = $protocol; @@ -97,7 +97,7 @@ class SettingsController extends Controller } - if(function_exists('posix_getpwuid')) { // Probably Linux + if (function_exists('posix_getpwuid')) { // Probably Linux $owner = posix_getpwuid(fileowner($_SERVER["SCRIPT_FILENAME"])); $start_settings['owner'] = $owner['name']; } else { // Windows @@ -552,7 +552,7 @@ class SettingsController extends Controller { if (!config('app.lock_passwords')) { if (Input::get('confirm_purge')=='DELETE') { - Artisan::call('snipeit:purge',['--force'=>'true','--no-interaction'=>true]); + Artisan::call('snipeit:purge', ['--force'=>'true','--no-interaction'=>true]); $output = Artisan::output(); return View::make('settings/purge') ->with('output', $output)->with('success', trans('admin/settings/message.purge.success')); diff --git a/app/Http/Controllers/UsersController.php b/app/Http/Controllers/UsersController.php index 40a9eaab90..fdfbbfab16 100755 --- a/app/Http/Controllers/UsersController.php +++ b/app/Http/Controllers/UsersController.php @@ -33,7 +33,6 @@ use URL; use View; use Illuminate\Http\Request; - /** * This controller handles all actions related to Users for * the Snipe-IT Asset Management application. @@ -142,7 +141,7 @@ class UsersController extends Controller return redirect::route('users')->with('success', trans('admin/users/message.success.create')); } - return redirect()->back()->withInput()->withErrors($user->getErrors()); + return redirect()->back()->withInput()->withErrors($user->getErrors()); @@ -284,9 +283,9 @@ class UsersController extends Controller $user->first_name = e($request->input('first_name')); $user->last_name = e($request->input('last_name')); $user->locale = e($request->input('locale')); - if (Input::has('username')) { - $user->username = e($request->input('username')); - } + if (Input::has('username')) { + $user->username = e($request->input('username')); + } $user->email = e($request->input('email')); $user->employee_num = e($request->input('employee_num')); @@ -431,7 +430,7 @@ class UsersController extends Controller //print_r($licenses); - $users = User::whereIn('id', $user_raw_array)->with('groups', 'assets', 'licenses','accessories')->get(); + $users = User::whereIn('id', $user_raw_array)->with('groups', 'assets', 'licenses', 'accessories')->get(); // $users = Company::scopeCompanyables($users)->get(); return View::make('users/confirm-bulk-delete', compact('users', 'statuslabel_list')); @@ -523,7 +522,7 @@ class UsersController extends Controller $logaction->logaction('checkin from'); } - LicenseSeat::whereIn('id', $license_array)->update(['assigned_to' => NULL]); + LicenseSeat::whereIn('id', $license_array)->update(['assigned_to' => null]); foreach ($users as $user) { $user->accessories()->sync(array()); @@ -553,22 +552,22 @@ class UsersController extends Controller { // Get user information - if (!$user = User::onlyTrashed()->find($id)) { - return redirect()->route('users')->with('error', trans('admin/users/messages.user_not_found')); - } + if (!$user = User::onlyTrashed()->find($id)) { + return redirect()->route('users')->with('error', trans('admin/users/messages.user_not_found')); + } - if (!Company::isCurrentUserHasAccess($user)) { - return redirect()->route('users')->with('error', trans('general.insufficient_permissions')); + if (!Company::isCurrentUserHasAccess($user)) { + return redirect()->route('users')->with('error', trans('general.insufficient_permissions')); + } else { + + // Restore the user + if (User::withTrashed()->where('id', $id)->restore()) { + return redirect()->route('users')->with('success', trans('admin/users/message.success.restored')); } else { - - // Restore the user - if (User::withTrashed()->where('id',$id)->restore()) { - return redirect()->route('users')->with('success', trans('admin/users/message.success.restored')); - } else { - return redirect()->route('users')->with('error','User could not be restored.'); - } - + return redirect()->route('users')->with('error', 'User could not be restored.'); } + + } } @@ -698,8 +697,8 @@ class UsersController extends Controller ->with('company_list', $company_list) ->with('manager_list', $manager_list) ->with('user', $user) - ->with('groups',$groups) - ->with('userGroups',$userGroups) + ->with('groups', $groups) + ->with('userGroups', $userGroups) ->with('clone_user', $user_to_clone); } catch (UserNotFoundException $e) { // Prepare the error message @@ -1193,29 +1192,29 @@ class UsersController extends Controller $global_count = 0; // Perform the search - do { - // Paginate (non-critical, if not supported by server) - ldap_control_paged_result($ldapconn, $page_size, false, $cookie); + do { + // Paginate (non-critical, if not supported by server) + ldap_control_paged_result($ldapconn, $page_size, false, $cookie); - $search_results = ldap_search($ldapconn, $base_dn, '('.$filter.')'); + $search_results = ldap_search($ldapconn, $base_dn, '('.$filter.')'); - if (!$search_results) { - return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_search').ldap_error($ldapconn)); - } + if (!$search_results) { + return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_search').ldap_error($ldapconn)); + } - // Get results from page - $results = ldap_get_entries($ldapconn, $search_results); - if (!$results) { - return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_get_entries').ldap_error($ldapconn)); - } + // Get results from page + $results = ldap_get_entries($ldapconn, $search_results); + if (!$results) { + return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_get_entries').ldap_error($ldapconn)); + } - // Add results to result set - $global_count += $results['count']; - $result_set = array_merge($result_set, $results); + // Add results to result set + $global_count += $results['count']; + $result_set = array_merge($result_set, $results); - ldap_control_paged_result_response($ldapconn, $search_results, $cookie); + ldap_control_paged_result_response($ldapconn, $search_results, $cookie); - } while ($cookie !== null && $cookie != ''); + } while ($cookie !== null && $cookie != ''); // Clean up after search diff --git a/app/Http/Controllers/ViewAssetsController.php b/app/Http/Controllers/ViewAssetsController.php index 984c0a0c74..f484a37487 100755 --- a/app/Http/Controllers/ViewAssetsController.php +++ b/app/Http/Controllers/ViewAssetsController.php @@ -59,7 +59,7 @@ class ViewAssetsController extends Controller public function getRequestableIndex() { - $assets = Asset::with('model', 'defaultLoc', 'assetloc','assigneduser')->Hardware()->RequestableAssets()->get(); + $assets = Asset::with('model', 'defaultLoc', 'assetloc', 'assigneduser')->Hardware()->RequestableAssets()->get(); return View::make('account/requestable-assets', compact('user', 'assets')); } @@ -143,7 +143,7 @@ class ViewAssetsController extends Controller public function getAcceptAsset($logID = null) { - if (!$findlog = DB::table('asset_logs')->where('id','=',$logID)->first()) { + if (!$findlog = DB::table('asset_logs')->where('id', '=', $logID)->first()) { echo 'no record'; //return redirect()->to('account')->with('error', trans('admin/hardware/message.does_not_exist')); } @@ -189,7 +189,7 @@ class ViewAssetsController extends Controller { // Check if the asset exists - if (is_null($findlog = DB::table('asset_logs')->where('id','=',$logID)->first())) { + if (is_null($findlog = DB::table('asset_logs')->where('id', '=', $logID)->first())) { // Redirect to the asset management page return redirect()->to('account/view-assets')->with('error', trans('admin/hardware/message.does_not_exist')); } diff --git a/app/Http/Middleware/CheckForSetup.php b/app/Http/Middleware/CheckForSetup.php index f2bef6bb88..8b9209c333 100644 --- a/app/Http/Middleware/CheckForSetup.php +++ b/app/Http/Middleware/CheckForSetup.php @@ -14,23 +14,23 @@ class CheckForSetup public function handle($request, Closure $next, $guard = null) { - if (Setting::setupCompleted()) { - - if ($request->is('setup*')) { - return redirect(config('app.url')); - } else { - return $next($request); - } + if (Setting::setupCompleted()) { + if ($request->is('setup*')) { + return redirect(config('app.url')); } else { - if (!$request->is('setup*')) { - return redirect(config('app.url').'/setup')->with('Request',$request); - } - return $next($request); - } + } else { + if (!$request->is('setup*')) { + return redirect(config('app.url').'/setup')->with('Request', $request); + } + + return $next($request); + + } + } } diff --git a/app/Http/Middleware/CheckPermissions.php b/app/Http/Middleware/CheckPermissions.php index c0a66ac7cd..d2319580a8 100644 --- a/app/Http/Middleware/CheckPermissions.php +++ b/app/Http/Middleware/CheckPermissions.php @@ -7,7 +7,6 @@ use Config; use Route; use Gate; - class CheckPermissions { /** diff --git a/app/Http/Requests/AssetRequest.php b/app/Http/Requests/AssetRequest.php index 24b25f2c4a..5b920cd494 100644 --- a/app/Http/Requests/AssetRequest.php +++ b/app/Http/Requests/AssetRequest.php @@ -5,6 +5,7 @@ namespace App\Http\Requests; use App\Http\Requests\Request; use App\Models\AssetModel; use Session; + class AssetRequest extends Request { /** @@ -40,8 +41,7 @@ class AssetRequest extends Request $model = AssetModel::find($this->request->get('model_id')); - if (($model) && ($model->fieldset)) - { + if (($model) && ($model->fieldset)) { $rules += $model->fieldset->validation_rules(); } diff --git a/app/Http/routes.php b/app/Http/routes.php index db71ae313b..a61b8573e7 100755 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -138,14 +138,22 @@ Route::group([ 'prefix' => 'api', 'middleware' => 'auth' ], function () { Route::group([ 'prefix' => 'categories' ], function () { Route::get('list', [ 'as' => 'api.categories.list', 'uses' => 'CategoriesController@getDatatable' ]); - Route::get( '{categoryID}/asset/view', - [ 'as' => 'api.categories.asset.view', 'uses' => 'CategoriesController@getDataViewAssets' ] ); - Route::get( '{categoryID}/accessory/view', - [ 'as' => 'api.categories.accessory.view', 'uses' => 'CategoriesController@getDataViewAccessories' ] ); - Route::get( '{categoryID}/consumable/view', - [ 'as' => 'api.categories.consumable.view', 'uses' => 'CategoriesController@getDataViewConsumables' ] ); - Route::get( '{categoryID}/component/view', - [ 'as' => 'api.categories.component.view', 'uses' => 'CategoriesController@getDataViewComponent' ] ); + Route::get( + '{categoryID}/asset/view', + [ 'as' => 'api.categories.asset.view', 'uses' => 'CategoriesController@getDataViewAssets' ] + ); + Route::get( + '{categoryID}/accessory/view', + [ 'as' => 'api.categories.accessory.view', 'uses' => 'CategoriesController@getDataViewAccessories' ] + ); + Route::get( + '{categoryID}/consumable/view', + [ 'as' => 'api.categories.consumable.view', 'uses' => 'CategoriesController@getDataViewConsumables' ] + ); + Route::get( + '{categoryID}/component/view', + [ 'as' => 'api.categories.component.view', 'uses' => 'CategoriesController@getDataViewComponent' ] + ); }); /*-- Suppliers API (mostly for creating new ones in-line while creating an asset) --*/ diff --git a/app/Models/Accessory.php b/app/Models/Accessory.php index a7544826da..227fcab37a 100755 --- a/app/Models/Accessory.php +++ b/app/Models/Accessory.php @@ -7,7 +7,7 @@ use Watson\Validating\ValidatingTrait; /** * Model for Accessories. - * + * * @version v1.0 */ class Accessory extends Model diff --git a/app/Models/Asset.php b/app/Models/Asset.php index 4b0c0f3dc1..63b953faff 100644 --- a/app/Models/Asset.php +++ b/app/Models/Asset.php @@ -172,13 +172,14 @@ class Asset extends Depreciable } - public function getDetailedNameAttribute() { - if($this->assigned_user) { - $user_name = $user->fullName(); - } else { - $user_name = "Unassigned"; - } - return $this->asset_tag . ' - ' . $this->name . ' (' . $user_name . ') ' . $this->model->name; + public function getDetailedNameAttribute() + { + if ($this->assigned_user) { + $user_name = $user->fullName(); + } else { + $user_name = "Unassigned"; + } + return $this->asset_tag . ' - ' . $this->name . ' (' . $user_name . ') ' . $this->model->name; } public function validationRules($id = '0') { @@ -542,13 +543,13 @@ class Asset extends Depreciable public function scopeAssetsByLocation($query, $location) { - return $query->where(function ($query) use ($location) - { - $query->whereHas('assigneduser', function ($query) use ($location) - { + return $query->where(function ($query) use ($location) { + + $query->whereHas('assigneduser', function ($query) use ($location) { + $query->where('users.location_id', '=', $location->id); - })->orWhere(function ($query) use ($location) - { + })->orWhere(function ($query) use ($location) { + $query->where('assets.rtd_location_id', '=', $location->id); $query->whereNull('assets.assigned_to'); }); @@ -642,7 +643,7 @@ class Asset extends Depreciable return $query->where('requestable', '=', 1) ->whereHas('assetstatus', function ($query) { - $query->where('deployable', '=', 1) + $query->where('deployable', '=', 1) ->where('pending', '=', 0) ->where('archived', '=', 0); }); diff --git a/app/Models/Company.php b/app/Models/Company.php index 3419a2f9ad..663ec24a0d 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -129,7 +129,7 @@ final class Company extends Model public static function scopeCompanyables($query, $column = 'company_id') { - if (!static::isFullMultipleCompanySupportEnabled() || (Auth::check() && Auth::user()->isSuperUser())) { + if (!static::isFullMultipleCompanySupportEnabled() || (Auth::check() && Auth::user()->isSuperUser())) { return $query; } else { return static::scopeCompanyablesDirectly($query, $column); diff --git a/app/Models/Group.php b/app/Models/Group.php index b54668ff6d..d5c6ea1b07 100755 --- a/app/Models/Group.php +++ b/app/Models/Group.php @@ -37,7 +37,4 @@ class Group extends Model { return json_decode($this->permissions, true); } - - - } diff --git a/app/Models/Setting.php b/app/Models/Setting.php index 0d3e378b2c..8482ca1298 100755 --- a/app/Models/Setting.php +++ b/app/Models/Setting.php @@ -55,22 +55,23 @@ class Setting extends Model return $static_cache; } - public static function setupCompleted() { + public static function setupCompleted() + { $users_table_exists = Schema::hasTable('users'); $settings_table_exists = Schema::hasTable('settings'); - if ($users_table_exists && $settings_table_exists) { - $usercount = User::withTrashed()->count(); + if ($users_table_exists && $settings_table_exists) { + $usercount = User::withTrashed()->count(); - if ($usercount > 0) { - return true; - } - return false; - } else { - return false; + if ($usercount > 0) { + return true; } + return false; + } else { + return false; + } return false; diff --git a/app/Models/User.php b/app/Models/User.php index 3ba643cfba..60fa756d5d 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -56,12 +56,12 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon $user_permissions = json_decode($this->permissions, true); //If the user is explicitly granted, return false - if (($user_permissions!='') && ((array_key_exists($section, $user_permissions)) && ($user_permissions[$section]=='1')) ) { + if (($user_permissions!='') && ((array_key_exists($section, $user_permissions)) && ($user_permissions[$section]=='1'))) { return true; } // If the user is explicitly denied, return false - if (($user_permissions=='') || array_key_exists($section, $user_permissions) && ($user_permissions[$section]=='-1')) { + if (($user_permissions=='') || array_key_exists($section, $user_permissions) && ($user_permissions[$section]=='-1')) { return false; } @@ -76,7 +76,8 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon return false; } - public function isSuperUser() { + public function isSuperUser() + { if (!$user_permissions = json_decode($this->permissions, true)) { return false; }