Formatting fixes for coding standards

This commit is contained in:
snipe 2016-06-22 12:27:41 -07:00
parent 70aefdc9c0
commit 4ed8ff5576
34 changed files with 1940 additions and 1935 deletions

View file

@ -1,5 +1,6 @@
<?php <?php
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\User; use App\Models\User;
use App\Models\Location; use App\Models\Location;
use App\Models\Category; use App\Models\Category;
@ -13,456 +14,450 @@ use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use League\Csv\Reader; use League\Csv\Reader;
class AssetImportCommand extends Command { class AssetImportCommand extends Command
{
/** /**
* The console command name. * The console command name.
* *
* @var string * @var string
*/ */
protected $name = 'snipeit:asset-import'; protected $name = 'snipeit:asset-import';
/** /**
* The console command description. * The console command description.
* *
* @var string * @var string
*/ */
protected $description = 'Import Assets from CSV'; protected $description = 'Import Assets from CSV';
/** /**
* Create a new command instance. * Create a new command instance.
* *
* @return void * @return void
*/ */
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
} }
/** /**
* Execute the console command. * Execute the console command.
* *
* @return mixed * @return mixed
*/ */
public function fire() public function fire()
{ {
$filename = $this->argument('filename'); $filename = $this->argument('filename');
if (!$this->option('testrun')=='true') { if (!$this->option('testrun')=='true') {
$this->comment('======= Importing Assets from '.$filename.' ========='); $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';
} else { } 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 (! ini_get("auto_detect_line_endings")) {
if ($category = Category::where('name', e($category_name))->where('category_type', 'asset')->first()) { ini_set("auto_detect_line_endings", '1');
$this->comment('Category '.$category_name.' already exists'); }
} else { $csv = Reader::createFromPath($this->argument('filename'));
$category = new Category(); $csv->setNewline("\r\n");
$category->name = e($category_name); $csv->setOffset(1);
$category->category_type = 'asset'; $duplicates = '';
$category->user_id = 1;
if ($category->save()) { // Loop through the records
$this->comment('Category '.$user_asset_category.' was created'); $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 { } else {
$this->error('Something went wrong! Category '.$user_asset_category.' was NOT created'); $user_name = '';
$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 { // User's email
$company = new Company(); 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 // User's email
if ($asset = Asset::where('asset_tag', e($user_asset_tag))->first()) { if (array_key_exists('2', $row)) {
$this->comment('The Asset with asset tag '.$user_asset_tag.' already exists'); $user_username = trim($row[2]);
} else { } else {
$asset = new Asset(); $user_username = '';
$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()) { // Asset Name
$this->comment('Asset '.$user_asset_name.' with serial number '.$user_asset_serial.' was created'); if (array_key_exists('3', $row)) {
} else { $user_asset_asset_name = trim($row[3]);
$this->error('Something went wrong! Asset '.$user_asset_name.' was NOT created: '.$asset->getErrors()->first()); } 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. * Get the console command arguments.
* *
* @return array * @return array
*/ */
protected function getArguments() protected function getArguments()
{ {
return array( return array(
array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), 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 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),
);
}
} }

View file

@ -46,32 +46,32 @@ class CreateAdmin extends Command
$show_in_list = $this->argument('show_in_list'); $show_in_list = $this->argument('show_in_list');
if (($first_name=='') || ($last_name=='') || ($username=='') || ($email=='') || ($password=='')) { if (($first_name=='') || ($last_name=='') || ($username=='') || ($email=='') || ($password=='')) {
$this->info('ERROR: All fields are required.'); $this->info('ERROR: All fields are required.');
} else { } else {
$user = new \App\Models\User; $user = new \App\Models\User;
$user->first_name = $first_name; $user->first_name = $first_name;
$user->last_name = $last_name; $user->last_name = $last_name;
$user->username = $username; $user->username = $username;
$user->email = $email; $user->email = $email;
$user->permissions = '{"admin":1,"user":1,"superuser":1,"reports.view":1, "licenses.keys":1}'; $user->permissions = '{"admin":1,"user":1,"superuser":1,"reports.view":1, "licenses.keys":1}';
$user->password = bcrypt($password); $user->password = bcrypt($password);
$user->activated = 1; $user->activated = 1;
if ($show_in_list == 'false') { if ($show_in_list == 'false') {
$user->show_in_list = 0; $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 ($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( // return array(
// array('username', InputArgument::REQUIRED, 'Username'), // array('username', InputArgument::REQUIRED, 'Username'),
// ); // );
// } // }
} }

View file

@ -5,7 +5,6 @@ namespace App\Console\Commands;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use App\Models\Setting; use App\Models\Setting;
class DisableLDAP extends Command class DisableLDAP extends Command
{ {
/** /**

View file

@ -10,375 +10,374 @@ use App\Models\Supplier;
use App\Models\License; use App\Models\License;
use App\Models\LicenseSeat; use App\Models\LicenseSeat;
class LicenseImportCommand extends Command { class LicenseImportCommand extends Command
{
/** /**
* The console command name. * The console command name.
* *
* @var string * @var string
*/ */
protected $name = 'snipeit:license-import'; protected $name = 'snipeit:license-import';
/** /**
* The console command description. * The console command description.
* *
* @var string * @var string
*/ */
protected $description = 'Import Licenses from CSV'; protected $description = 'Import Licenses from CSV';
/** /**
* Create a new command instance. * Create a new command instance.
* *
* @return void * @return void
*/ */
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
} }
/** /**
* Execute the console command. * Execute the console command.
* *
* @return mixed * @return mixed
*/ */
public function fire() public function fire()
{ {
$filename = $this->argument('filename'); $filename = $this->argument('filename');
if (!$this->option('testrun')=='true') { if (!$this->option('testrun')=='true') {
$this->comment('======= Importing Licenses from '.$filename.' ========='); $this->comment('======= Importing Licenses from '.$filename.' =========');
} else { } else {
$this->comment('====== TEST ONLY License Import for '.$filename.' ===='); $this->comment('====== TEST ONLY License Import for '.$filename.' ====');
$this->comment('============== NO DATA WILL BE WRITTEN =============='); $this->comment('============== NO DATA WILL BE WRITTEN ==============');
} }
if (! ini_get("auto_detect_line_endings")) { if (! ini_get("auto_detect_line_endings")) {
ini_set("auto_detect_line_endings", '1'); ini_set("auto_detect_line_endings", '1');
} }
$csv = Reader::createFromPath($this->argument('filename')); $csv = Reader::createFromPath($this->argument('filename'));
$csv->setNewline("\r\n"); $csv->setNewline("\r\n");
$csv->setOffset(1); $csv->setOffset(1);
$duplicates = ''; $duplicates = '';
// Loop through the records // Loop through the records
$nbInsert = $csv->each(function ($row) use ($duplicates) { $nbInsert = $csv->each(function ($row) use ($duplicates) {
$status_id = 1; $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)) { if (array_key_exists('0', $row)) {
$user_name = trim($row[0]); $user_name = trim($row[0]);
} else { } else {
$user_name = ''; $user_name = '';
} }
if (array_key_exists('1',$row)) { if (array_key_exists('1', $row)) {
$user_email = trim($row[1]); $user_email = trim($row[1]);
} else { } else {
$user_email = ''; $user_email = '';
} }
if (array_key_exists('2',$row)) { if (array_key_exists('2', $row)) {
$user_username = trim($row[2]); $user_username = trim($row[2]);
} else { } else {
$user_username = ''; $user_username = '';
} }
if (array_key_exists('3',$row)) { if (array_key_exists('3', $row)) {
$user_license_name = trim($row[3]); $user_license_name = trim($row[3]);
} else { } else {
$user_license_name = ''; $user_license_name = '';
} }
if (array_key_exists('4',$row)) { if (array_key_exists('4', $row)) {
$user_license_serial = trim($row[4]); $user_license_serial = trim($row[4]);
} else { } else {
$user_license_serial = ''; $user_license_serial = '';
} }
if (array_key_exists('5',$row)) { if (array_key_exists('5', $row)) {
$user_licensed_to_name = trim($row[5]); $user_licensed_to_name = trim($row[5]);
} else { } else {
$user_licensed_to_name = ''; $user_licensed_to_name = '';
} }
if (array_key_exists('6',$row)) { if (array_key_exists('6', $row)) {
$user_licensed_to_email = trim($row[6]); $user_licensed_to_email = trim($row[6]);
} else { } else {
$user_licensed_to_email = ''; $user_licensed_to_email = '';
} }
if (array_key_exists('7',$row)) { if (array_key_exists('7', $row)) {
$user_license_seats = trim($row[7]); $user_license_seats = trim($row[7]);
} else { } else {
$user_license_seats = ''; $user_license_seats = '';
} }
if (array_key_exists('8',$row)) { if (array_key_exists('8', $row)) {
$user_license_reassignable = trim($row[8]); $user_license_reassignable = trim($row[8]);
if ($user_license_reassignable!='') { if ($user_license_reassignable!='') {
if ((strtolower($user_license_reassignable)=='yes') || (strtolower($user_license_reassignable)=='true') || ($user_license_reassignable=='1')) { if ((strtolower($user_license_reassignable)=='yes') || (strtolower($user_license_reassignable)=='true') || ($user_license_reassignable=='1')) {
$user_license_reassignable = 1; $user_license_reassignable = 1;
} }
} else { } else {
$user_license_reassignable = 0; $user_license_reassignable = 0;
} }
} else { } else {
$user_license_reassignable = 0; $user_license_reassignable = 0;
} }
if (array_key_exists('9',$row)) { if (array_key_exists('9', $row)) {
$user_license_supplier = trim($row[9]); $user_license_supplier = trim($row[9]);
} else { } else {
$user_license_supplier = ''; $user_license_supplier = '';
} }
if (array_key_exists('10',$row)) { if (array_key_exists('10', $row)) {
$user_license_maintained = trim($row[10]); $user_license_maintained = trim($row[10]);
if ($user_license_maintained!='') { if ($user_license_maintained!='') {
if ((strtolower($user_license_maintained)=='yes') || (strtolower($user_license_maintained)=='true') || ($user_license_maintained=='1')) { if ((strtolower($user_license_maintained)=='yes') || (strtolower($user_license_maintained)=='true') || ($user_license_maintained=='1')) {
$user_license_maintained = 1; $user_license_maintained = 1;
} }
} else { } else {
$user_license_maintained = 0; $user_license_maintained = 0;
} }
} else { } else {
$user_license_maintained = ''; $user_license_maintained = '';
} }
if (array_key_exists('11',$row)) { if (array_key_exists('11', $row)) {
$user_license_notes = trim($row[11]); $user_license_notes = trim($row[11]);
} else { } else {
$user_license_notes = ''; $user_license_notes = '';
} }
if (array_key_exists('12',$row)) { if (array_key_exists('12', $row)) {
if ($row[12]!='') { if ($row[12]!='') {
$user_license_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12])); $user_license_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12]));
} else { } else {
$user_license_purchase_date = ''; $user_license_purchase_date = '';
} }
} else { } else {
$user_license_purchase_date = 0; $user_license_purchase_date = 0;
} }
// A number was given instead of a name // A number was given instead of a name
if (is_numeric($user_name)) { if (is_numeric($user_name)) {
$this->comment('User '.$user_name.' is not a name - assume this user already exists'); $this->comment('User '.$user_name.' is not a name - assume this user already exists');
$user_username = ''; $user_username = '';
// No name was given // No name was given
} elseif ($user_name=='') { } elseif ($user_name=='') {
$this->comment('No user data provided - skipping user creation, just adding license'); $this->comment('No user data provided - skipping user creation, just adding license');
$first_name = ''; $first_name = '';
$last_name = ''; $last_name = '';
$user_username = ''; $user_username = '';
} else { } else {
$name = explode(" ", $user_name); $name = explode(" ", $user_name);
$first_name = $name[0]; $first_name = $name[0];
$email_last_name = ''; $email_last_name = '';
$email_prefix = $first_name; $email_prefix = $first_name;
if (!array_key_exists(1, $name)) { if (!array_key_exists(1, $name)) {
$last_name=''; $last_name='';
$email_last_name = $last_name; $email_last_name = $last_name;
$email_prefix = $first_name; $email_prefix = $first_name;
} else { } else {
$last_name = str_replace($first_name,'',$user_name); $last_name = str_replace($first_name, '', $user_name);
if ($this->option('email_format')=='filastname') { if ($this->option('email_format')=='filastname') {
$email_last_name.=str_replace(' ','',$last_name); $email_last_name.=str_replace(' ', '', $last_name);
$email_prefix = $first_name[0].$email_last_name; $email_prefix = $first_name[0].$email_last_name;
} elseif ($this->option('email_format')=='firstname.lastname') { } elseif ($this->option('email_format')=='firstname.lastname') {
$email_last_name.=str_replace(' ','',$last_name); $email_last_name.=str_replace(' ', '', $last_name);
$email_prefix = $first_name.'.'.$email_last_name; $email_prefix = $first_name.'.'.$email_last_name;
} elseif ($this->option('email_format')=='firstname') { } elseif ($this->option('email_format')=='firstname') {
$email_last_name.=str_replace(' ','',$last_name); $email_last_name.=str_replace(' ', '', $last_name);
$email_prefix = $first_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 // Generate an email based on their name if no email address is given
if ($user_email=='') { if ($user_email=='') {
if ($first_name=='Unknown') { if ($first_name=='Unknown') {
$status_id = 7; $status_id = 7;
} }
$email = strtolower($email_prefix).'@'.$this->option('domain'); $email = strtolower($email_prefix).'@'.$this->option('domain');
$user_email = str_replace("'",'',$email); $user_email = str_replace("'", '', $email);
} }
} }
$this->comment('Full Name: '.$user_name); $this->comment('Full Name: '.$user_name);
$this->comment('First Name: '.$first_name); $this->comment('First Name: '.$first_name);
$this->comment('Last Name: '.$last_name); $this->comment('Last Name: '.$last_name);
$this->comment('Username: '.$user_username); $this->comment('Username: '.$user_username);
$this->comment('Email: '.$user_email); $this->comment('Email: '.$user_email);
$this->comment('License Name: '.$user_license_name); $this->comment('License Name: '.$user_license_name);
$this->comment('Serial No: '.$user_license_serial); $this->comment('Serial No: '.$user_license_serial);
$this->comment('Licensed To Name: '.$user_licensed_to_name); $this->comment('Licensed To Name: '.$user_licensed_to_name);
$this->comment('Licensed To Email: '.$user_licensed_to_email); $this->comment('Licensed To Email: '.$user_licensed_to_email);
$this->comment('Seats: '.$user_license_seats); $this->comment('Seats: '.$user_license_seats);
$this->comment('Reassignable: '.$user_license_reassignable); $this->comment('Reassignable: '.$user_license_reassignable);
$this->comment('Supplier: '.$user_license_supplier); $this->comment('Supplier: '.$user_license_supplier);
$this->comment('Maintained: '.$user_license_maintained); $this->comment('Maintained: '.$user_license_maintained);
$this->comment('Notes: '.$user_license_notes); $this->comment('Notes: '.$user_license_notes);
$this->comment('Purchase Date: '.$user_license_purchase_date); $this->comment('Purchase Date: '.$user_license_purchase_date);
$this->comment('------------- Action Summary ----------------'); $this->comment('------------- Action Summary ----------------');
if ($user_username!='') { if ($user_username!='') {
if ($user = User::where('username', $user_username)->whereNotNull('username')->first()) { if ($user = User::where('username', $user_username)->whereNotNull('username')->first()) {
$this->comment('User '.$user_username.' already exists'); $this->comment('User '.$user_username.' already exists');
} else { } else {
$user = new \App\Models\User; $user = new \App\Models\User;
$password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20); $password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
$user->first_name = $first_name; $user->first_name = $first_name;
$user->last_name = $last_name; $user->last_name = $last_name;
$user->username = $user_username; $user->username = $user_username;
$user->email = $user_email; $user->email = $user_email;
$user->permissions = '{user":1}'; $user->permissions = '{user":1}';
$user->password = bcrypt($password); $user->password = bcrypt($password);
$user->activated = 1; $user->activated = 1;
if ($user->save()) { if ($user->save()) {
$this->comment('User '.$first_name.' created'); $this->comment('User '.$first_name.' created');
} else { } else {
$this->error('ERROR CREATING User '.$first_name.' '.$last_name); $this->error('ERROR CREATING User '.$first_name.' '.$last_name);
$this->error($user->getErrors()); $this->error($user->getErrors());
} }
$this->comment('User '.$first_name.' created'); $this->comment('User '.$first_name.' created');
} }
} else { } else {
$user = new User; $user = new User;
$user->user_id = null; $user->user_id = null;
} }
// Check for the supplier match and create it if it doesn't exist // Check for the supplier match and create it if it doesn't exist
if ($supplier = Supplier::where('name', $user_license_supplier)->first()) { if ($supplier = Supplier::where('name', $user_license_supplier)->first()) {
$this->comment('Supplier '.$user_license_supplier.' already exists'); $this->comment('Supplier '.$user_license_supplier.' already exists');
} else { } else {
$supplier = new Supplier(); $supplier = new Supplier();
$supplier->name = e($user_license_supplier); $supplier->name = e($user_license_supplier);
$supplier->user_id = 1; $supplier->user_id = 1;
if ($supplier->save()) { if ($supplier->save()) {
$this->comment('Supplier '.$user_license_supplier.' was created'); $this->comment('Supplier '.$user_license_supplier.' was created');
} else { } else {
$this->comment('Something went wrong! Supplier '.$user_license_supplier.' was NOT created'); $this->comment('Something went wrong! Supplier '.$user_license_supplier.' was NOT created');
} }
} }
// Add the license // Add the license
$license = new License(); $license = new License();
$license->name = e($user_license_name); $license->name = e($user_license_name);
if ($user_license_purchase_date!='') { if ($user_license_purchase_date!='') {
$license->purchase_date = $user_license_purchase_date; $license->purchase_date = $user_license_purchase_date;
} else { } else {
$license->purchase_date = null; $license->purchase_date = null;
} }
$license->serial = e($user_license_serial); $license->serial = e($user_license_serial);
$license->seats = e($user_license_seats); $license->seats = e($user_license_seats);
$license->supplier_id = $supplier->id; $license->supplier_id = $supplier->id;
$license->user_id = 1; $license->user_id = 1;
if ($user_license_purchase_date!='') { if ($user_license_purchase_date!='') {
$license->purchase_date = $user_license_purchase_date; $license->purchase_date = $user_license_purchase_date;
} else { } else {
$license->purchase_date = null; $license->purchase_date = null;
} }
$license->license_name = $user_licensed_to_name; $license->license_name = $user_licensed_to_name;
$license->license_email = $user_licensed_to_email; $license->license_email = $user_licensed_to_email;
$license->notes = e($user_license_notes); $license->notes = e($user_license_notes);
if ($license->save()) { if ($license->save()) {
$this->comment('License '.$user_license_name.' with serial number '.$user_license_serial.' was created'); $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++) { for ($x = 0; $x < $user_license_seats; $x++) {
// Create the license seat entries // Create the license seat entries
$license_seat = new LicenseSeat(); $license_seat = new LicenseSeat();
$license_seat->license_id = $license->id; $license_seat->license_id = $license->id;
// Only assign the first seat to the user // Only assign the first seat to the user
if ($x==0) { if ($x==0) {
$license_seat->assigned_to = $user->id; $license_seat->assigned_to = $user->id;
} else { } else {
$license_seat->assigned_to = null; $license_seat->assigned_to = null;
} }
if ($license_seat->save()) { if ($license_seat->save()) {
$license_seat_created++; $license_seat_created++;
} }
} }
if ($license_seat_created > 0) { if ($license_seat_created > 0) {
$this->comment($license_seat_created.' seats were created'); $this->comment($license_seat_created.' seats were created');
} else { } else {
$this->comment('Something went wrong! NO seats for '.$user_license_name.' were created'); $this->comment('Something went wrong! NO seats for '.$user_license_name.' were created');
} }
} else { } 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. * Get the console command arguments.
* *
* @return array * @return array
*/ */
protected function getArguments() protected function getArguments()
{ {
return array( return array(
array('filename', InputArgument::REQUIRED, 'File for the CSV import.'), 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 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),
);
}
} }

File diff suppressed because it is too large Load diff

View file

@ -55,76 +55,74 @@ class PaveIt extends Command
*/ */
public function handle() 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->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')) {
if( $this->option('soft')) Accessory::getQuery()->delete();
{ Asset::getQuery()->delete();
Accessory::getQuery()->delete(); Category::getQuery()->delete();
Asset::getQuery()->delete(); Company::getQuery()->delete();
Category::getQuery()->delete(); Component::getQuery()->delete();
Company::getQuery()->delete(); Consumable::getQuery()->delete();
Component::getQuery()->delete(); Depreciation::getQuery()->delete();
Consumable::getQuery()->delete(); License::getQuery()->delete();
Depreciation::getQuery()->delete(); LicenseSeat::getQuery()->delete();
License::getQuery()->delete(); Location::getQuery()->delete();
LicenseSeat::getQuery()->delete(); Manufacturer::getQuery()->delete();
Location::getQuery()->delete(); AssetModel::getQuery()->delete();
Manufacturer::getQuery()->delete(); Statuslabel::getQuery()->delete();
AssetModel::getQuery()->delete(); Supplier::getQuery()->delete();
Statuslabel::getQuery()->delete(); Group::getQuery()->delete();
Supplier::getQuery()->delete();
Group::getQuery()->delete();
DB::statement('delete from accessories_users'); DB::statement('delete from accessories_users');
DB::statement('delete from asset_logs'); DB::statement('delete from asset_logs');
DB::statement('delete from asset_maintenances'); DB::statement('delete from asset_maintenances');
DB::statement('delete from asset_uploads'); DB::statement('delete from asset_uploads');
DB::statement('delete from consumables_users'); DB::statement('delete from consumables_users');
DB::statement('delete from custom_field_custom_fieldset'); DB::statement('delete from custom_field_custom_fieldset');
DB::statement('delete from custom_fields'); DB::statement('delete from custom_fields');
DB::statement('delete from custom_fieldsets'); DB::statement('delete from custom_fieldsets');
DB::statement('delete from components_assets'); DB::statement('delete from components_assets');
DB::statement('delete from password_resets'); DB::statement('delete from password_resets');
DB::statement('delete from requested_assets'); DB::statement('delete from requested_assets');
DB::statement('delete from requests'); DB::statement('delete from requests');
DB::statement('delete from throttle'); DB::statement('delete from throttle');
DB::statement('delete from users_groups'); DB::statement('delete from users_groups');
DB::statement('delete from users WHERE id!=1'); DB::statement('delete from users WHERE id!=1');
} else { } else {
\DB::statement('drop table IF EXISTS accessories_users'); \DB::statement('drop table IF EXISTS accessories_users');
\DB::statement('drop table IF EXISTS accessories'); \DB::statement('drop table IF EXISTS accessories');
\DB::statement('drop table IF EXISTS asset_logs'); \DB::statement('drop table IF EXISTS asset_logs');
\DB::statement('drop table IF EXISTS asset_maintenances'); \DB::statement('drop table IF EXISTS asset_maintenances');
\DB::statement('drop table IF EXISTS asset_uploads'); \DB::statement('drop table IF EXISTS asset_uploads');
\DB::statement('drop table IF EXISTS assets'); \DB::statement('drop table IF EXISTS assets');
\DB::statement('drop table IF EXISTS categories'); \DB::statement('drop table IF EXISTS categories');
\DB::statement('drop table IF EXISTS companies'); \DB::statement('drop table IF EXISTS companies');
\DB::statement('drop table IF EXISTS consumables_users'); \DB::statement('drop table IF EXISTS consumables_users');
\DB::statement('drop table IF EXISTS consumables'); \DB::statement('drop table IF EXISTS consumables');
\DB::statement('drop table IF EXISTS custom_field_custom_fieldset'); \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_fields');
\DB::statement('drop table IF EXISTS custom_fieldsets'); \DB::statement('drop table IF EXISTS custom_fieldsets');
\DB::statement('drop table IF EXISTS depreciations'); \DB::statement('drop table IF EXISTS depreciations');
\DB::statement('drop table IF EXISTS groups'); \DB::statement('drop table IF EXISTS groups');
\DB::statement('drop table IF EXISTS history'); \DB::statement('drop table IF EXISTS history');
\DB::statement('drop table IF EXISTS components'); \DB::statement('drop table IF EXISTS components');
\DB::statement('drop table IF EXISTS components_assets'); \DB::statement('drop table IF EXISTS components_assets');
\DB::statement('drop table IF EXISTS license_seats'); \DB::statement('drop table IF EXISTS license_seats');
\DB::statement('drop table IF EXISTS licenses'); \DB::statement('drop table IF EXISTS licenses');
\DB::statement('drop table IF EXISTS locations'); \DB::statement('drop table IF EXISTS locations');
\DB::statement('drop table IF EXISTS manufacturers'); \DB::statement('drop table IF EXISTS manufacturers');
\DB::statement('drop table IF EXISTS models'); \DB::statement('drop table IF EXISTS models');
\DB::statement('drop table IF EXISTS migrations'); \DB::statement('drop table IF EXISTS migrations');
\DB::statement('drop table IF EXISTS password_resets'); \DB::statement('drop table IF EXISTS password_resets');
\DB::statement('drop table IF EXISTS requested_assets'); \DB::statement('drop table IF EXISTS requested_assets');
\DB::statement('drop table IF EXISTS requests'); \DB::statement('drop table IF EXISTS requests');
\DB::statement('drop table IF EXISTS settings'); \DB::statement('drop table IF EXISTS settings');
\DB::statement('drop table IF EXISTS status_labels'); \DB::statement('drop table IF EXISTS status_labels');
\DB::statement('drop table IF EXISTS suppliers'); \DB::statement('drop table IF EXISTS suppliers');
\DB::statement('drop table IF EXISTS throttle'); \DB::statement('drop table IF EXISTS throttle');
\DB::statement('drop table IF EXISTS users_groups'); \DB::statement('drop table IF EXISTS users_groups');
\DB::statement('drop table IF EXISTS users'); \DB::statement('drop table IF EXISTS users');
} }
} }
} }
} }

View file

@ -53,7 +53,7 @@ class Purge extends Command
public function handle() public function handle()
{ {
$force = $this->option('force'); $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 * Delete assets
@ -140,7 +140,7 @@ class Purge extends Command
$supplier->forceDelete(); $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.'); $this->info($users->count().' users purged.');
$user_assoc = 0; $user_assoc = 0;
foreach ($users as $user) { foreach ($users as $user) {

View file

@ -1,6 +1,7 @@
<?php <?php
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Asset; use App\Models\Asset;
use App\Models\License; use App\Models\License;
use App\Models\Setting; use App\Models\Setting;
@ -8,129 +9,125 @@ use DB;
use Illuminate\Console\Command; use Illuminate\Console\Command;
class SendExpirationAlerts extends Command { class SendExpirationAlerts extends Command
{
/** /**
* The console command name. * The console command name.
* *
* @var string * @var string
*/ */
protected $name = 'snipeit:expiring-alerts'; protected $name = 'snipeit:expiring-alerts';
/** /**
* The console command description. * The console command description.
* *
* @var string * @var string
*/ */
protected $description = 'Check for expiring warrantees and service agreements, and sends out an alert email.'; protected $description = 'Check for expiring warrantees and service agreements, and sends out an alert email.';
/** /**
* Create a new command instance. * Create a new command instance.
* *
* @return void * @return void
*/ */
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
} }
/** /**
* Execute the console command. * Execute the console command.
* *
* @return mixed * @return mixed
*/ */
public function fire() public function fire()
{ {
// Expiring Assets // Expiring Assets
$expiring_assets = Asset::getExpiringWarrantee(Setting::getSettings()->alert_interval); $expiring_assets = Asset::getExpiringWarrantee(Setting::getSettings()->alert_interval);
$this->info(count($expiring_assets).' expiring assets'); $this->info(count($expiring_assets).' expiring assets');
$asset_data['count'] = count($expiring_assets); $asset_data['count'] = count($expiring_assets);
$asset_data['email_content'] =''; $asset_data['email_content'] ='';
$now = date("Y-m-d"); $now = date("Y-m-d");
foreach ($expiring_assets as $asset) { foreach ($expiring_assets as $asset) {
$expires = $asset->warrantee_expires(); $expires = $asset->warrantee_expires();
$difference = round(abs(strtotime($expires) - strtotime($now))/86400); $difference = round(abs(strtotime($expires) - strtotime($now))/86400);
if ($difference > 30) { if ($difference > 30) {
$asset_data['email_content'] .= '<tr style="background-color: #fcffa3;">'; $asset_data['email_content'] .= '<tr style="background-color: #fcffa3;">';
} else { } else {
$asset_data['email_content'] .= '<tr style="background-color:#d9534f;">'; $asset_data['email_content'] .= '<tr style="background-color:#d9534f;">';
} }
$asset_data['email_content'] .= '<td><a href="'.config('app.url').'/hardware/'.e($asset->id).'/view">'; $asset_data['email_content'] .= '<td><a href="'.config('app.url').'/hardware/'.e($asset->id).'/view">';
$asset_data['email_content'] .= $asset->showAssetName().'</a></td><td>'.e($asset->asset_tag).'</td>'; $asset_data['email_content'] .= $asset->showAssetName().'</a></td><td>'.e($asset->asset_tag).'</td>';
$asset_data['email_content'] .= '<td>'.e($asset->warrantee_expires()).'</td>'; $asset_data['email_content'] .= '<td>'.e($asset->warrantee_expires()).'</td>';
$asset_data['email_content'] .= '<td>'.$difference.' days</td>'; $asset_data['email_content'] .= '<td>'.$difference.' days</td>';
$asset_data['email_content'] .= '<td>'.($asset->supplier ? e($asset->supplier->name) : '').'</td>'; $asset_data['email_content'] .= '<td>'.($asset->supplier ? e($asset->supplier->name) : '').'</td>';
$asset_data['email_content'] .= '<td>'.($asset->assigneduser ? e($asset->assigneduser->fullName()) : '').'</td>'; $asset_data['email_content'] .= '<td>'.($asset->assigneduser ? e($asset->assigneduser->fullName()) : '').'</td>';
$asset_data['email_content'] .= '</tr>'; $asset_data['email_content'] .= '</tr>';
} }
// Expiring licenses // Expiring licenses
$expiring_licenses = License::getExpiringLicenses(Setting::getSettings()->alert_interval); $expiring_licenses = License::getExpiringLicenses(Setting::getSettings()->alert_interval);
$this->info(count($expiring_licenses).' expiring licenses'); $this->info(count($expiring_licenses).' expiring licenses');
$license_data['count'] = count($expiring_licenses); $license_data['count'] = count($expiring_licenses);
$license_data['email_content'] = ''; $license_data['email_content'] = '';
foreach ($expiring_licenses as $license) { foreach ($expiring_licenses as $license) {
$expires = $license->expiration_date; $expires = $license->expiration_date;
$difference = round(abs(strtotime($expires) - strtotime($now))/86400); $difference = round(abs(strtotime($expires) - strtotime($now))/86400);
if ($difference > 30) { if ($difference > 30) {
$license_data['email_content'] .= '<tr style="background-color: #fcffa3;">'; $license_data['email_content'] .= '<tr style="background-color: #fcffa3;">';
} else { } else {
$license_data['email_content'] .= '<tr style="background-color:#d9534f;">'; $license_data['email_content'] .= '<tr style="background-color:#d9534f;">';
} }
$license_data['email_content'] .= '<td><a href="'.config('app.url').'/admin/licenses/'.$license->id.'/view">'; $license_data['email_content'] .= '<td><a href="'.config('app.url').'/admin/licenses/'.$license->id.'/view">';
$license_data['email_content'] .= $license->name.'</a></td>'; $license_data['email_content'] .= $license->name.'</a></td>';
$license_data['email_content'] .= '<td>'.$license->expiration_date.'</td>'; $license_data['email_content'] .= '<td>'.$license->expiration_date.'</td>';
$license_data['email_content'] .= '<td>'.$difference.' days</td>'; $license_data['email_content'] .= '<td>'.$difference.' days</td>';
$license_data['email_content'] .= '</tr>'; $license_data['email_content'] .= '</tr>';
} }
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) { if (count($expiring_assets) > 0) {
\Mail::send('emails.expiring-assets-report', $asset_data, function ($m) { \Mail::send('emails.expiring-assets-report', $asset_data, function ($m) {
$m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name); $m->to(explode(',', Setting::getSettings()->alert_email), Setting::getSettings()->site_name);
$m->subject('Expiring Assets Report'); $m->subject('Expiring Assets Report');
}); });
} }
if (count($expiring_licenses) > 0) { if (count($expiring_licenses) > 0) {
\Mail::send('emails.expiring-licenses-report', $license_data, function ($m) { \Mail::send('emails.expiring-licenses-report', $license_data, function ($m) {
$m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name); $m->to(explode(',', Setting::getSettings()->alert_email), Setting::getSettings()->site_name);
$m->subject('Expiring Licenses Report'); $m->subject('Expiring Licenses Report');
}); });
} }
} else { } else {
if (Setting::getSettings()->alert_email=='') { if (Setting::getSettings()->alert_email=='') {
echo "Could not send email. No alert email configured in settings. \n"; echo "Could not send email. No alert email configured in settings. \n";
} elseif (Setting::getSettings()->alerts_enabled!=1) { } elseif (Setting::getSettings()->alerts_enabled!=1) {
echo "Alerts are disabled in the settings. No mail will be sent. \n"; echo "Alerts are disabled in the settings. No mail will be sent. \n";
} }
}
}
}
}
} }

View file

@ -48,22 +48,21 @@ class SendInventoryAlerts extends Command
$data['count'] = count($data['data']); $data['count'] = count($data['data']);
if (count($data['data']) > 0) { if (count($data['data']) > 0) {
\Mail::send('emails.low-inventory', $data, function ($m) { \Mail::send('emails.low-inventory', $data, function ($m) {
$m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name); $m->to(explode(',', Setting::getSettings()->alert_email), Setting::getSettings()->site_name);
$m->subject('Low Inventory Report'); $m->subject('Low Inventory Report');
}); });
} }
} else { } else {
if (Setting::getSettings()->alert_email=='') { if (Setting::getSettings()->alert_email=='') {
echo "Could not send email. No alert email configured in settings. \n"; echo "Could not send email. No alert email configured in settings. \n";
} elseif (Setting::getSettings()->alerts_enabled!=1) { } elseif (Setting::getSettings()->alerts_enabled!=1) {
echo "Alerts are disabled in the settings. No mail will be sent. \n"; echo "Alerts are disabled in the settings. No mail will be sent. \n";
} }
} }
} }
} }

