Skip to content

Commit

Permalink
Merge branch 'snipe-develop' into added-localized-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
nuraeil committed Nov 16, 2021
2 parents 6b28018 + 6feb39f commit 74ed790
Show file tree
Hide file tree
Showing 34 changed files with 1,442 additions and 647 deletions.
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ RUN \
&& rm -r "/var/www/html/storage/app/backups" && ln -fs "/var/lib/snipeit/dumps" "/var/www/html/storage/app/backups" \
&& mkdir -p "/var/lib/snipeit/keys" && ln -fs "/var/lib/snipeit/keys/oauth-private.key" "/var/www/html/storage/oauth-private.key" \
&& ln -fs "/var/lib/snipeit/keys/oauth-public.key" "/var/www/html/storage/oauth-public.key" \
&& ln -fs "/var/lib/snipeit/keys/ldap_client_tls.cert" "/var/www/html/storage/ldap_client_tls.cert" \
&& ln -fs "/var/lib/snipeit/keys/ldap_client_tls.key" "/var/www/html/storage/ldap_client_tls.key" \
&& chown docker "/var/lib/snipeit/keys/" \
&& chown -h docker "/var/www/html/storage/" \
&& chmod +x /var/www/html/artisan \
Expand Down
36 changes: 26 additions & 10 deletions app/Console/Commands/RestoreFromBackup.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ class RestoreFromBackup extends Command
*/
protected $signature = 'snipeit:restore
{--force : Skip the danger prompt; assuming you hit "y"}
{filename : The zip file to be migrated}
{filename : The full path of the .zip file to be migrated}
{--no-progress : Don\'t show a progress bar}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Restore from a previously created backup';
protected $description = 'Restore from a previously created Snipe-IT backup file';

/**
* Create a new command instance.
Expand All @@ -34,6 +34,8 @@ public function __construct()
parent::__construct();
}

public static $buffer_size = 1024 * 1024; // use a 1MB buffer, ought to work fine for most cases?
/**
* Execute the console command.
*
Expand All @@ -42,7 +44,10 @@ public function __construct()
public function handle()
{
$dir = getcwd();
echo "Current working directory is: $dir\n";
if( $dir != base_path() ) { // usually only the case when running via webserver, not via command-line
\Log::debug("Current working directory is: $dir, changing directory to: ".base_path());
chdir(base_path()); // TODO - is this *safe* to change on a running script?!
}
//
$filename = $this->argument('filename');

Expand All @@ -67,7 +72,7 @@ public function handle()
ZipArchive::ER_INCONS => 'Zip archive inconsistent.',
ZipArchive::ER_INVAL => 'Invalid argument.',
ZipArchive::ER_MEMORY => 'Malloc failure.',
ZipArchive::ER_NOENT => 'No such file.',
ZipArchive::ER_NOENT => 'No such file ('.$filename.') in directory '.$dir.'.',
ZipArchive::ER_NOZIP => 'Not a zip archive.',
ZipArchive::ER_OPEN => "Can't open file.",
ZipArchive::ER_READ => 'Read error.',
Expand Down Expand Up @@ -144,7 +149,7 @@ public function handle()
continue;
}
if (@pathinfo($raw_path)['extension'] == 'sql') {
echo "Found a sql file!\n";
\Log::debug("Found a sql file!");
$sqlfiles[] = $raw_path;
$sqlfile_indices[] = $i;
continue;
Expand Down Expand Up @@ -206,7 +211,13 @@ public function handle()

$env_vars = getenv();
$env_vars['MYSQL_PWD'] = config('database.connections.mysql.password');
$proc_results = proc_open('mysql -h '.escapeshellarg(config('database.connections.mysql.host')).' -u '.escapeshellarg(config('database.connections.mysql.username')).' '.escapeshellarg(config('database.connections.mysql.database')), // yanked -p since we pass via ENV
// TODO notes: we are stealing the dump_binary_path (which *probably* also has your copy of the mysql binary in it. But it might not, so we might need to extend this)
// we unilaterally prepend a slash to the `mysql` command. This might mean your path could look like /blah/blah/blah//mysql - which should be fine. But maybe in some environments it isn't?
$mysql_binary = config('database.connections.mysql.dump.dump_binary_path').'/mysql';
if( ! file_exists($mysql_binary) ) {
return $this->error("mysql tool at: '$mysql_binary' does not exist, cannot restore. Please edit DB_DUMP_PATH in your .env to point to a directory that contains the mysqldump and mysql binary");
}
$proc_results = proc_open("$mysql_binary -h ".escapeshellarg(config('database.connections.mysql.host')).' -u '.escapeshellarg(config('database.connections.mysql.username')).' '.escapeshellarg(config('database.connections.mysql.database')), // yanked -p since we pass via ENV
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
$pipes,
null,
Expand All @@ -233,9 +244,10 @@ public function handle()

return false;
}

while (($buffer = fgets($sql_contents)) !== false) {
//$this->info("Buffer is: '$buffer'");
$bytes_read = 0;
while (($buffer = fgets($sql_contents, self::$buffer_size)) !== false) {
$bytes_read += strlen($buffer);
// \Log::debug("Buffer is: '$buffer'");
$bytes_written = fwrite($pipes[0], $buffer);
if ($bytes_written === false) {
$stdout = fgets($pipes[1]);
Expand All @@ -246,6 +258,10 @@ public function handle()
return false;
}
}
if (!feof($sql_contents) || $bytes_read == 0) {
return $this->error("Not at end of file for sql file, or zero bytes read. aborting!");
}

fclose($pipes[0]);
fclose($sql_contents);

Expand Down Expand Up @@ -273,7 +289,7 @@ public function handle()
$fp = $za->getStream($ugly_file_name);
//$this->info("Weird problem, here are file details? ".print_r($file_details,true));
$migrated_file = fopen($file_details['dest'].'/'.basename($pretty_file_name), 'w');
while (($buffer = fgets($fp)) !== false) {
while (($buffer = fgets($fp, self::$buffer_size)) !== false) {
fwrite($migrated_file, $buffer);
}
fclose($migrated_file);
Expand Down
16 changes: 15 additions & 1 deletion app/Http/Controllers/Api/AssetsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ public function index(Request $request, $audit = null)
// case we override with the actual count, so we should return 0 items.
$offset = (($assets) && ($request->get('offset') > $assets->count())) ? $assets->count() : $request->get('offset', 0);


// Check to make sure the limit is not higher than the max allowed
((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results');

Expand Down Expand Up @@ -336,6 +337,7 @@ public function index(Request $request, $audit = null)
return (new $transformer)->transformAssets($assets, $total, $request);
}


/**
* Returns JSON with information about an asset (by tag) for detail view.
*
Expand Down Expand Up @@ -373,9 +375,19 @@ public function showBySerial(Request $request, $serial)
}
return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200);

$assets = Asset::with('assetstatus')->with('assignedTo');

if ($request->input('deleted', 'false') === 'true') {
$assets = $assets->withTrashed();
}

$assets = $assets->where('serial', $serial)->get();
if ($assets) {
return (new AssetsTransformer)->transformAssets($assets, $assets->count());
} else {
return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200);
}
}

/**
* Returns JSON with information about an asset for detail view.
Expand Down Expand Up @@ -677,6 +689,8 @@ public function destroy($id)
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 200);
}



/**
* Restore a soft-deleted asset.
*
Expand Down Expand Up @@ -899,7 +913,7 @@ public function audit(Request $request)
}
}

return response()->json(Helper::formatStandardApiResponse('error', ['asset_tag'=> e($request->input('asset_tag'))], 'Asset with tag '.$request->input('asset_tag').' not found'));
return response()->json(Helper::formatStandardApiResponse('error', ['asset_tag'=> e($request->input('asset_tag'))], 'Asset with tag '.e($request->input('asset_tag')).' not found'));



Expand Down
122 changes: 120 additions & 2 deletions app/Http/Controllers/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
use App\Models\User;
use App\Notifications\FirstAdminNotification;
use App\Notifications\MailTest;
use Artisan;
use Auth;
use Crypt;
use DB;
Expand All @@ -22,6 +21,8 @@
use Input;
use Redirect;
use Response;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Artisan;

/**
* This controller handles all actions related to Settings for
Expand Down Expand Up @@ -1018,17 +1019,25 @@ public function getBackups()
$backup_files = Storage::files($path);
$files_raw = [];


if (count($backup_files) > 0) {
for ($f = 0; $f < count($backup_files); $f++) {

// Skip dotfiles like .gitignore and .DS_STORE
if ((substr(basename($backup_files[$f]), 0, 1) != '.')) {
//$lastmodified = Carbon::parse(Storage::lastModified($backup_files[$f]))->toDatetimeString();
$file_timestamp = Storage::lastModified($backup_files[$f]);


$files_raw[] = [
'filename' => basename($backup_files[$f]),
'filesize' => Setting::fileSizeConvert(Storage::size($backup_files[$f])),
'modified' => Storage::lastModified($backup_files[$f]),
'modified_value' => $file_timestamp,
'modified_display' => Helper::getFormattedDateObject($file_timestamp, $type = 'datetime', false),

];
}

}
}

Expand Down Expand Up @@ -1128,6 +1137,115 @@ public function deleteFile($filename = null)
}
}


/**
* Uploads a backup file
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v6.0]
*
* @return Redirect
*/

public function postUploadBackup(Request $request) {

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

$rules = [
'file' => 'required|mimes:zip|max:'.$max_file_size,
];

$validator = \Validator::make($request->all(), $rules);

if ($validator->passes()) {

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

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

return redirect()->route('settings.backups.index')->with('success', 'File uploaded');
} else {
return redirect()->route('settings.backups.index')->withErrors($request->getErrors());
}
}

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



}

