snipe-it/app/Http/Controllers/Assets/AssetsController.php

926 lines
37 KiB
PHP
Raw Normal View History

2016-03-25 01:18:05 -07:00
<?php
namespace App\Http\Controllers\Assets;
2016-03-25 01:18:05 -07:00
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
use App\Http\Requests\ImageUploadRequest;
2016-03-25 01:18:05 -07:00
use App\Models\Actionlog;
use App\Models\Manufacturer;
2023-07-13 20:48:51 -07:00
use Illuminate\Support\Facades\Log;
2016-03-25 01:18:05 -07:00
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\CheckoutRequest;
2016-03-25 01:18:05 -07:00
use App\Models\Company;
use App\Models\Location;
use App\Models\Setting;
2023-05-15 11:52:57 -07:00
use App\Models\Statuslabel;
2016-03-25 01:18:05 -07:00
use App\Models\User;
2023-07-13 20:48:51 -07:00
use Illuminate\Support\Facades\Auth;
2022-11-01 05:02:12 -07:00
use App\View\Label;
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
use Carbon\Carbon;
2023-07-13 20:48:51 -07:00
use Illuminate\Support\Facades\DB;
2023-09-12 16:11:36 -07:00
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Gate;
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
use Illuminate\Http\Request;
2023-07-13 20:48:51 -07:00
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
2023-07-13 20:48:51 -07:00
use Illuminate\Support\Facades\Validator;
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
use League\Csv\Reader;
2023-09-12 16:11:36 -07:00
use Illuminate\Support\Facades\Redirect;
2016-03-25 01:18:05 -07:00
/**
2016-04-07 13:21:09 -07:00
* This class controls all actions related to assets for
* the Snipe-IT Asset Management application.
*
* @version v1.0
* @author [A. Gianotto] [<snipe@snipe.net>]
2016-03-25 01:18:05 -07:00
*/
class AssetsController extends Controller
{
protected $qrCodeDimensions = ['height' => 3.5, 'width' => 3.5];
protected $barCodeDimensions = ['height' => 2, 'width' => 22];
2016-03-25 01:18:05 -07:00
public function __construct()
{
$this->middleware('auth');
parent::__construct();
}
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the assets listing, which is generated in getDatatable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see AssetController::getDatatable() method that generates the JSON response
* @since [v1.0]
* @param Request $request
* @return View
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function index(Request $request)
2016-03-25 01:18:05 -07:00
{
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
$this->authorize('index', Asset::class);
$company = Company::find($request->input('company_id'));
return view('hardware/index')->with('company', $company);
2016-03-25 01:18:05 -07:00
}
/**
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
* Returns a view that presents a form to create a new asset.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param Request $request
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
* @return View
* @internal param int $model_id
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
*/
public function create(Request $request)
2016-03-25 01:18:05 -07:00
{
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
$this->authorize('create', Asset::class);
$view = View::make('hardware/edit')
->with('statuslabel_list', Helper::statusLabelList())
->with('item', new Asset)
->with('statuslabel_types', Helper::statusTypeList());
2016-03-25 01:18:05 -07:00
2019-05-23 17:39:50 -07:00
if ($request->filled('model_id')) {
$selected_model = AssetModel::find($request->input('model_id'));
2016-03-25 01:18:05 -07:00
$view->with('selected_model', $selected_model);
}
2016-03-25 01:18:05 -07:00
return $view;
}
/**
* Validate and process new asset form data.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return Redirect
*/
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
public function store(ImageUploadRequest $request)
2016-03-25 01:18:05 -07:00
{
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
$this->authorize(Asset::class);
// Handle asset tags - there could be one, or potentially many.
// This is only necessary on create, not update, since bulk editing is handled
// differently
$asset_tags = $request->input('asset_tags');
2020-06-16 16:06:25 -07:00
$settings = Setting::getSettings();
$success = false;
$serials = $request->input('serials');
2016-03-25 01:18:05 -07:00
for ($a = 1; $a <= count($asset_tags); $a++) {
$asset = new Asset();
$asset->model()->associate(AssetModel::find($request->input('model_id')));
$asset->name = $request->input('name');
2020-04-21 03:58:31 -07:00
// Check for a corresponding serial
if (($serials) && (array_key_exists($a, $serials))) {
$asset->serial = $serials[$a];
}
2019-08-14 23:13:23 -07:00
if (($asset_tags) && (array_key_exists($a, $asset_tags))) {
$asset->asset_tag = $asset_tags[$a];
}
2016-03-25 01:18:05 -07:00
$asset->company_id = Company::getIdForCurrentUser($request->input('company_id'));
$asset->model_id = $request->input('model_id');
$asset->order_number = $request->input('order_number');
$asset->notes = $request->input('notes');
$asset->user_id = Auth::id();
$asset->archived = '0';
$asset->physical = '1';
$asset->depreciate = '0';
$asset->status_id = request('status_id');
$asset->warranty_months = request('warranty_months', null);
$asset->purchase_cost = request('purchase_cost');
$asset->purchase_date = request('purchase_date', null);
$asset->asset_eol_date = request('asset_eol_date', null);
$asset->assigned_to = request('assigned_to', null);
$asset->supplier_id = request('supplier_id', null);
$asset->requestable = request('requestable', 0);
$asset->rtd_location_id = request('rtd_location_id', null);
$asset->byod = request('byod', 0);
if (! empty($settings->audit_interval)) {
$asset->next_audit_date = Carbon::now()->addMonths($settings->audit_interval)->toDateString();
}
if ($asset->assigned_to == '') {
$asset->location_id = $request->input('rtd_location_id', null);
}
2020-04-21 03:58:31 -07:00
// Create the image (if one was chosen.)
if ($request->has('image')) {
$asset = $request->handleImages($asset);
}
2016-03-25 01:18:05 -07:00
2020-04-21 03:58:31 -07:00
// Update custom fields in the database.
// Validation for these fields is handled through the AssetRequest form request
$model = AssetModel::find($request->get('model_id'));
2020-04-21 03:58:31 -07:00
if (($model) && ($model->fieldset)) {
foreach ($model->fieldset->fields as $field) {
if ($field->field_encrypted == '1') {
2020-04-21 03:58:31 -07:00
if (Gate::allows('admin')) {
if (is_array($request->input($field->db_column))) {
2023-07-13 20:48:51 -07:00
$asset->{$field->db_column} = Crypt::encrypt(implode(', ', $request->input($field->db_column)));
} else {
2023-07-13 20:48:51 -07:00
$asset->{$field->db_column} = Crypt::encrypt($request->input($field->db_column));
}
}
2020-04-21 03:58:31 -07:00
} else {
if (is_array($request->input($field->db_column))) {
$asset->{$field->db_column} = implode(', ', $request->input($field->db_column));
} else {
$asset->{$field->db_column} = $request->input($field->db_column);
}
2017-07-08 17:04:24 -07:00
}
}
2016-06-10 16:36:46 -07:00
}
// Validate the asset before saving
if ($asset->isValid() && $asset->save()) {
if (request('assigned_user')) {
$target = User::find(request('assigned_user'));
$location = $target->location_id;
} elseif (request('assigned_asset')) {
$target = Asset::find(request('assigned_asset'));
$location = $target->location_id;
} elseif (request('assigned_location')) {
$target = Location::find(request('assigned_location'));
$location = $target->id;
}
if (isset($target)) {
$asset->checkOut($target, Auth::user(), date('Y-m-d H:i:s'), $request->input('expected_checkin', null), 'Checked out on asset creation', $request->get('name'), $location);
}
$success = true;
}
}
if ($success) {
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
return redirect()->route('hardware.index')
->with('success-unescaped', trans('admin/hardware/message.create.success_linked', ['link' => route('hardware.show', $asset->id), 'id', 'tag' => $asset->asset_tag]));
2016-03-25 01:18:05 -07:00
}
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
return redirect()->back()->withInput()->withErrors($asset->getErrors());
2016-03-25 01:18:05 -07:00
}
public function getOptionCookie(Request $request){
$value = $request->cookie('optional_info');
echo $value;
return $value;
}
2016-03-25 01:18:05 -07:00
/**
* Returns a view that presents a form to edit an existing asset.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $assetId
* @since [v1.0]
* @return View
*/
public function edit($assetId = null)
2016-03-25 01:18:05 -07:00
{
if (! $item = Asset::find($assetId)) {
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
// Redirect to the asset management page with error
2016-12-15 20:02:47 -08:00
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
//Handles company checks and permissions.
$this->authorize($item);
2016-03-25 01:18:05 -07:00
2017-06-09 16:31:25 -07:00
return view('hardware/edit', compact('item'))
->with('statuslabel_list', Helper::statusLabelList())
2017-10-28 11:17:52 -07:00
->with('statuslabel_types', Helper::statusTypeList());
2016-03-25 01:18:05 -07:00
}
/**
* Returns a view that presents information about an asset for detail view.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $assetId
* @since [v1.0]
* @return View
*/
public function show($assetId = null)
{
$asset = Asset::withTrashed()->find($assetId);
$this->authorize('view', $asset);
$settings = Setting::getSettings();
if (isset($asset)) {
$audit_log = Actionlog::where('action_type', '=', 'audit')
->where('item_id', '=', $assetId)
->where('item_type', '=', Asset::class)
->orderBy('created_at', 'DESC')->first();
if ($asset->location) {
$use_currency = $asset->location->currency;
} else {
if ($settings->default_currency != '') {
$use_currency = $settings->default_currency;
} else {
$use_currency = trans('general.currency');
}
}
$qr_code = (object) [
'display' => $settings->qr_code == '1',
'url' => route('qr_code/hardware', $asset->id),
];
return view('hardware/view', compact('asset', 'qr_code', 'settings'))
->with('use_currency', $use_currency)->with('audit_log', $audit_log);
}
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
}
2016-03-25 01:18:05 -07:00
/**
* Validate and process asset edit form.
*
* @param int $assetId
* @return \Illuminate\Http\RedirectResponse|Redirect
*@since [v1.0]
* @author [A. Gianotto] [<snipe@snipe.net>]
*/
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
public function update(ImageUploadRequest $request, $assetId = null)
2016-03-25 01:18:05 -07:00
{
// Check if the asset exists
if (! $asset = Asset::find($assetId)) {
2016-03-25 01:18:05 -07:00
// Redirect to the asset management page with error
2016-12-15 20:02:47 -08:00
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
$this->authorize($asset);
2016-03-25 01:18:05 -07:00
$asset->status_id = $request->input('status_id', null);
$asset->warranty_months = $request->input('warranty_months', null);
2023-03-29 00:56:34 -07:00
$asset->purchase_cost = $request->input('purchase_cost', null);
2023-07-18 08:26:25 -07:00
$asset->purchase_date = $request->input('purchase_date', null);
if ($request->filled('purchase_date') && !$request->filled('asset_eol_date') && ($asset->model->eol > 0)) {
2023-07-18 08:26:25 -07:00
$asset->purchase_date = $request->input('purchase_date', null);
2023-07-13 20:48:51 -07:00
$asset->asset_eol_date = Carbon::parse($request->input('purchase_date'))->addMonths($asset->model->eol)->format('Y-m-d');
$asset->eol_explicit = false;
2023-07-17 12:44:09 -07:00
} elseif ($request->filled('asset_eol_date')) {
2023-09-13 11:51:14 -07:00
$asset->asset_eol_date = $request->input('asset_eol_date', null);
$months = Carbon::parse($asset->asset_eol_date)->diffInMonths($asset->purchase_date);
if($asset->model->eol) {
if($months != $asset->model->eol > 0) {
2023-09-13 11:51:14 -07:00
$asset->eol_explicit = true;
} else {
$asset->eol_explicit = false;
}
} else {
$asset->eol_explicit = true;
}
} elseif (!$request->filled('asset_eol_date') && (($asset->model->eol) == 0)) {
$asset->asset_eol_date = null;
$asset->eol_explicit = false;
2023-09-13 11:51:14 -07:00
}
$asset->supplier_id = $request->input('supplier_id', null);
$asset->expected_checkin = $request->input('expected_checkin', null);
2016-03-25 01:18:05 -07:00
// If the box isn't checked, it's not in the request at all.
2019-05-23 17:39:50 -07:00
$asset->requestable = $request->filled('requestable');
$asset->rtd_location_id = $request->input('rtd_location_id', null);
$asset->byod = $request->input('byod', 0);
2016-03-25 01:18:05 -07:00
2023-05-15 11:52:57 -07:00
$status = Statuslabel::find($asset->status_id);
if($status->archived){
$asset->assigned_to = null;
}
if ($asset->assigned_to == '') {
$asset->location_id = $request->input('rtd_location_id', null);
}
2019-05-23 17:39:50 -07:00
if ($request->filled('image_delete')) {
try {
unlink(public_path().'/uploads/assets/'.$asset->image);
$asset->image = '';
} catch (\Exception $e) {
2023-07-13 20:48:51 -07:00
Log::info($e);
}
2016-03-25 01:18:05 -07:00
}
// Update the asset data
$asset_tag = $request->input('asset_tags');
$serial = $request->input('serials');
$asset->name = $request->input('name');
$asset->serial = $serial[1];
$asset->company_id = Company::getIdForCurrentUser($request->input('company_id'));
$asset->model_id = $request->input('model_id');
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
$asset->order_number = $request->input('order_number');
$asset->asset_tag = $asset_tag[1];
$asset->notes = $request->input('notes');
$asset->physical = '1';
2016-03-25 01:18:05 -07:00
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
$asset = $request->handleImages($asset);
2016-03-25 01:18:05 -07:00
2016-06-10 16:36:46 -07:00
// Update custom fields in the database.
// Validation for these fields is handlded through the AssetRequest form request
// FIXME: No idea why this is returning a Builder error on db_column_name.
// Need to investigate and fix. Using static method for now.
$model = AssetModel::find($request->get('model_id'));
if (($model) && ($model->fieldset)) {
2016-06-22 12:27:41 -07:00
foreach ($model->fieldset->fields as $field) {
if ($field->field_encrypted == '1') {
if (Gate::allows('admin')) {
if (is_array($request->input($field->db_column))) {
2023-07-13 20:48:51 -07:00
$asset->{$field->db_column} = Crypt::encrypt(implode(', ', $request->input($field->db_column)));
} else {
2023-07-13 20:48:51 -07:00
$asset->{$field->db_column} = Crypt::encrypt($request->input($field->db_column));
}
}
} else {
if (is_array($request->input($field->db_column))) {
$asset->{$field->db_column} = implode(', ', $request->input($field->db_column));
} else {
$asset->{$field->db_column} = $request->input($field->db_column);
}
}
2016-06-10 16:36:46 -07:00
}
}
2016-03-25 01:18:05 -07:00
2016-03-25 01:18:05 -07:00
if ($asset->save()) {
return redirect()->route('hardware.show', $assetId)
->with('success', trans('admin/hardware/message.update.success'));
2016-03-25 01:18:05 -07:00
}
2019-12-06 11:07:13 -08:00
return redirect()->back()->withInput()->withErrors($asset->getErrors());
2016-03-25 01:18:05 -07:00
}
/**
* Delete a given asset (mark as deleted).
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $assetId
* @since [v1.0]
* @return Redirect
*/
public function destroy($assetId)
2016-03-25 01:18:05 -07:00
{
// Check if the asset exists
if (is_null($asset = Asset::find($assetId))) {
// Redirect to the asset management page with error
2016-12-15 20:02:47 -08:00
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
$this->authorize('delete', $asset);
2016-03-25 01:18:05 -07:00
DB::table('assets')
->where('id', $asset->id)
->update(['assigned_to' => null]);
2016-03-25 01:18:05 -07:00
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
if ($asset->image) {
try {
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
Storage::disk('public')->delete('assets'.'/'.$asset->image);
} catch (\Exception $e) {
2023-07-13 20:48:51 -07:00
Log::debug($e);
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
}
}
2016-03-25 01:18:05 -07:00
$asset->delete();
2016-12-15 20:02:47 -08:00
return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.delete.success'));
2016-03-25 01:18:05 -07:00
}
/**
* Searches the assets table by serial, and redirects if it finds one
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return Redirect
*/
public function getAssetBySerial(Request $request)
{
$topsearch = ($request->get('topsearch')=="true");
if (!$asset = Asset::where('serial', '=', $request->get('serial'))->first()) {
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
}
$this->authorize('view', $asset);
return redirect()->route('hardware.show', $asset->id)->with('topsearch', $topsearch);
}
2016-03-25 01:18:05 -07:00
/**
2020-04-21 03:58:31 -07:00
* Searches the assets table by asset tag, and redirects if it finds one
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return Redirect
*/
2023-01-31 22:56:23 -08:00
public function getAssetByTag(Request $request, $tag=null)
2016-03-25 01:18:05 -07:00
{
2022-11-01 05:02:12 -07:00
$tag = $tag ? $tag : $request->get('assetTag');
$topsearch = ($request->get('topsearch') == 'true');
2016-03-25 01:18:05 -07:00
2022-11-01 05:02:12 -07:00
if (! $asset = Asset::where('asset_tag', '=', $tag)->first()) {
2016-12-15 20:02:47 -08:00
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
Discussion: Moving to policies for controller based authorization (#3080) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations.
2016-12-19 11:04:28 -08:00
$this->authorize('view', $asset);
return redirect()->route('hardware.show', $asset->id)->with('topsearch', $topsearch);
2016-03-25 01:18:05 -07:00
}
2016-03-25 01:18:05 -07:00
/**
* Return a QR code for the asset
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $assetId
* @since [v1.0]
* @return Response
*/
2016-03-25 01:18:05 -07:00
public function getQrCode($assetId = null)
{
$settings = Setting::getSettings();
if ($settings->qr_code == '1') {
$asset = Asset::withTrashed()->find($assetId);
if ($asset) {
$size = Helper::barcodeDimensions($settings->barcode_type);
$qr_file = public_path().'/uploads/barcodes/qr-'.str_slug($asset->asset_tag).'-'.str_slug($asset->id).'.png';
if (isset($asset->id, $asset->asset_tag)) {
if (file_exists($qr_file)) {
$header = ['Content-type' => 'image/png'];
return response()->file($qr_file, $header);
} else {
$barcode = new \Com\Tecnick\Barcode\Barcode();
$barcode_obj = $barcode->getBarcodeObj($settings->barcode_type, route('hardware.show', $asset->id), $size['height'], $size['width'], 'black', [-2, -2, -2, -2]);
file_put_contents($qr_file, $barcode_obj->getPngData());
return response($barcode_obj->getPngData())->header('Content-type', 'image/png');
}
}
2016-03-25 01:18:05 -07:00
}
return 'That asset is invalid';
2016-03-25 01:18:05 -07:00
}
}
2016-05-19 19:12:42 -07:00
/**
* Return a 2D barcode for the asset
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $assetId
* @since [v1.0]
* @return Response
*/
public function getBarCode($assetId = null)
{
$settings = Setting::getSettings();
$asset = Asset::find($assetId);
$barcode_file = public_path().'/uploads/barcodes/'.str_slug($settings->alt_barcode).'-'.str_slug($asset->asset_tag).'.png';
2016-05-19 19:12:42 -07:00
if (isset($asset->id, $asset->asset_tag)) {
if (file_exists($barcode_file)) {
$header = ['Content-type' => 'image/png'];
return response()->file($barcode_file, $header);
} else {
// Calculate barcode width in pixel based on label width (inch)
$barcode_width = ($settings->labels_width - $settings->labels_display_sgutter) * 200.000000000001;
$barcode = new \Com\Tecnick\Barcode\Barcode();
try {
$barcode_obj = $barcode->getBarcodeObj($settings->alt_barcode, $asset->asset_tag, ($barcode_width < 300 ? $barcode_width : 300), 50);
file_put_contents($barcode_file, $barcode_obj->getPngData());
return response($barcode_obj->getPngData())->header('Content-type', 'image/png');
} catch (\Exception $e) {
2023-07-13 20:48:51 -07:00
Log::debug('The barcode format is invalid.');
return response(file_get_contents(public_path('uploads/barcodes/invalid_barcode.gif')))->header('Content-type', 'image/gif');
}
}
2016-05-19 19:12:42 -07:00
}
}
/**
* Return a label for an individual asset.
*
* @author [L. Swartzendruber] [<logan.swartzendruber@gmail.com>
* @param int $assetId
* @return View
*/
2020-04-21 03:58:31 -07:00
public function getLabel($assetId = null)
{
if (isset($assetId)) {
$asset = Asset::find($assetId);
2020-04-21 03:58:31 -07:00
$this->authorize('view', $asset);
2022-11-01 05:02:12 -07:00
return (new Label())
->with('assets', collect([ $asset ]))
->with('settings', Setting::getSettings())
2022-11-02 01:04:40 -07:00
->with('template', request()->get('template'))
2022-11-01 05:02:12 -07:00
->with('offset', request()->get('offset'))
2020-04-21 03:58:31 -07:00
->with('bulkedit', false)
->with('count', 0);
2016-05-19 19:12:42 -07:00
}
}
2016-03-25 01:18:05 -07:00
/**
* Returns a view that presents a form to clone an asset.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $assetId
* @since [v1.0]
* @return View
*/
2016-03-25 01:18:05 -07:00
public function getClone($assetId = null)
{
// Check if the asset exists
if (is_null($asset_to_clone = Asset::find($assetId))) {
// Redirect to the asset management page
2016-12-15 20:02:47 -08:00
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
2016-12-29 14:02:18 -08:00
$this->authorize('create', $asset_to_clone);
2016-03-25 01:18:05 -07:00
$asset = clone $asset_to_clone;
$asset->id = null;
$asset->asset_tag = '';
$asset->serial = '';
$asset->assigned_to = '';
2017-06-09 16:31:25 -07:00
return view('hardware/edit')
->with('statuslabel_list', Helper::statusLabelList())
->with('statuslabel_types', Helper::statusTypeList())
->with('item', $asset);
2016-03-25 01:18:05 -07:00
}
2016-08-12 16:01:59 -07:00
/**
* Return history import view
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return View
*/
public function getImportHistory()
{
$this->authorize('admin');
2017-06-09 16:31:25 -07:00
return view('hardware/history');
2016-08-12 16:01:59 -07:00
}
/**
* Import history
*
* This needs a LOT of love. It's done very inelegantly right now, and there are
* a ton of optimizations that could (and should) be done.
*
* Updated to respect checkin dates:
* No checkin column, assume all items are checked in (todays date)
* Checkin date in the past, update history.
* Checkin date in future or empty, check the item out to the user.
*
2016-08-12 16:01:59 -07:00
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.3]
* @return View
*/
public function postImportHistory(Request $request)
{
if (! $request->hasFile('user_import_csv')) {
2019-08-13 18:00:21 -07:00
return back()->with('error', 'No file provided. Please select a file for import and try again. ');
}
if (! ini_get('auto_detect_line_endings')) {
ini_set('auto_detect_line_endings', '1');
2016-08-12 16:01:59 -07:00
}
$csv = Reader::createFromPath($request->file('user_import_csv'));
2019-08-13 18:00:21 -07:00
$csv->setHeaderOffset(0);
$header = $csv->getHeader();
$isCheckinHeaderExplicit = in_array('checkin date', (array_map('strtolower', $header)));
2023-03-14 14:07:09 -07:00
try {
$results = $csv->getRecords();
} catch (\Exception $e) {
return back()->with('error', trans('general.error_in_import_file', ['error' => $e->getMessage()]));
2023-03-14 14:07:09 -07:00
}
$item = [];
$status = [];
$status['error'] = [];
$status['success'] = [];
2016-12-29 14:02:18 -08:00
foreach ($results as $row) {
2016-08-12 16:01:59 -07:00
if (is_array($row)) {
$row = array_change_key_case($row, CASE_LOWER);
$asset_tag = Helper::array_smart_fetch($row, 'asset tag');
if (! array_key_exists($asset_tag, $item)) {
$item[$asset_tag] = [];
2016-08-12 16:01:59 -07:00
}
$batch_counter = count($item[$asset_tag]);
$item[$asset_tag][$batch_counter]['checkout_date'] = Carbon::parse(Helper::array_smart_fetch($row, 'checkout date'))->format('Y-m-d H:i:s');
if ($isCheckinHeaderExplicit) {
//checkin date not empty, assume past transaction or future checkin date (expected)
if (! empty(Helper::array_smart_fetch($row, 'checkin date'))) {
$item[$asset_tag][$batch_counter]['checkin_date'] = Carbon::parse(Helper::array_smart_fetch($row, 'checkin date'))->format('Y-m-d H:i:s');
} else {
$item[$asset_tag][$batch_counter]['checkin_date'] = '';
}
} else {
//checkin header missing, assume data is unavailable and make checkin date explicit (now) so we don't encounter invalid state.
$item[$asset_tag][$batch_counter]['checkin_date'] = Carbon::parse(now())->format('Y-m-d H:i:s');
}
$item[$asset_tag][$batch_counter]['asset_tag'] = Helper::array_smart_fetch($row, 'asset tag');
$item[$asset_tag][$batch_counter]['name'] = Helper::array_smart_fetch($row, 'name');
$item[$asset_tag][$batch_counter]['email'] = Helper::array_smart_fetch($row, 'email');
2016-12-29 14:02:18 -08:00
if ($asset = Asset::where('asset_tag', '=', $asset_tag)->first()) {
$item[$asset_tag][$batch_counter]['asset_id'] = $asset->id;
2016-12-29 14:02:18 -08:00
$base_username = User::generateFormattedNameFromFullName(Setting::getSettings()->username_format, $item[$asset_tag][$batch_counter]['name']);
$user = User::where('username', '=', $base_username['username']);
$user_query = ' on username '.$base_username['username'];
if ($request->input('match_firstnamelastname') == '1') {
2016-12-29 14:02:18 -08:00
$firstnamedotlastname = User::generateFormattedNameFromFullName('firstname.lastname', $item[$asset_tag][$batch_counter]['name']);
$item[$asset_tag][$batch_counter]['username'][] = $firstnamedotlastname['username'];
2016-12-29 14:02:18 -08:00
$user->orWhere('username', '=', $firstnamedotlastname['username']);
$user_query .= ', or on username '.$firstnamedotlastname['username'];
2016-08-12 16:01:59 -07:00
}
if ($request->input('match_flastname') == '1') {
2016-12-29 14:02:18 -08:00
$flastname = User::generateFormattedNameFromFullName('filastname', $item[$asset_tag][$batch_counter]['name']);
$item[$asset_tag][$batch_counter]['username'][] = $flastname['username'];
2016-12-29 14:02:18 -08:00
$user->orWhere('username', '=', $flastname['username']);
$user_query .= ', or on username '.$flastname['username'];
}
if ($request->input('match_firstname') == '1') {
2016-12-29 14:02:18 -08:00
$firstname = User::generateFormattedNameFromFullName('firstname', $item[$asset_tag][$batch_counter]['name']);
$item[$asset_tag][$batch_counter]['username'][] = $firstname['username'];
2016-12-29 14:02:18 -08:00
$user->orWhere('username', '=', $firstname['username']);
$user_query .= ', or on username '.$firstname['username'];
}
if ($request->input('match_email') == '1') {
if ($item[$asset_tag][$batch_counter]['name'] == '') {
$item[$asset_tag][$batch_counter]['username'][] = $user_email = User::generateEmailFromFullName($item[$asset_tag][$batch_counter]['name']);
2016-12-29 14:02:18 -08:00
$user->orWhere('username', '=', $user_email);
$user_query .= ', or on username '.$user_email;
}
}
if ($request->input('match_username') == '1') {
// Added #8825: add explicit username lookup
$raw_username = $item[$asset_tag][$batch_counter]['name'];
$user->orWhere('username', '=', $raw_username);
$user_query .= ', or on username '.$raw_username;
}
// A matching user was found
if ($user = $user->first()) {
//$user is now matched user from db
2016-08-12 16:01:59 -07:00
$item[$asset_tag][$batch_counter]['user_id'] = $user->id;
Actionlog::firstOrCreate([
'item_id' => $asset->id,
'item_type' => Asset::class,
'user_id' => Auth::user()->id,
'note' => 'Checkout imported by '.Auth::user()->present()->fullName().' from history importer',
'target_id' => $item[$asset_tag][$batch_counter]['user_id'],
'target_type' => User::class,
'created_at' => $item[$asset_tag][$batch_counter]['checkout_date'],
'action_type' => 'checkout',
]);
$checkin_date = $item[$asset_tag][$batch_counter]['checkin_date'];
if ($isCheckinHeaderExplicit) {
//if checkin date header exists, assume that empty or future date is still checked out
//if checkin is before todays date, assume it's checked in and do not assign user ID, if checkin date is in the future or blank, this is the expected checkin date, items is checked out
if ((strtotime($checkin_date) > strtotime(Carbon::now())) || (empty($checkin_date))
) {
//only do this if item is checked out
$asset->assigned_to = $user->id;
$asset->assigned_type = User::class;
}
}
if (! empty($checkin_date)) {
//only make a checkin there is a valid checkin date or we created one on import.
Actionlog::firstOrCreate([
'item_id' => $item[$asset_tag][$batch_counter]['asset_id'],
'item_type' => Asset::class,
'user_id' => Auth::user()->id,
'note' => 'Checkin imported by '.Auth::user()->present()->fullName().' from history importer',
'target_id' => null,
'created_at' => $checkin_date,
'action_type' => 'checkin',
]);
}
if ($asset->save()) {
$status['success'][]['asset'][$asset_tag]['msg'] = 'Asset successfully matched for '.Helper::array_smart_fetch($row, 'name').$user_query.' on '.$item[$asset_tag][$batch_counter]['checkout_date'];
} else {
$status['error'][]['asset'][$asset_tag]['msg'] = 'Asset and user was matched but could not be saved.';
}
2016-08-12 16:01:59 -07:00
} else {
$item[$asset_tag][$batch_counter]['user_id'] = null;
$status['error'][]['user'][Helper::array_smart_fetch($row, 'name')]['msg'] = 'User does not exist so no checkin log was created.';
2016-08-12 16:01:59 -07:00
}
} else {
$item[$asset_tag][$batch_counter]['asset_id'] = null;
$status['error'][]['asset'][$asset_tag]['msg'] = 'Asset does not exist so no match was attempted.';
2016-08-12 16:01:59 -07:00
}
}
}
2017-06-09 16:31:25 -07:00
return view('hardware/history')->with('status', $status);
2016-08-12 16:01:59 -07:00
}
public function sortByName(array $recordA, array $recordB): int
{
return strcmp($recordB['Full Name'], $recordA['Full Name']);
}
2016-03-25 01:18:05 -07:00
/**
2023-04-11 10:52:14 -07:00
* Restore a deleted asset.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $assetId
* @since [v1.0]
* @return View
*/
2016-03-25 01:18:05 -07:00
public function getRestore($assetId = null)
{
if ($asset = Asset::withTrashed()->find($assetId)) {
$this->authorize('delete', $asset);
if ($asset->deleted_at == '') {
return redirect()->back()->with('error', trans('general.not_deleted', ['item_type' => trans('general.asset')]));
}
if ($asset->restore()) {
// Redirect them to the deleted page if there are more, otherwise the section index
$deleted_assets = Asset::onlyTrashed()->count();
if ($deleted_assets > 0) {
return redirect()->back()->with('success', trans('admin/hardware/message.restore.success'));
}
return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.restore.success'));
}
// Check validation to make sure we're not restoring an asset with the same asset tag (or unique attribute) as an existing asset
return redirect()->back()->with('error', trans('general.could_not_restore', ['item_type' => trans('general.asset'), 'error' => $asset->getErrors()->first()]));
2016-03-25 01:18:05 -07:00
}
Cleanup controller escaping (#3084) * Make delete routes work. We put a little form in the modal that spoofs the delete field. * Fix route on creating a user. * Fix redundant id parameter. * Port acceptance tests to new urls. * Initial work on migrating to model based policies instead of global gates. Will allow for much more detailed permissions bits in the future. * This needs to stay for the dashboard checks. * Add user states for permissions to build tests. * Build up unit tests for gates/permissions. Move accessories/consumables/assets to policies instead of in authserviceprovider * Migrate various locations to new syntax. Update test to be more specific * Fix functional tests. Add an artisan command for installing a settings setup on travis-ci * Try a different id... Need to come up with a better way of passing the id for tests that need an existing one. * Try to fix travis * Update urls to use routes and not hardcode old paths. Also fix some migration errors found along the way.: * Add a environment for travis functional tests. * Adjust config file to make travis use it. * Use redirect()->route instead of redirect()-to * Dump all failures in the output directory if travis fails. * Cleanups and minor fixes. * Adjust the supplier modelfactory to comply with new validation restrictions. * Some test fixes. * Locales can be longer than 5 characters according to faker... fex gez_ET. Increase lenght in mysql and add a validation * Update test database dump to latest migrations. * Extend Supplier phone/fax length. This catches issues found in testing with a phone number with a five digit extension. fex (356) 654-3024 x36632 Also move away from escaping all values put into eloquent. Eloquent already uses PDO parameter binding, and this was leading to names like Mr Ryan O'Malley turning into an html escaped version of that name when stored. All values should be escaped when using {{}}, we'll just have to be more cautious when we use {!!, but I think we already are? * Remove additional escaping here, like we did in suppliers controller. * No need to eager load all of these relationships when we can call the count on the querybuilder directly * Work on controller cleanup * Always start from scrach, catches more issues this way. * Update sql dump. Remove old code from permissions test. * Generate a deletable item on demand in the test, rather than relying on one existing. I think we should probably move to mock all the database stuff at some point.. * More travis related fixes * Break script into multiple functional lines * Update all controllers to use the new helper, also cleanup syntax and docblocks along the way.
2016-12-19 22:00:50 -08:00
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
2016-03-25 01:18:05 -07:00
}
2017-10-28 11:17:52 -07:00
public function quickScan()
{
$this->authorize('audit', Asset::class);
$dt = Carbon::now()->addMonths(12)->toDateString();
2017-10-28 11:17:52 -07:00
return view('hardware/quickscan')->with('next_audit_date', $dt);
}
2016-08-25 21:03:24 -07:00
2021-12-19 13:53:31 -08:00
public function quickScanCheckin()
{
$this->authorize('checkin', Asset::class);
return view('hardware/quickscan-checkin');
}
2017-10-27 17:38:11 -07:00
public function audit($id)
{
$settings = Setting::getSettings();
$this->authorize('audit', Asset::class);
$dt = Carbon::now()->addMonths($settings->audit_interval)->toDateString();
$asset = Asset::findOrFail($id);
2017-10-28 11:17:52 -07:00
return view('hardware/audit')->with('asset', $asset)->with('next_audit_date', $dt)->with('locations_list');
}
public function dueForAudit()
{
$this->authorize('audit', Asset::class);
return view('hardware/audit-due');
}
public function overdueForAudit()
{
$this->authorize('audit', Asset::class);
return view('hardware/audit-overdue');
}
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
public function auditStore(Request $request, $id)
{
$this->authorize('audit', Asset::class);
$rules = [
2017-08-25 18:40:20 -07:00
'location_id' => 'exists:locations,id|nullable|numeric',
'next_audit_date' => 'date|nullable',
];
2023-07-13 20:48:51 -07:00
$validator = Validator::make($request->all(), $rules);
2017-08-25 18:40:20 -07:00
if ($validator->fails()) {
return response()->json(Helper::formatStandardApiResponse('error', null, $validator->errors()->all()));
2016-03-25 01:18:05 -07:00
}
$asset = Asset::findOrFail($id);
// We don't want to log this as a normal update, so let's bypass that
$asset->unsetEventDispatcher();
$asset->next_audit_date = $request->input('next_audit_date');
$asset->last_audit_date = date('Y-m-d H:i:s');
2016-03-25 01:18:05 -07:00
// Check to see if they checked the box to update the physical location,
// not just note it in the audit notes
if ($request->input('update_location') == '1') {
2023-07-13 20:48:51 -07:00
Log::debug('update location in audit');
$asset->location_id = $request->input('location_id');
}
if ($asset->save()) {
$file_name = '';
// Upload an image, if attached
if ($request->hasFile('image')) {
$path = 'private_uploads/audits';
if (! Storage::exists($path)) {
Storage::makeDirectory($path, 775);
}
$upload = $image = $request->file('image');
$ext = $image->getClientOriginalExtension();
$file_name = 'audit-'.str_random(18).'.'.$ext;
Storage::putFileAs($path, $upload, $file_name);
}
[WIP] Added #5957 - Flysystem support (#6262) * Added AWS url to example env * Upgrader - added check for new storage path and attempt to move * Ignore symlink * Updated paths for models * Moved copy methods * Added AWS_URL support For some reasin, Flysystem was generating the wrong AWS url (with a region included) * Switch to Flysystem for image uploads * Nicer display of image preview * Updated image preview on edit blades to use Flysystem * Twiddled some more paths * Working filesystems config * Updated Asset Models and Departments to use Flysystem * Janky workaround for differing S3/local urls/paths * Try to smartly use S3 as public disk if S3 is configured * Use public disk Storage options for public files * Additional transformer edits for Flysystem * Removed debugging * Added missing use Storage directive * Updated seeders to use Flysystem * Default logo * Set a default width We can potentially override this in settings later * Use Flysystem for logo upload * Update downloadFile to use Flysystem * Updated AssetFilesController to use Flysystem * Updated acceptance signatures to use Flysystem * Updated signature view to use Flysystem This isn’t working 100% yet * Use Flysystem facade for displaying asset image * Set assets path Should clean all these up when we’re done here * Added Rackspace support for Flysystem * Added Flysystem migrator console command * Added use Storage directive for categories * Added user avatars to Flysystem * Added profile avatar to Flysystem * Added the option to delete local files with the migrator * Added a check to prevent people from trying to move from local to local * Fixed the selectlists for Flysystem * Fixed the getImageUrl method to reflect Flysystem * Fixed AWS copy process * Fixed models path * More selectlist updates for Flysystem * Updated example .envs with updated env variable names * *sigh* * Updated non-asset getImageUrl() methods to use Flysystem * Removed S3 hardcoding * Use Flysystem in email headers * Fixed typo * Removed camera support from asset file upload We’ll find a way to add this in later (and add that support to all of the other image uploads as well) * Fixed path for categories * WIP - Switched to standard handleImages for asset upload. This is currently broken as I refact the handleImages method. Because the assets store/create methods use their own Form Request, the handleImages method doesn’t exist in that Form Request so it wil error now. * Fixed css URL error * Updated Debugbar to latest version (#6265) v3.2 adds support for Laravel 5.7 * Fixed: Missing CSS file in basic.blade.php (#6264) * Fixed missing CSS file in basic.blade.php * Added * Changed stylesheet import for authorize.blade.php * Updated composer lock * Added AWS_BUCKET_ROOT as env variable * Use nicer image preview for logo upload * Removed AssetRequest form request * Removed asset form request, moved custom field validation into model * Added additional help text for logo upload * Increased the size of the image resize - should make this a setting tho * Few more formatting tweaks to logo section of branding blade preview * Use Flysystem for asset/license file uploads * Use Flysystem for removing images from models that have been deleted * Enable backups to use Flysystem This only handles part of the problem. This just makes it so we can ship files to S3 if we want, but does not account for how we backup files that are hosted on S3 * Use Flysystem to download license files * Updated audits to use Flysystem
2018-09-29 21:33:52 -07:00
$asset->logAudit($request->input('note'), $request->input('location_id'), $file_name);
return redirect()->route('assets.audit.due')->with('success', trans('admin/hardware/message.audit.success'));
}
2016-03-25 01:18:05 -07:00
}
2017-11-02 04:21:57 -07:00
WIP - Improved requested assets (#5289) * WIP - beginning of improved requested assets - Use Ajax tables for faster loading - Use new notifications for requesting an asset TODO: - Use ajax tables for requestable asset models - Use new notifications for canceling an asset request - Expire requests once the asset has been checked out to the requesting user * Only show asset name in email if it has one * Refactor requested method to only include non-canceled requests * Refactored requestable assets to log request and cancelation * Added softdeletes on checkout requests * Differentiate between canceling and deleting requests * Added asset request cancelation notification * Added timestamps and corrected unique key on requests table * Improved requests view * Re-use blade for cancel/request email * Refactored BS table formatter for requested assets * Location name min reduced to 2 * Added PAT test as maintenance option This needs to be refactored into database-driven options with a UI * Better slack message * Added getImageUrl method for assets * Include qty in request notifications TODO: - Try to pull requested info from original request for cancelation, otherwise it will default to 1 * Removed old asset request/cancel emails * Added user profile asset request routes * Added profile controller requested assets method * Added blade link to requested assets for profile view * Sort user history desc * Added requested assets blade * Added canceled at to checkoutRequest method * Include qty in request * Fixed comment, removed allowed_columns * Removed Queable methods, since we don’t use a queue * Fixed return type in method doc * Fixed version number * Changed id to user_id for clarity
2018-04-04 17:33:02 -07:00
public function getRequestedIndex($user_id = null)
2017-11-02 04:21:57 -07:00
{
$this->authorize('index', Asset::class);
WIP - Improved requested assets (#5289) * WIP - beginning of improved requested assets - Use Ajax tables for faster loading - Use new notifications for requesting an asset TODO: - Use ajax tables for requestable asset models - Use new notifications for canceling an asset request - Expire requests once the asset has been checked out to the requesting user * Only show asset name in email if it has one * Refactor requested method to only include non-canceled requests * Refactored requestable assets to log request and cancelation * Added softdeletes on checkout requests * Differentiate between canceling and deleting requests * Added asset request cancelation notification * Added timestamps and corrected unique key on requests table * Improved requests view * Re-use blade for cancel/request email * Refactored BS table formatter for requested assets * Location name min reduced to 2 * Added PAT test as maintenance option This needs to be refactored into database-driven options with a UI * Better slack message * Added getImageUrl method for assets * Include qty in request notifications TODO: - Try to pull requested info from original request for cancelation, otherwise it will default to 1 * Removed old asset request/cancel emails * Added user profile asset request routes * Added profile controller requested assets method * Added blade link to requested assets for profile view * Sort user history desc * Added requested assets blade * Added canceled at to checkoutRequest method * Include qty in request * Fixed comment, removed allowed_columns * Removed Queable methods, since we don’t use a queue * Fixed return type in method doc * Fixed version number * Changed id to user_id for clarity
2018-04-04 17:33:02 -07:00
$requestedItems = CheckoutRequest::with('user', 'requestedItem')->whereNull('canceled_at')->with('user', 'requestedItem');
if ($user_id) {
$requestedItems->where('user_id', $user_id)->get();
2017-11-02 04:21:57 -07:00
}
WIP - Improved requested assets (#5289) * WIP - beginning of improved requested assets - Use Ajax tables for faster loading - Use new notifications for requesting an asset TODO: - Use ajax tables for requestable asset models - Use new notifications for canceling an asset request - Expire requests once the asset has been checked out to the requesting user * Only show asset name in email if it has one * Refactor requested method to only include non-canceled requests * Refactored requestable assets to log request and cancelation * Added softdeletes on checkout requests * Differentiate between canceling and deleting requests * Added asset request cancelation notification * Added timestamps and corrected unique key on requests table * Improved requests view * Re-use blade for cancel/request email * Refactored BS table formatter for requested assets * Location name min reduced to 2 * Added PAT test as maintenance option This needs to be refactored into database-driven options with a UI * Better slack message * Added getImageUrl method for assets * Include qty in request notifications TODO: - Try to pull requested info from original request for cancelation, otherwise it will default to 1 * Removed old asset request/cancel emails * Added user profile asset request routes * Added profile controller requested assets method * Added blade link to requested assets for profile view * Sort user history desc * Added requested assets blade * Added canceled at to checkoutRequest method * Include qty in request * Fixed comment, removed allowed_columns * Removed Queable methods, since we don’t use a queue * Fixed return type in method doc * Fixed version number * Changed id to user_id for clarity
2018-04-04 17:33:02 -07:00
$requestedItems = $requestedItems->orderBy('created_at', 'desc')->get();
2017-11-02 04:21:57 -07:00
return view('hardware/requested', compact('requestedItems'));
}
2020-04-28 08:31:30 -07:00
}