View file

@ -4,44 +4,42 @@ namespace App\Console\Commands;
use Illuminate\Console\Command; use Illuminate\Console\Command;
class SystemBackup extends Command { class SystemBackup extends Command
{
/** /**
* The console command name. * The console command name.
* *
* @var string * @var string
*/ */
protected $name = 'snipeit:backup'; protected $name = 'snipeit:backup';
/** /**
* The console command description. * The console command description.
* *
* @var string * @var string
*/ */
protected $description = 'This command creates a database dump and zips up all of the uploaded files in the upload directories.'; 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');
}
/**
* 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');
}
} }

View file

@ -6,7 +6,8 @@ use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Console\Command; use Illuminate\Console\Command;
class Versioning extends Command { class Versioning extends Command
{
/** /**
* The console command name. * The console command name.
@ -45,14 +46,14 @@ class Versioning extends Command {
// The git's output // The git's output
// get the argument passed in the git command // get the argument passed in the git command
$hash_version = $this->argument('app_version'); $hash_version = $this->argument('app_version');
// discard the commit hash // discard the commit hash
$version = explode('-', $hash_version); $version = explode('-', $hash_version);
$realVersion = $version[0] . '-' . $version[1]; $realVersion = $version[0] . '-' . $version[1];
// save the version array to a variable // save the version array to a variable
$array = var_export(array('app_version' => $realVersion,'hash_version' => $hash_version), true); $array = var_export(array('app_version' => $realVersion,'hash_version' => $hash_version), true);
// Construct our file content // Construct our file content

View file

@ -52,7 +52,7 @@ class AccessoriesController extends Controller
public function getCreate(Request $request) public function getCreate(Request $request)
{ {
// Show the page // Show the page
$category_list = Helper::categoryList('accessory'); $category_list = Helper::categoryList('accessory');
$company_list = Helper::companyList(); $company_list = Helper::companyList();
$location_list = Helper::locationsList(); $location_list = Helper::locationsList();
return View::make('accessories/edit') return View::make('accessories/edit')

View file

@ -110,10 +110,10 @@ class AssetModelsController extends Controller
$image = Input::file('image'); $image = Input::file('image');
$file_name = str_random(25).".".$image->getClientOriginalExtension(); $file_name = str_random(25).".".$image->getClientOriginalExtension();
$path = public_path('uploads/models/'.$file_name); $path = public_path('uploads/models/'.$file_name);
Image::make($image->getRealPath())->resize(500, null, function ($constraint) { Image::make($image->getRealPath())->resize(500, null, function ($constraint) {
$constraint->aspectRatio(); $constraint->aspectRatio();
$constraint->upsize(); $constraint->upsize();
})->save($path); })->save($path);
$model->image = $file_name; $model->image = $file_name;
} }

View file

@ -80,16 +80,17 @@ class AssetsController extends Controller
* @since [v3.0] * @since [v3.0]
* @return Redirect * @return Redirect
*/ */
public function getAssetByTag() { public function getAssetByTag()
{
if (Input::get('topsearch')=="true") { if (Input::get('topsearch')=="true") {
$topsearch = true; $topsearch = true;
} else { } else {
$topsearch = false; $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()->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')) { if (Input::has('image')) {
$image = Input::get('image'); $image = Input::get('image');
$header = explode(';', $image, 2)[0]; $header = explode(';', $image, 2)[0];
$extension = substr( $header, strpos($header, '/')+1); $extension = substr($header, strpos($header, '/')+1);
$image = substr( $image, strpos($image, ',')+1); $image = substr($image, strpos($image, ',')+1);
$file_name = str_random(25).".".$extension; $file_name = str_random(25).".".$extension;
$path = public_path('uploads/assets/'.$file_name); $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. // FIXME: No idea why this is returning a Builder error on db_column_name.
// Need to investigate and fix. Using static method for now. // Need to investigate and fix. Using static method for now.
$model = AssetModel::find($request->get('model_id')); $model = AssetModel::find($request->get('model_id'));
if($model->fieldset) if ($model->fieldset) {
{ foreach ($model->fieldset->fields as $field) {
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))); $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')) { if (Input::has('image')) {
$image = $request->input('image'); $image = $request->input('image');
$header = explode(';', $image, 2)[0]; $header = explode(';', $image, 2)[0];
$extension = substr( $header, strpos($header, '/')+1); $extension = substr($header, strpos($header, '/')+1);
$image = substr( $image, strpos($image, ',')+1); $image = substr($image, strpos($image, ',')+1);
$file_name = str_random(25).".".$extension; $file_name = str_random(25).".".$extension;
$path = public_path('uploads/assets/'.$file_name); $path = public_path('uploads/assets/'.$file_name);
Image::make($image)->resize(500, 500, function ($constraint) { Image::make($image)->resize(500, 500, function ($constraint) {
$constraint->aspectRatio(); $constraint->aspectRatio();
$constraint->upsize(); $constraint->upsize();
})->save($path); })->save($path);
$asset->image = $file_name; $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. // FIXME: No idea why this is returning a Builder error on db_column_name.
// Need to investigate and fix. Using static method for now. // Need to investigate and fix. Using static method for now.
$model = AssetModel::find($request->get('model_id')); $model = AssetModel::find($request->get('model_id'));
if($model->fieldset) if ($model->fieldset) {
{ foreach ($model->fieldset->fields as $field) {
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))); $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($field->name);
// LOG::debug(\App\Models\CustomField::name_to_db_name($field->name)); // LOG::debug(\App\Models\CustomField::name_to_db_name($field->name));
// LOG::debug($field->db_column_name()); // LOG::debug($field->db_column_name());
} }
} }
@ -753,7 +752,7 @@ class AssetsController extends Controller
if (isset($asset->id,$asset->asset_tag)) { if (isset($asset->id,$asset->asset_tag)) {
$barcode = new \Com\Tecnick\Barcode\Barcode(); $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'); 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. // Check if the uploads directory exists. If not, try to create it.
if(!file_exists($path)) if (!file_exists($path)) {
mkdir($path, 0755); mkdir($path, 0755);
}
if ($handle = opendir($path)) { if ($handle = opendir($path)) {
/* This is the correct way to loop over the directory. */ /* 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 redirect()->to('hardware')->with('error', trans('general.insufficient_permissions'));
} }
$return = Artisan::call('snipeit:import', $return = Artisan::call(
['filename'=> config('app.private_uploads').'/imports/assets/'.$filename, 'snipeit:import',
['filename'=> config('app.private_uploads').'/imports/assets/'.$filename,
'--email_format'=>'firstname.lastname', '--email_format'=>'firstname.lastname',
'--username_format'=>'firstname.lastname', '--username_format'=>'firstname.lastname',
'--web-importer' => true, '--web-importer' => true,
'--user_id' => Auth::user()->id '--user_id' => Auth::user()->id
]); ]
);
$display_output = Artisan::output(); $display_output = Artisan::output();
$file = config('app.private_uploads').'/imports/assets/'.str_replace('.csv', '', $filename).'-output-'.date("Y-m-d-his").'.txt'; $file = config('app.private_uploads').'/imports/assets/'.str_replace('.csv', '', $filename).'-output-'.date("Y-m-d-his").'.txt';
file_put_contents($file, $display_output); 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')); 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')); return redirect()->back()->with('import_errors', json_decode($display_output))->with('error', trans('admin/hardware/message.import.error'));
} }
dd("Shouldn't be here"); dd("Shouldn't be here");
@ -964,7 +966,7 @@ class AssetsController extends Controller
} elseif (isset($asset->id)) { } elseif (isset($asset->id)) {
// Restore the asset // 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')); return redirect()->route('hardware')->with('success', trans('admin/hardware/message.restore.success'));
} else { } else {

View file

@ -244,7 +244,7 @@ class CategoriesController extends Controller
public function getDatatable() public function getDatatable()
{ {
// Grab all the categories // Grab all the categories
$categories = Category::with('assets', 'accessories', 'consumables','components'); $categories = Category::with('assets', 'accessories', 'consumables', 'components');
if (Input::has('search')) { if (Input::has('search')) {
$categories = $categories->TextSearch(e(Input::get('search'))); $categories = $categories->TextSearch(e(Input::get('search')));
@ -300,7 +300,8 @@ class CategoriesController extends Controller
return $data; return $data;
} }
public function getDataViewAssets($categoryID) { public function getDataViewAssets($categoryID)
{
$category = Category::with('assets.company')->find($categoryID); $category = Category::with('assets.company')->find($categoryID);
$category_assets = $category->assets(); $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 = Category::with('accessories.company')->find($categoryID);
$category_assets = $category->accessories; $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 = Category::with('accessories.company')->find($categoryID);
$category_assets = $category->consumables; $category_assets = $category->consumables;
@ -474,7 +477,8 @@ class CategoriesController extends Controller
return $data; return $data;
} }
public function getDataViewComponent($categoryID) { public function getDataViewComponent($categoryID)
{
$category = Category::with('accessories.company')->find($categoryID); $category = Category::with('accessories.company')->find($categoryID);
$category_assets = $category->components; $category_assets = $category->components;
@ -525,7 +529,4 @@ class CategoriesController extends Controller
$data = array('total' => $count, 'rows' => $rows); $data = array('total' => $count, 'rows' => $rows);
return $data; return $data;
} }
} }

View file

@ -260,7 +260,8 @@ class CustomFieldsController extends Controller
* @since [v3.0] * @since [v3.0]
* @return Array * @return Array
*/ */
public function postReorder($id) { public function postReorder($id)
{
$fieldset=CustomFieldset::find($id); $fieldset=CustomFieldset::find($id);
$fields = array(); $fields = array();

View file

@ -11,7 +11,6 @@ use Str;
use View; use View;
use Auth; use Auth;
/** /**
* This controller handles all actions related to Depreciations for * This controller handles all actions related to Depreciations for
* the Snipe-IT Asset Management application. * the Snipe-IT Asset Management application.

View file

@ -93,7 +93,7 @@ class GroupsController extends Controller
$permissions = config('permissions'); $permissions = config('permissions');
$groupPermissions = $group->decodePermissions(); $groupPermissions = $group->decodePermissions();
$selected_array = Helper::selectedPermissionsArray($permissions, $groupPermissions); $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'));
} }
/** /**

View file

@ -156,16 +156,16 @@ class LicensesController extends Controller
$insertedId = $license->id; $insertedId = $license->id;
// Save the license seat data // Save the license seat data
DB::transaction(function() use (&$insertedId,&$license) { DB::transaction(function () use (&$insertedId, &$license) {
for ($x=0; $x<$license->seats; $x++) { for ($x=0; $x<$license->seats; $x++) {
$license_seat = new LicenseSeat(); $license_seat = new LicenseSeat();
$license_seat->license_id = $insertedId; $license_seat->license_id = $insertedId;
$license_seat->user_id = Auth::user()->id; $license_seat->user_id = Auth::user()->id;
$license_seat->assigned_to = null; $license_seat->assigned_to = null;
$license_seat->notes = null; $license_seat->notes = null;
$license_seat->save(); $license_seat->save();
} }
}); });
// Redirect to the new license page // Redirect to the new license page

View file

@ -370,7 +370,7 @@ class LocationsController extends Controller
public function getDataViewUsers($locationID) public function getDataViewUsers($locationID)
{ {
$location = Location::find($locationID); $location = Location::find($locationID);
$users = User::where('location_id','=',$location->id); $users = User::where('location_id', '=', $location->id);
if (Input::has('search')) { if (Input::has('search')) {
$users = $users->TextSearch(e(Input::get('search'))); $users = $users->TextSearch(e(Input::get('search')));

View file

@ -110,7 +110,7 @@ class ReportsController extends Controller
->orderBy('created_at', 'DESC') ->orderBy('created_at', 'DESC')
->get(); ->get();
return View::make('reports/asset', compact('assets'))->with('settings',$settings); return View::make('reports/asset', compact('assets'))->with('settings', $settings);
} }
/** /**

View file

@ -49,7 +49,7 @@ class SettingsController extends Controller
$start_settings['db_error'] = $e->getMessage(); $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; $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"])); $owner = posix_getpwuid(fileowner($_SERVER["SCRIPT_FILENAME"]));
$start_settings['owner'] = $owner['name']; $start_settings['owner'] = $owner['name'];
} else { // Windows } else { // Windows
@ -552,7 +552,7 @@ class SettingsController extends Controller
{ {
if (!config('app.lock_passwords')) { if (!config('app.lock_passwords')) {
if (Input::get('confirm_purge')=='DELETE') { 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(); $output = Artisan::output();
return View::make('settings/purge') return View::make('settings/purge')
->with('output', $output)->with('success', trans('admin/settings/message.purge.success')); ->with('output', $output)->with('success', trans('admin/settings/message.purge.success'));

View file

@ -33,7 +33,6 @@ use URL;
use View; use View;
use Illuminate\Http\Request; use Illuminate\Http\Request;
/** /**
* This controller handles all actions related to Users for * This controller handles all actions related to Users for
* the Snipe-IT Asset Management application. * 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::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->first_name = e($request->input('first_name'));
$user->last_name = e($request->input('last_name')); $user->last_name = e($request->input('last_name'));
$user->locale = e($request->input('locale')); $user->locale = e($request->input('locale'));
if (Input::has('username')) { if (Input::has('username')) {
$user->username = e($request->input('username')); $user->username = e($request->input('username'));
} }
$user->email = e($request->input('email')); $user->email = e($request->input('email'));
$user->employee_num = e($request->input('employee_num')); $user->employee_num = e($request->input('employee_num'));
@ -431,7 +430,7 @@ class UsersController extends Controller
//print_r($licenses); //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(); // $users = Company::scopeCompanyables($users)->get();
return View::make('users/confirm-bulk-delete', compact('users', 'statuslabel_list')); return View::make('users/confirm-bulk-delete', compact('users', 'statuslabel_list'));
@ -523,7 +522,7 @@ class UsersController extends Controller
$logaction->logaction('checkin from'); $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) { foreach ($users as $user) {
$user->accessories()->sync(array()); $user->accessories()->sync(array());
@ -553,22 +552,22 @@ class UsersController extends Controller
{ {
// Get user information // Get user information
if (!$user = User::onlyTrashed()->find($id)) { if (!$user = User::onlyTrashed()->find($id)) {
return redirect()->route('users')->with('error', trans('admin/users/messages.user_not_found')); return redirect()->route('users')->with('error', trans('admin/users/messages.user_not_found'));
} }
if (!Company::isCurrentUserHasAccess($user)) { if (!Company::isCurrentUserHasAccess($user)) {
return redirect()->route('users')->with('error', trans('general.insufficient_permissions')); 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 { } else {
return redirect()->route('users')->with('error', 'User could not be restored.');
// 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.');
}
} }
}
} }
@ -698,8 +697,8 @@ class UsersController extends Controller
->with('company_list', $company_list) ->with('company_list', $company_list)
->with('manager_list', $manager_list) ->with('manager_list', $manager_list)
->with('user', $user) ->with('user', $user)
->with('groups',$groups) ->with('groups', $groups)
->with('userGroups',$userGroups) ->with('userGroups', $userGroups)
->with('clone_user', $user_to_clone); ->with('clone_user', $user_to_clone);
} catch (UserNotFoundException $e) { } catch (UserNotFoundException $e) {
// Prepare the error message // Prepare the error message
@ -1193,29 +1192,29 @@ class UsersController extends Controller
$global_count = 0; $global_count = 0;
// Perform the search // Perform the search
do { do {
// Paginate (non-critical, if not supported by server) // Paginate (non-critical, if not supported by server)
ldap_control_paged_result($ldapconn, $page_size, false, $cookie); 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) { if (!$search_results) {
return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_search').ldap_error($ldapconn)); return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_search').ldap_error($ldapconn));
} }
// Get results from page // Get results from page
$results = ldap_get_entries($ldapconn, $search_results); $results = ldap_get_entries($ldapconn, $search_results);
if (!$results) { if (!$results) {
return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_get_entries').ldap_error($ldapconn)); return redirect()->route('users')->with('error', trans('admin/users/message.error.ldap_could_not_get_entries').ldap_error($ldapconn));
} }
// Add results to result set // Add results to result set
$global_count += $results['count']; $global_count += $results['count'];
$result_set = array_merge($result_set, $results); $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 // Clean up after search

View file

@ -59,7 +59,7 @@ class ViewAssetsController extends Controller
public function getRequestableIndex() 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')); return View::make('account/requestable-assets', compact('user', 'assets'));
} }
@ -143,7 +143,7 @@ class ViewAssetsController extends Controller
public function getAcceptAsset($logID = null) 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'; echo 'no record';
//return redirect()->to('account')->with('error', trans('admin/hardware/message.does_not_exist')); //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 // 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 // Redirect to the asset management page
return redirect()->to('account/view-assets')->with('error', trans('admin/hardware/message.does_not_exist')); return redirect()->to('account/view-assets')->with('error', trans('admin/hardware/message.does_not_exist'));
} }

View file

@ -14,23 +14,23 @@ class CheckForSetup
public function handle($request, Closure $next, $guard = null) public function handle($request, Closure $next, $guard = null)
{ {
if (Setting::setupCompleted()) { if (Setting::setupCompleted()) {
if ($request->is('setup*')) {
return redirect(config('app.url'));
} else {
return $next($request);
}
if ($request->is('setup*')) {
return redirect(config('app.url'));
} else { } else {
if (!$request->is('setup*')) {
return redirect(config('app.url').'/setup')->with('Request',$request);
}
return $next($request); return $next($request);
} }
} else {
if (!$request->is('setup*')) {
return redirect(config('app.url').'/setup')->with('Request', $request);
}
return $next($request);
}
} }
} }

View file

@ -7,7 +7,6 @@ use Config;
use Route; use Route;
use Gate; use Gate;
class CheckPermissions class CheckPermissions
{ {
/** /**

View file

@ -5,6 +5,7 @@ namespace App\Http\Requests;
use App\Http\Requests\Request; use App\Http\Requests\Request;
use App\Models\AssetModel; use App\Models\AssetModel;
use Session; use Session;
class AssetRequest extends Request class AssetRequest extends Request
{ {
/** /**
@ -40,8 +41,7 @@ class AssetRequest extends Request
$model = AssetModel::find($this->request->get('model_id')); $model = AssetModel::find($this->request->get('model_id'));
if (($model) && ($model->fieldset)) if (($model) && ($model->fieldset)) {
{
$rules += $model->fieldset->validation_rules(); $rules += $model->fieldset->validation_rules();
} }

View file

@ -138,14 +138,22 @@ Route::group([ 'prefix' => 'api', 'middleware' => 'auth' ], function () {
Route::group([ 'prefix' => 'categories' ], function () { Route::group([ 'prefix' => 'categories' ], function () {
Route::get('list', [ 'as' => 'api.categories.list', 'uses' => 'CategoriesController@getDatatable' ]); Route::get('list', [ 'as' => 'api.categories.list', 'uses' => 'CategoriesController@getDatatable' ]);
Route::get( '{categoryID}/asset/view', Route::get(
[ 'as' => 'api.categories.asset.view', 'uses' => 'CategoriesController@getDataViewAssets' ] ); '{categoryID}/asset/view',
Route::get( '{categoryID}/accessory/view', [ 'as' => 'api.categories.asset.view', 'uses' => 'CategoriesController@getDataViewAssets' ]
[ 'as' => 'api.categories.accessory.view', 'uses' => 'CategoriesController@getDataViewAccessories' ] ); );
Route::get( '{categoryID}/consumable/view', Route::get(
[ 'as' => 'api.categories.consumable.view', 'uses' => 'CategoriesController@getDataViewConsumables' ] ); '{categoryID}/accessory/view',
Route::get( '{categoryID}/component/view', [ 'as' => 'api.categories.accessory.view', 'uses' => 'CategoriesController@getDataViewAccessories' ]
[ 'as' => 'api.categories.component.view', 'uses' => 'CategoriesController@getDataViewComponent' ] ); );
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) --*/ /*-- Suppliers API (mostly for creating new ones in-line while creating an asset) --*/

View file

@ -7,7 +7,7 @@ use Watson\Validating\ValidatingTrait;
/** /**
* Model for Accessories. * Model for Accessories.
* *
* @version v1.0 * @version v1.0
*/ */
class Accessory extends Model class Accessory extends Model

View file

@ -172,13 +172,14 @@ class Asset extends Depreciable
} }
public function getDetailedNameAttribute() { public function getDetailedNameAttribute()
if($this->assigned_user) { {
$user_name = $user->fullName(); if ($this->assigned_user) {
} else { $user_name = $user->fullName();
$user_name = "Unassigned"; } else {
} $user_name = "Unassigned";
return $this->asset_tag . ' - ' . $this->name . ' (' . $user_name . ') ' . $this->model->name; }
return $this->asset_tag . ' - ' . $this->name . ' (' . $user_name . ') ' . $this->model->name;
} }
public function validationRules($id = '0') public function validationRules($id = '0')
{ {
@ -542,13 +543,13 @@ class Asset extends Depreciable
public function scopeAssetsByLocation($query, $location) public function scopeAssetsByLocation($query, $location)
{ {
return $query->where(function ($query) use ($location) return $query->where(function ($query) use ($location) {
{
$query->whereHas('assigneduser', function ($query) use ($location) $query->whereHas('assigneduser', function ($query) use ($location) {
{
$query->where('users.location_id', '=', $location->id); $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->where('assets.rtd_location_id', '=', $location->id);
$query->whereNull('assets.assigned_to'); $query->whereNull('assets.assigned_to');
}); });
@ -642,7 +643,7 @@ class Asset extends Depreciable
return $query->where('requestable', '=', 1) return $query->where('requestable', '=', 1)
->whereHas('assetstatus', function ($query) { ->whereHas('assetstatus', function ($query) {
$query->where('deployable', '=', 1) $query->where('deployable', '=', 1)
->where('pending', '=', 0) ->where('pending', '=', 0)
->where('archived', '=', 0); ->where('archived', '=', 0);
}); });

View file

@ -129,7 +129,7 @@ final class Company extends Model
public static function scopeCompanyables($query, $column = 'company_id') 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; return $query;
} else { } else {
return static::scopeCompanyablesDirectly($query, $column); return static::scopeCompanyablesDirectly($query, $column);

View file

@ -37,7 +37,4 @@ class Group extends Model
{ {
return json_decode($this->permissions, true); return json_decode($this->permissions, true);
} }
} }

View file

@ -55,22 +55,23 @@ class Setting extends Model
return $static_cache; return $static_cache;
} }
public static function setupCompleted() { public static function setupCompleted()
{
$users_table_exists = Schema::hasTable('users'); $users_table_exists = Schema::hasTable('users');
$settings_table_exists = Schema::hasTable('settings'); $settings_table_exists = Schema::hasTable('settings');
if ($users_table_exists && $settings_table_exists) { if ($users_table_exists && $settings_table_exists) {
$usercount = User::withTrashed()->count(); $usercount = User::withTrashed()->count();
if ($usercount > 0) { if ($usercount > 0) {
return true; return true;
}
return false;
} else {
return false;
} }
return false;
} else {
return false;
}
return false; return false;

View file

@ -56,12 +56,12 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
$user_permissions = json_decode($this->permissions, true); $user_permissions = json_decode($this->permissions, true);
//If the user is explicitly granted, return false //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; return true;
} }
// If the user is explicitly denied, return false // 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; return false;
} }
@ -76,7 +76,8 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
return false; return false;
} }
public function isSuperUser() { public function isSuperUser()
{
if (!$user_permissions = json_decode($this->permissions, true)) { if (!$user_permissions = json_decode($this->permissions, true)) {
return false; return false;
} }