/**
* Restore the backup file.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v6.0]
*
* @return View
*/
public function postRestore($filename = null)
{

if (! config('app.lock_passwords')) {
$path = 'app/backups';

if (Storage::exists($path.'/'.$filename)) {

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


// TODO: run a backup

// TODO: add db:wipe


// run the restore command
Artisan::call('snipeit:restore',
[
'--force' => true,
'--no-progress' => true,
'filename' => storage_path($path).'/'.$filename
]);

$output = Artisan::output();


// If it's greater than 300, it probably worked
if (strlen($output) > 300) {
\Auth::logout();
return redirect()->route('login')->with('success', 'Your system has been restored. Please login again.');
} else {
return redirect()->route('settings.backups.index')->with('error', $output);

}
//dd($output);

// TODO: insert the user if they are not there in the old one




// log the user out



} else {
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
}
} else {
return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
}
}

/**
* Return a form to allow a super admin to update settings.
*
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Requests/AssetFileRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function authorize()
*/
public function rules()
{
$max_file_size = Helper::file_upload_max_size();
$max_file_size = \App\Helpers\Helper::file_upload_max_size();

return [
'file.*' => 'required|mimes:png,gif,jpg,svg,jpeg,doc,docx,pdf,txt,zip,rar,xls,xlsx,lic,xml,rtf,webp|max:'.$max_file_size,
Expand Down
5 changes: 0 additions & 5 deletions app/Http/Requests/ImageUploadRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,6 @@ public function handleImages($item, $w = 600, $form_fieldname = null, $path = nu
$use_db_field = $db_fieldname;
}

\Log::info('Image path is: '.$path);
\Log::debug('Type is: '.$type);
\Log::debug('Form fieldname is: '.$form_fieldname);
\Log::debug('DB fieldname is: '.$use_db_field);
\Log::debug('Trying to upload to '. $path);

// ConvertBase64ToFiles just changes object type,
// as it cannot currently insert files to $this->files
Expand Down
Loading

0 comments on commit 74ed790

Please sign in to comment.