Adopt Laravel coding style

Shift automatically applies the Laravel coding style - which uses the PSR-2 coding style as a base with some minor additions.

You may customize the adopted coding style by adding your own [PHP CS Fixer][1] `.php_cs` config file to your project root. Feel free to use [Shift's Laravel ruleset][2] to help you get started.

[1]: https://github.com/FriendsOfPHP/PHP-CS-Fixer
[2]: https://gist.github.com/laravel-shift/cab527923ed2a109dda047b97d53c200
This commit is contained in:
Laravel Shift 2021-06-10 20:15:52 +00:00
parent 54cb6c050a
commit 934afa036f
4549 changed files with 35238 additions and 38391 deletions

View file

@ -2,10 +2,10 @@
namespace App\Console\Commands;
use App\Models\LicenseSeat;
use Illuminate\Console\Command;
use App\Models\User;
use App\Models\License;
use App\Models\LicenseSeat;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
class CheckinLicensesFromAllUsers extends Command
@ -41,24 +41,23 @@ class CheckinLicensesFromAllUsers extends Command
*/
public function handle()
{
$license_id = $this->option('license_id');
$notify = $this->option('notify');
if (! $license_id) {
$this->error('ERROR: License ID is required.');
return false;
}
if (! $license = License::where('id', '=', $license_id)->first()) {
$this->error('Invalid license ID');
return false;
}
$this->info('Checking in ALL seats for '.$license->name);
$licenseSeats = LicenseSeat::where('license_id', '=', $license_id)
->whereNotNull('assigned_to')
->with('user')
@ -84,12 +83,6 @@ class CheckinLicensesFromAllUsers extends Command
// Log the checkin
$seat->logCheckin($seat->user, 'Checked in via cli tool');
}
}
}
}
}

View file

@ -2,10 +2,10 @@
namespace App\Console\Commands;
use App\Models\LicenseSeat;
use Illuminate\Console\Command;
use App\Models\User;
use App\Models\License;
use App\Models\LicenseSeat;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
class CheckoutLicenseToAllUsers extends Command
@ -41,18 +41,18 @@ class CheckoutLicenseToAllUsers extends Command
*/
public function handle()
{
$license_id = $this->option('license_id');
$notify = $this->option('notify');
if (! $license_id) {
$this->error('ERROR: License ID is required.');
return false;
}
if (! $license = License::where('id', '=', $license_id)->with('assignedusers')->first()) {
$this->error('Invalid license ID');
return false;
}
@ -78,10 +78,10 @@ class CheckoutLicenseToAllUsers extends Command
continue;
}
// If the license is valid, check that there is an available seat
if ($license->availCount()->count() < 1) {
$this->error('ERROR: No available seats');
return false;
}
@ -89,7 +89,6 @@ class CheckoutLicenseToAllUsers extends Command
// Get the seat ID
$licenseSeat = $license->freeSeat();
// Update the seat with checkout info,
$licenseSeat->assigned_to = $user->id;
if ($licenseSeat->save()) {
@ -103,10 +102,6 @@ class CheckoutLicenseToAllUsers extends Command
$licenseSeat->logCheckout('Checked out via cli tool', $user);
$this->info('License '.$license_id.' seat '.$licenseSeat->id.' checked out to '.$user->username);
}
}
}
}
}

View file

@ -37,7 +37,6 @@ class CreateAdmin extends Command
*/
public function handle()
{
$first_name = $this->option('first_name');
$last_name = $this->option('last_name');
$username = $this->option('username');
@ -70,10 +69,7 @@ class CreateAdmin extends Command
foreach ($errors->all() as $error) {
$this->info('ERROR:'.$error);
}
}
}
}
}

View file

@ -38,9 +38,7 @@ class DisableLDAP extends Command
*/
public function handle()
{
if ($this->confirm("\n****************************************************\nThis will disable LDAP support. You will not be able \nto login with an account that does not exist \nlocally in the Snipe-IT local database. \n****************************************************\n\nDo you wish to continue? [y|N]")) {
$setting = Setting::getSettings();
$setting->ldap_enabled = 0;
if ($setting->save()) {
@ -51,6 +49,5 @@ class DisableLDAP extends Command
} else {
$this->info('Canceled. No actions taken.');
}
}
}

View file

@ -37,7 +37,6 @@ class FixDoubleEscape extends Command
*/
public function handle()
{
$tables = [
'\App\Models\Asset' => ['name'],
'\App\Models\License' => ['name'],
@ -56,16 +55,13 @@ class FixDoubleEscape extends Command
'\App\Models\User' => ['first_name', 'last_name'],
];
$count = array();
$count = [];
foreach ($tables as $classname => $fields) {
$count[$classname] = array();
$count[$classname] = [];
$count[$classname]['classname'] = 0;
foreach ($fields as $field) {
$count[$classname]['classname']++;
$count[$classname][$field] = 0;
@ -74,12 +70,10 @@ class FixDoubleEscape extends Command
$row->{$field} = html_entity_decode($row->{$field}, ENT_QUOTES);
$row->save();
$count[$classname][$field]++;
}
}
}
$this->info('Update complete');
}
}

View file

@ -29,7 +29,6 @@ class FixMismatchedAssetsAndLogs extends Command
*/
private $dryrun = false;
/**
* Create a new command instance.
*
@ -47,7 +46,6 @@ class FixMismatchedAssetsAndLogs extends Command
*/
public function handle()
{
if ($this->option('dryrun')) {
$this->dryrun = true;
}
@ -93,13 +91,9 @@ class FixMismatchedAssetsAndLogs extends Command
}
} else {
//$this->info('Asset ID '.$asset->id.': There is a checkin '.$checkin_log->created_at.' after this checkout '.$checkout_log->created_at);
}
}
}
$this->info($mismatch_count.' mismatched assets.');
}
}

View file

@ -2,9 +2,9 @@
namespace App\Console\Commands;
use App\Models\Location;
use Illuminate\Console\Command;
use League\Csv\Reader;
use App\Models\Location;
class ImportLocations extends Command
{
@ -39,10 +39,8 @@ class ImportLocations extends Command
*/
public function handle()
{
if (!ini_get("auto_detect_line_endings")) {
ini_set("auto_detect_line_endings", '1');
if (! ini_get('auto_detect_line_endings')) {
ini_set('auto_detect_line_endings', '1');
}
$filename = $this->argument('filename');
@ -53,7 +51,6 @@ class ImportLocations extends Command
// Import parent location names first if they don't exist
foreach ($results as $parent_index => $parent_row) {
if (array_key_exists('Parent Name', $parent_row)) {
$parent_name = trim($parent_row['Parent Name']);
if (array_key_exists('Name', $parent_row)) {
@ -62,7 +59,7 @@ class ImportLocations extends Command
// Save parent location name
// This creates a sort of name-stub that we'll update later on in this script
$parent_location = Location::firstOrCreate(array('name' => $parent_name));
$parent_location = Location::firstOrCreate(['name' => $parent_name]);
if (array_key_exists('Name', $parent_row)) {
$this->info('Parent for '.$parent_row['Name'].' is '.$parent_name.'. Attempting to save '.$parent_name.'.');
}
@ -74,18 +71,15 @@ class ImportLocations extends Command
} else {
$this->info('- Parent location '.$parent_name.' was created.');
}
} else {
$this->info('- No Parent Name provided, so no parent location will be created.');
}
}
$this->info('----- Parents Created.... backfilling additional details... --------');
// Loop through ALL records and add/update them if there are additional fields
// besides name
foreach ($results as $index => $row) {
if (array_key_exists('Parent Name', $row)) {
$parent_name = trim($row['Parent Name']);
} else {
@ -94,11 +88,12 @@ class ImportLocations extends Command
// Set the location attributes to save
if (array_key_exists('Name', $row)) {
$location = Location::firstOrCreate(array('name' => trim($row['Name'])));
$location = Location::firstOrCreate(['name' => trim($row['Name'])]);
$location->name = trim($row['Name']);
$this->info('Checking location: '.$location->name);
} else {
$this->error('Location name is required and is missing from at least one row in this dataset. Check your CSV for extra trailing rows and try again.');
return false;
}
if (array_key_exists('Currency', $row)) {
@ -126,7 +121,6 @@ class ImportLocations extends Command
$location->ldap_ou = trim($row['OU']);
}
// If a parent name is provided, we created it earlier in the script,
// so let's grab that ID
if ($parent_name) {
@ -151,12 +145,6 @@ class ImportLocations extends Command
} else {
$this->error('- Non-parent Location '.$location->name.' could not be created: '.$location->getErrors());
}
}
}
}
}

View file

@ -3,11 +3,11 @@
namespace App\Console\Commands;
use App\Models\Department;
use Illuminate\Console\Command;
use App\Models\Setting;
use App\Models\Ldap;
use App\Models\User;
use App\Models\Location;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Console\Command;
use Log;
class LdapSync extends Command
@ -62,14 +62,15 @@ class LdapSync extends Command
Ldap::bindAdminToLdap($ldapconn);
} catch (\Exception $e) {
if ($this->option('json_summary')) {
$json_summary = [ "error" => true, "error_message" => $e->getMessage(), "summary" => [] ];
$json_summary = ['error' => true, 'error_message' => $e->getMessage(), 'summary' => []];
$this->info(json_encode($json_summary));
}
LOG::info($e);
return [];
}
$summary = array();
$summary = [];
try {
if ($this->option('base_dn') != '') {
@ -81,15 +82,16 @@ class LdapSync extends Command
$results = Ldap::findLdapUsers($search_base);
} catch (\Exception $e) {
if ($this->option('json_summary')) {
$json_summary = [ "error" => true, "error_message" => $e->getMessage(), "summary" => [] ];
$json_summary = ['error' => true, 'error_message' => $e->getMessage(), 'summary' => []];
$this->info(json_encode($json_summary));
}
LOG::info($e);
return [];
}
/* Determine which location to assign users to by default. */
$location = NULL; // FIXME - this would be better called "$default_location", which is more explicit about its purpose
$location = null; // FIXME - this would be better called "$default_location", which is more explicit about its purpose
if ($this->option('location') != '') {
$location = Location::where('name', '=', $this->option('location'))->first();
@ -109,45 +111,44 @@ class LdapSync extends Command
if ($this->option('base_dn') == '') {
// Retrieve locations with a mapped OU, and sort them from the shallowest to deepest OU (see #3993)
$ldap_ou_locations = Location::where('ldap_ou', '!=', '')->get()->toArray();
$ldap_ou_lengths = array();
$ldap_ou_lengths = [];
foreach ($ldap_ou_locations as $ou_loc) {
$ldap_ou_lengths[] = strlen($ou_loc["ldap_ou"]);
$ldap_ou_lengths[] = strlen($ou_loc['ldap_ou']);
}
array_multisort($ldap_ou_lengths, SORT_ASC, $ldap_ou_locations);
if (sizeof($ldap_ou_locations) > 0) {
if (count($ldap_ou_locations) > 0) {
LOG::debug('Some locations have special OUs set. Locations will be automatically set for users in those OUs.');
}
// Inject location information fields
for ($i = 0; $i < $results["count"]; $i++) {
$results[$i]["ldap_location_override"] = false;
$results[$i]["location_id"] = 0;
for ($i = 0; $i < $results['count']; $i++) {
$results[$i]['ldap_location_override'] = false;
$results[$i]['location_id'] = 0;
}
// Grab subsets based on location-specific DNs, and overwrite location for these users.
foreach ($ldap_ou_locations as $ldap_loc) {
try {
$location_users = Ldap::findLdapUsers($ldap_loc["ldap_ou"]);
$location_users = Ldap::findLdapUsers($ldap_loc['ldap_ou']);
} catch (\Exception $e) { // FIXME: this is stolen from line 77 or so above
if ($this->option('json_summary')) {
$json_summary = [ "error" => true, "error_message" => trans('admin/users/message.error.ldap_could_not_search')." Location: ".$ldap_loc['name']." (ID: ".$ldap_loc['id'].") cannot connect to \"".$ldap_loc["ldap_ou"]."\" - ".$e->getMessage(), "summary" => [] ];
$json_summary = ['error' => true, 'error_message' => trans('admin/users/message.error.ldap_could_not_search').' Location: '.$ldap_loc['name'].' (ID: '.$ldap_loc['id'].') cannot connect to "'.$ldap_loc['ldap_ou'].'" - '.$e->getMessage(), 'summary' => []];
$this->info(json_encode($json_summary));
}
LOG::info($e);
return [];
}
$usernames = array();
for ($i = 0; $i < $location_users["count"]; $i++) {
$usernames = [];
for ($i = 0; $i < $location_users['count']; $i++) {
if (array_key_exists($ldap_result_username, $location_users[$i])) {
$location_users[$i]["ldap_location_override"] = true;
$location_users[$i]["location_id"] = $ldap_loc["id"];
$location_users[$i]['ldap_location_override'] = true;
$location_users[$i]['location_id'] = $ldap_loc['id'];
$usernames[] = $location_users[$i][$ldap_result_username][0];
}
}
// Delete located users from the general group.
@ -166,51 +167,48 @@ class LdapSync extends Command
}
/* Create user account entries in Snipe-IT */
$tmp_pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
$tmp_pass = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20);
$pass = bcrypt($tmp_pass);
for ($i = 0; $i < $results["count"]; $i++) {
if (empty($ldap_result_active_flag) || $results[$i][$ldap_result_active_flag][0] == "TRUE") {
$item = array();
$item["username"] = isset($results[$i][$ldap_result_username][0]) ? $results[$i][$ldap_result_username][0] : "";
$item["employee_number"] = isset($results[$i][$ldap_result_emp_num][0]) ? $results[$i][$ldap_result_emp_num][0] : "";
$item["lastname"] = isset($results[$i][$ldap_result_last_name][0]) ? $results[$i][$ldap_result_last_name][0] : "";
$item["firstname"] = isset($results[$i][$ldap_result_first_name][0]) ? $results[$i][$ldap_result_first_name][0] : "";
$item["email"] = isset($results[$i][$ldap_result_email][0]) ? $results[$i][$ldap_result_email][0] : "" ;
$item["ldap_location_override"] = isset($results[$i]["ldap_location_override"]) ? $results[$i]["ldap_location_override"]:"";
$item["location_id"] = isset($results[$i]["location_id"]) ? $results[$i]["location_id"]:"";
$item["telephone"] = isset($results[$i][$ldap_result_phone][0]) ? $results[$i][$ldap_result_phone][0] : "";
$item["jobtitle"] = isset($results[$i][$ldap_result_jobtitle][0]) ? $results[$i][$ldap_result_jobtitle][0] : "";
$item["country"] = isset($results[$i][$ldap_result_country][0]) ? $results[$i][$ldap_result_country][0] : "";
$item["department"] = isset($results[$i][$ldap_result_dept][0]) ? $results[$i][$ldap_result_dept][0] : "";
for ($i = 0; $i < $results['count']; $i++) {
if (empty($ldap_result_active_flag) || $results[$i][$ldap_result_active_flag][0] == 'TRUE') {
$item = [];
$item['username'] = isset($results[$i][$ldap_result_username][0]) ? $results[$i][$ldap_result_username][0] : '';
$item['employee_number'] = isset($results[$i][$ldap_result_emp_num][0]) ? $results[$i][$ldap_result_emp_num][0] : '';
$item['lastname'] = isset($results[$i][$ldap_result_last_name][0]) ? $results[$i][$ldap_result_last_name][0] : '';
$item['firstname'] = isset($results[$i][$ldap_result_first_name][0]) ? $results[$i][$ldap_result_first_name][0] : '';
$item['email'] = isset($results[$i][$ldap_result_email][0]) ? $results[$i][$ldap_result_email][0] : '';
$item['ldap_location_override'] = isset($results[$i]['ldap_location_override']) ? $results[$i]['ldap_location_override'] : '';
$item['location_id'] = isset($results[$i]['location_id']) ? $results[$i]['location_id'] : '';
$item['telephone'] = isset($results[$i][$ldap_result_phone][0]) ? $results[$i][$ldap_result_phone][0] : '';
$item['jobtitle'] = isset($results[$i][$ldap_result_jobtitle][0]) ? $results[$i][$ldap_result_jobtitle][0] : '';
$item['country'] = isset($results[$i][$ldap_result_country][0]) ? $results[$i][$ldap_result_country][0] : '';
$item['department'] = isset($results[$i][$ldap_result_dept][0]) ? $results[$i][$ldap_result_dept][0] : '';
$department = Department::firstOrCreate([
'name' => $item["department"],
'name' => $item['department'],
]);
$user = User::where('username', $item["username"])->first();
$user = User::where('username', $item['username'])->first();
if ($user) {
// Updating an existing user.
$item["createorupdate"] = 'updated';
$item['createorupdate'] = 'updated';
} else {
// Creating a new user.
$user = new User;
$user->password = $pass;
$user->activated = 0;
$item["createorupdate"] = 'created';
$item['createorupdate'] = 'created';
}
$user->first_name = $item["firstname"];
$user->last_name = $item["lastname"];
$user->username = $item["username"];
$user->email = $item["email"];
$user->employee_num = e($item["employee_number"]);
$user->phone = $item["telephone"];
$user->jobtitle = $item["jobtitle"];
$user->country = $item["country"];
$user->first_name = $item['firstname'];
$user->last_name = $item['lastname'];
$user->username = $item['username'];
$user->email = $item['email'];
$user->employee_num = e($item['employee_number']);
$user->phone = $item['telephone'];
$user->jobtitle = $item['jobtitle'];
$user->country = $item['country'];
$user->department_id = $department->id;
// Sync activated state for Active Directory.
@ -254,13 +252,11 @@ class LdapSync extends Command
if ($item['ldap_location_override'] == true) {
$user->location_id = $item['location_id'];
} elseif ((isset($location)) && (! empty($location))) {
if ((is_array($location)) && (array_key_exists('id', $location))) {
$user->location_id = $location['id'];
} elseif (is_object($location)) {
$user->location_id = $location->id;
}
}
$user->ldap_import = 1;
@ -268,19 +264,18 @@ class LdapSync extends Command
$errors = '';
if ($user->save()) {
$item["note"] = $item["createorupdate"];
$item["status"]='success';
$item['note'] = $item['createorupdate'];
$item['status'] = 'success';
} else {
foreach ($user->getErrors()->getMessages() as $key => $err) {
$errors .= $err[0];
}
$item["note"] = $errors;
$item["status"]='error';
$item['note'] = $errors;
$item['status'] = 'error';
}
array_push($summary, $item);
}
}
if ($this->option('summary')) {
@ -292,7 +287,7 @@ class LdapSync extends Command
}
}
} elseif ($this->option('json_summary')) {
$json_summary = [ "error" => false, "error_message" => "", "summary" => $summary ]; // hardcoding the error to false and the error_message to blank seems a bit weird
$json_summary = ['error' => false, 'error_message' => '', 'summary' => $summary]; // hardcoding the error to false and the error_message to blank seems a bit weird
$this->info(json_encode($json_summary));
} else {
return $summary;

View file

@ -4,13 +4,13 @@ declare(strict_types=1);
namespace App\Console\Commands;
use Log;
use Exception;
use Adldap\Models\User as AdldapUser;
use App\Models\Location;
use App\Models\User;
use App\Services\LdapAd;
use App\Models\Location;
use Exception;
use Illuminate\Console\Command;
use Adldap\Models\User as AdldapUser;
use Log;
/**
* LDAP / AD sync command.
@ -108,22 +108,21 @@ class LdapSyncNg extends Command
*/
public function handle()
{
$dispatcher = \Adldap\Adldap::getEventDispatcher();
// Listen for all model events.
$dispatcher->listen('Adldap\Models\Events\*', function ($eventName, array $data) {
echo $eventName; // Returns 'Adldap\Models\Events\Updating'
var_dump($data); // Returns [0] => (object) Adldap\Models\Events\Updating;
\Log::debug("Event: ".$eventName." data - ".print_r($data, true));
\Log::debug('Event: '.$eventName.' data - '.print_r($data, true));
});
$dispatcher->listen('Adldap\Auth\Events\*', function ($eventName, array $data) {
echo $eventName; // Returns 'Adldap\Models\Events\Updating'
var_dump($data); // Returns [0] => (object) Adldap\Models\Events\Updating;
\Log::debug("Event: ".$eventName." data - ".print_r($data, true));
\Log::debug('Event: '.$eventName.' data - '.print_r($data, true));
});
ini_set('max_execution_time', env('LDAP_TIME_LIM', "600")); //600 seconds = 10 minutes
ini_set('max_execution_time', env('LDAP_TIME_LIM', '600')); //600 seconds = 10 minutes
ini_set('memory_limit', '500M');
$old_error_reporting = error_reporting(); // grab old error_reporting .ini setting, for later re-enablement
error_reporting($old_error_reporting & ~E_DEPRECATED); // disable deprecation warnings, for LDAP in PHP 7.4 (and greater)
@ -150,6 +149,7 @@ class LdapSyncNg extends Command
}
error_reporting($old_error_reporting); // re-enable deprecation warnings.
return $this->getSummary();
}
@ -213,7 +213,7 @@ class LdapSyncNg extends Command
} else {
$errors = '';
foreach ($user->getErrors()->getMessages() as $error) {
$errors .= implode(", ",$error);
$errors .= implode(', ', $error);
}
$summary['note'] = $snipeUser->getDN().' was not imported. REASON: '.$errors;
$summary['status'] = 'ERROR';
@ -235,14 +235,13 @@ class LdapSyncNg extends Command
* @author Wes Hulette <jwhulette@gmail.com>
*
* @since 5.0.0
*
*/
private function processLdapUsers(): void
{
try {
\Log::debug("CAL:LING GET LDAP SUSERS");
\Log::debug('CAL:LING GET LDAP SUSERS');
$ldapUsers = $this->ldap->getLdapUsers();
\Log::debug("END CALLING GET LDAP USERS");
\Log::debug('END CALLING GET LDAP USERS');
} catch (Exception $e) {
$this->outputError($e);
exit($e->getMessage());

View file

@ -2,10 +2,9 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
class MergeUsersByUsername extends Command
{
@ -44,7 +43,7 @@ class MergeUsersByUsername extends Command
$users = User::where('username', 'LIKE', '%@%')->whereNull('deleted_at')->get();
foreach ($users as $user) {
$parts = explode("@", $user->username);
$parts = explode('@', $user->username);
$bad_users = User::where('username', '=', $parts[0])->whereNull('deleted_at')->with('assets', 'manager', 'userlog', 'licenses', 'consumables', 'accessories', 'managedLocations')->get();
foreach ($bad_users as $bad_user) {
@ -89,7 +88,6 @@ class MergeUsersByUsername extends Command
$this->info('Updating managed user records to user '.$user->id);
User::where('manager_id', '=', $bad_user->id)->update(['manager_id' => $user->id]);
// Update location manager IDs
foreach ($bad_user->managedLocations as $managedLocation) {
$this->info('Updating managed location record '.$managedLocation->name.' to manager '.$user->id);
@ -101,12 +99,7 @@ class MergeUsersByUsername extends Command
$this->info('Marking the user as deleted');
$bad_user->deleted_at = Carbon::now()->timestamp;
$bad_user->save();
}
}
}
}
}
}

View file

@ -2,7 +2,6 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
@ -39,33 +38,31 @@ class MoveUploadsToNewDisk extends Command
*/
public function handle()
{
if (config('filesystems.default') == 'local') {
$this->error('Your current disk is set to local so we cannot proceed.');
$this->warn("Please configure your .env settings for S3. \nChange your PUBLIC_FILESYSTEM_DISK value to 's3_public' and your PRIVATE_FILESYSTEM_DISK to s3_private.");
return false;
}
$delete_local = $this->argument('delete_local');
$public_uploads['accessories'] = glob('public/accessories'."/*.*");
$public_uploads['assets'] = glob('public/assets'."/*.*");
$public_uploads['avatars'] = glob('public/avatars'."/*.*");
$public_uploads['categories'] = glob('public/categories'."/*.*");
$public_uploads['companies'] = glob('public/companies'."/*.*");
$public_uploads['components'] = glob('public/components'."/*.*");
$public_uploads['consumables'] = glob('public/consumables'."/*.*");
$public_uploads['departments'] = glob('public/departments'."/*.*");
$public_uploads['locations'] = glob('public/locations'."/*.*");
$public_uploads['manufacturers'] = glob('public/manufacturers'."/*.*");
$public_uploads['suppliers'] = glob('public/suppliers'."/*.*");
$public_uploads['assetmodels'] = glob('public/models'."/*.*");
$public_uploads['accessories'] = glob('public/accessories'.'/*.*');
$public_uploads['assets'] = glob('public/assets'.'/*.*');
$public_uploads['avatars'] = glob('public/avatars'.'/*.*');
$public_uploads['categories'] = glob('public/categories'.'/*.*');
$public_uploads['companies'] = glob('public/companies'.'/*.*');
$public_uploads['components'] = glob('public/components'.'/*.*');
$public_uploads['consumables'] = glob('public/consumables'.'/*.*');
$public_uploads['departments'] = glob('public/departments'.'/*.*');
$public_uploads['locations'] = glob('public/locations'.'/*.*');
$public_uploads['manufacturers'] = glob('public/manufacturers'.'/*.*');
$public_uploads['suppliers'] = glob('public/suppliers'.'/*.*');
$public_uploads['assetmodels'] = glob('public/models'.'/*.*');
// iterate files
foreach($public_uploads as $public_type => $public_upload)
{
foreach ($public_uploads as $public_type => $public_upload) {
$type_count = 0;
$this->info("- There are ".count($public_upload).' PUBLIC '.$public_type.' files.');
$this->info('- There are '.count($public_upload).' PUBLIC '.$public_type.' files.');
for ($i = 0; $i < count($public_upload); $i++) {
$type_count++;
@ -79,13 +76,11 @@ class MoveUploadsToNewDisk extends Command
\Log::debug($e);
$this->error($e);
}
}
}
}
$logos = glob("public/uploads/setting*.*");
$this->info("- There are ".count($logos).' files that might be logos.');
$logos = glob('public/uploads/setting*.*');
$this->info('- There are '.count($logos).' files that might be logos.');
$type_count = 0;
foreach ($logos as $logo) {
@ -96,19 +91,17 @@ class MoveUploadsToNewDisk extends Command
$this->info($type_count.'. LOGO: '.$filename.' was copied to '.env('PUBLIC_AWS_URL').'/uploads/'.$filename);
}
$private_uploads['assets'] = glob('storage/private_uploads/assets'."/*.*");
$private_uploads['signatures'] = glob('storage/private_uploads/signatures'."/*.*");
$private_uploads['audits'] = glob('storage/private_uploads/audits'."/*.*");
$private_uploads['assetmodels'] = glob('storage/private_uploads/assetmodels'."/*.*");
$private_uploads['imports'] = glob('storage/private_uploads/imports'."/*.*");
$private_uploads['licenses'] = glob('storage/private_uploads/licenses'."/*.*");
$private_uploads['users'] = glob('storage/private_uploads/users'."/*.*");
$private_uploads['backups'] = glob('storage/private_uploads/users'."/*.*");
$private_uploads['assets'] = glob('storage/private_uploads/assets'.'/*.*');
$private_uploads['signatures'] = glob('storage/private_uploads/signatures'.'/*.*');
$private_uploads['audits'] = glob('storage/private_uploads/audits'.'/*.*');
$private_uploads['assetmodels'] = glob('storage/private_uploads/assetmodels'.'/*.*');
$private_uploads['imports'] = glob('storage/private_uploads/imports'.'/*.*');
$private_uploads['licenses'] = glob('storage/private_uploads/licenses'.'/*.*');
$private_uploads['users'] = glob('storage/private_uploads/users'.'/*.*');
$private_uploads['backups'] = glob('storage/private_uploads/users'.'/*.*');
foreach($private_uploads as $private_type => $private_upload)
{
$this->info("- There are ".count($private_upload).' PRIVATE '.$private_type.' files.');
foreach ($private_uploads as $private_type => $private_upload) {
$this->info('- There are '.count($private_upload).' PRIVATE '.$private_type.' files.');
$type_count = 0;
for ($x = 0; $x < count($private_upload); $x++) {
@ -119,17 +112,13 @@ class MoveUploadsToNewDisk extends Command
Storage::put($private_type.'/'.$filename, file_get_contents($private_upload[$i]));
$new_url = Storage::url($private_type.'/'.$filename, $filename);
$this->info($type_count.'. PRIVATE: '.$filename.' was copied to '.$new_url);
} catch (\Exception $e) {
\Log::debug($e);
$this->error($e);
}
}
}
if ($delete_local == 'true') {
$public_delete_count = 0;
$private_delete_count = 0;
@ -139,10 +128,8 @@ class MoveUploadsToNewDisk extends Command
$this->warn("\nTHIS WILL DELETE ALL OF YOUR LOCAL UPLOADED FILES. \n\nThis cannot be undone, so you should take a backup of your system before you proceed.\n");
$this->error('!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
if ($this->confirm("Do you wish to continue?")) {
if ($this->confirm('Do you wish to continue?')) {
foreach ($public_uploads as $public_type => $public_upload) {
for ($i = 0; $i < count($public_upload); $i++) {
$filename = $public_upload[$i];
try {
@ -152,13 +139,10 @@ class MoveUploadsToNewDisk extends Command
\Log::debug($e);
$this->error($e);
}
}
}
foreach($private_uploads as $private_type => $private_upload)
{
foreach ($private_uploads as $private_type => $private_upload) {
for ($i = 0; $i < count($private_upload); $i++) {
$filename = $private_upload[$i];
try {
@ -168,16 +152,11 @@ class MoveUploadsToNewDisk extends Command
\Log::debug($e);
$this->error($e);
}
}
}
$this->info($public_delete_count." PUBLIC local files and ".$private_delete_count." PRIVATE local files were deleted from your filesystem.");
$this->info($public_delete_count.' PUBLIC local files and '.$private_delete_count.' PRIVATE local files were deleted from your filesystem.');
}
}
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
@ -13,7 +14,6 @@ ini_set('memory_limit', env('IMPORT_MEMORY_LIMIT', '500M'));
*/
class ObjectImportCommand extends Command
{
/**
* The console command name.
*
@ -37,7 +37,9 @@ class ObjectImportCommand extends Command
{
parent::__construct();
}
private $bar;
/**
* Execute the console command.
*
@ -55,7 +57,6 @@ class ObjectImportCommand extends Command
->setShouldNotify($this->option('send-welcome'))
->setUsernameFormat($this->option('username_format'));
// This $logFile/useFiles() bit is currently broken, so commenting it out for now
// $logFile = $this->option('logfile');
// \Log::useFiles($logFile);
@ -65,22 +66,22 @@ class ObjectImportCommand extends Command
$this->bar = null;
if (! empty($this->errors)) {
$this->comment("The following Errors were encountered.");
$this->comment('The following Errors were encountered.');
foreach ($this->errors as $asset => $error) {
$this->comment('Error: Item: '.$asset.' failed validation: '.json_encode($error));
}
} else {
$this->comment("All Items imported successfully!");
$this->comment('All Items imported successfully!');
}
$this->comment("");
$this->comment('');
return;
}
public function errorCallback($item, $field, $errorString)
{
$this->errors[$item->name][$field] = $errorString;
}
public function progress($count)
{
if (! $this->bar) {
@ -94,12 +95,12 @@ class ObjectImportCommand extends Command
$this->bar->finish();
}
}
// Tracks the current item for error messages
private $updating;
// An array of errors encountered while parsing
private $errors;
/**
* Log a message to file, configurable by the --log-file parameter.
* If a warning message is passed, we'll spit it to the console as well.
@ -121,6 +122,7 @@ class ObjectImportCommand extends Command
}
}
}
/**
* Get the console command arguments.
*
@ -130,12 +132,11 @@ class ObjectImportCommand extends Command
*/
protected function getArguments()
{
return array(
array('filename', InputArgument::REQUIRED, 'File for the CSV import.'),
);
return [
['filename', InputArgument::REQUIRED, 'File for the CSV import.'],
];
}
/**
* Get the console command options.
*
@ -145,16 +146,15 @@ class ObjectImportCommand extends Command
*/
protected function getOptions()
{
return array(
array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null),
array('username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null),
array('logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log') ),
array('item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Accessory, License, or User', 'Asset'),
array('web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'),
array('user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1),
array('update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'),
array('send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'),
);
return [
['email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null],
['username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null],
['logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log')],
['item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Accessory, License, or User', 'Asset'],
['web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'],
['user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1],
['update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'],
['send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'],
];
}
}

View file

@ -80,7 +80,6 @@ class Purge extends Command
$location->forceDelete();
}
$accessories = Accessory::whereNotNull('deleted_at')->withTrashed()->get();
$accessory_assoc = 0;
$this->info($accessories->count().' accessories purged.');
@ -92,7 +91,6 @@ class Purge extends Command
}
$this->info($accessory_assoc.' corresponding log records purged.');
$consumables = Consumable::whereNotNull('deleted_at')->withTrashed()->get();
$this->info($consumables->count().' consumables purged.');
foreach ($consumables as $consumable) {
@ -101,7 +99,6 @@ class Purge extends Command
$consumable->forceDelete();
}
$components = Component::whereNotNull('deleted_at')->withTrashed()->get();
$this->info($components->count().' components purged.');
foreach ($components as $component) {
@ -126,7 +123,6 @@ class Purge extends Command
$model->forceDelete();
}
$categories = Category::whereNotNull('deleted_at')->withTrashed()->get();
$this->info($categories->count().' categories purged.');
foreach ($categories as $category) {
@ -165,11 +161,8 @@ class Purge extends Command
$this->info('- Status Label "'.$status_label->name.'" deleted.');
$status_label->forceDelete();
}
} else {
$this->info('Action canceled. Nothing was purged.');
}
}
}

View file

@ -48,15 +48,13 @@ class ReEncodeCustomFieldNames extends Command
*/
public function handle()
{
if ($this->confirm('This will regenerate all of the custom field database fieldnames in your database. THIS WILL CHANGE YOUR SCHEMA AND SHOULD NOT BE DONE WITHOUT MAKING A BACKUP FIRST. Do you wish to continue?'))
{
if ($this->confirm('This will regenerate all of the custom field database fieldnames in your database. THIS WILL CHANGE YOUR SCHEMA AND SHOULD NOT BE DONE WITHOUT MAKING A BACKUP FIRST. Do you wish to continue?')) {
/** Get all of the custom fields */
$fields = CustomField::get();
$asset_columns = \DB::getSchemaBuilder()->getColumnListing('assets');
$custom_field_columns = array();
$custom_field_columns = [];
/** Loop through the columns on the assets table */
foreach ($asset_columns as $asset_column) {
@ -71,18 +69,16 @@ class ReEncodeCustomFieldNames extends Command
* Then use that ID as the array key for use comparing the actual assets field name
* and the db_column value from the custom fields table.
*/
$last_part = substr(strrchr($asset_column, "_snipeit_"), 1);
$last_part = substr(strrchr($asset_column, '_snipeit_'), 1);
$custom_field_columns[$last_part] = $asset_column;
}
}
foreach ($fields as $field) {
$this->info($field->name.' ('.$field->id.') column should be '.$field->convertUnicodeDbSlug().'');
/** The assets table has the column it should have, all is well */
if (\Schema::hasColumn('assets', $field->convertUnicodeDbSlug()))
{
if (\Schema::hasColumn('assets', $field->convertUnicodeDbSlug())) {
$this->info('-- ✓ This field exists - all good');
/**
@ -104,7 +100,6 @@ class ReEncodeCustomFieldNames extends Command
});
$this->warn('-- ✓ Field updated from '.$custom_field_columns[$field->id].' to '.$field->convertUnicodeDbSlug());
} else {
$this->warn('-- X WARNING: There is no field on the assets table ending in '.$field->id.'. This may require more in-depth investigation and may mean the schema was altered manually.');
}
@ -115,12 +110,7 @@ class ReEncodeCustomFieldNames extends Command
*/
$field->db_column = $field->convertUnicodeDbSlug();
$field->save();
}
}
}
}
}
}

View file

@ -44,20 +44,19 @@ class RecryptFromMcrypt extends Command
public function handle()
{
// Check and see if they have a legacy app key listed in their .env
// If not, we can try to use the current APP_KEY if looks like it's old
$legacy_key = env('LEGACY_APP_KEY');
$key_parts = explode(':', $legacy_key);
$legacy_cipher = env('LEGACY_CIPHER', 'rijndael-256');
$errors = array();
$errors = [];
if (! $legacy_key) {
$this->error('ERROR: You do not have a LEGACY_APP_KEY set in your .env file. Please locate your old APP_KEY and ADD a line to your .env file like: LEGACY_APP_KEY=YOUR_OLD_APP_KEY');
return false;
}
// Do some basic legacy app key length checks
if (strlen($legacy_key) == 32) {
$legacy_length_check = true;
@ -68,13 +67,12 @@ class RecryptFromMcrypt extends Command
$legacy_length_check = false;
}
// Check that the app key is 32 characters
if ($legacy_length_check === true) {
$this->comment('INFO: Your LEGACY_APP_KEY looks correct. Okay to continue.');
} else {
$this->error('ERROR: Your LEGACY_APP_KEY is not the correct length (32 characters or base64 followed by 44 characters for later versions). Please locate your old APP_KEY and use that as your LEGACY_APP_KEY in your .env file to continue.');
return false;
}
@ -84,8 +82,7 @@ class RecryptFromMcrypt extends Command
$force = ($this->option('force')) ? true : false;
if ($force || ($this->confirm("Are you SURE you wish to continue?"))) {
if ($force || ($this->confirm('Are you SURE you wish to continue?'))) {
$backup_file = 'backups/env-backups/'.'app_key-'.date('Y-m-d-gis');
try {
@ -95,7 +92,6 @@ class RecryptFromMcrypt extends Command
$this->info('WARNING: Could not backup app keys');
}
if ($legacy_cipher) {
$mcrypter = new McryptEncrypter($legacy_key, $legacy_cipher);
} else {
@ -121,14 +117,12 @@ class RecryptFromMcrypt extends Command
$query->orWhereNotNull($custom_field->db_column);
}
// Get all assets with a value in any of the fields that were encrypted
/** @var Asset[] $assets */
$assets = $query->get();
$bar = $this->output->createProgressBar(count($assets));
foreach ($assets as $asset) {
foreach ($custom_fields as $encrypted_field) {
$columnName = $encrypted_field->db_column;
@ -144,14 +138,11 @@ class RecryptFromMcrypt extends Command
$errors[] = ' - ERROR: Could not decrypt field ['.$encrypted_field->name.']: '.$e->getMessage();
}
}
}
$asset->save();
$bar->advance();
}
$bar->finish();
if (count($errors) > 0) {
@ -162,6 +153,5 @@ class RecryptFromMcrypt extends Command
}
}
}
}
}

View file

@ -40,10 +40,7 @@ class RegenerateAssetTags extends Command
*/
public function handle()
{
if ($this->confirm('This will regenerate all of the asset tags within your system. This action is data-destructive and should be used with caution. Do you wish to continue?'))
{
if ($this->confirm('This will regenerate all of the asset tags within your system. This action is data-destructive and should be used with caution. Do you wish to continue?')) {
$output['info'] = [];
$output['warn'] = [];
$output['error'] = [];
@ -63,7 +60,6 @@ class RegenerateAssetTags extends Command
}
foreach ($total_assets as $asset) {
$start_tag++;
$output['info'][] = 'Asset tag:'.$asset->asset_tag;
$asset->asset_tag = $settings->auto_increment_prefix.$settings->auto_increment_prefix.$start_tag;
@ -81,7 +77,6 @@ class RegenerateAssetTags extends Command
$bar->finish();
$this->info("\n");
if (($this->option('output') == 'all') || ($this->option('output') == 'info')) {
foreach ($output['info'] as $key => $output_text) {
$this->info($output_text);
@ -98,7 +93,5 @@ class RegenerateAssetTags extends Command
}
}
}
}
}

View file

@ -2,7 +2,6 @@
namespace App\Console\Commands;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Console\Command;
@ -40,7 +39,6 @@ class ResetDemoSettings extends Command
*/
public function handle()
{
$this->info('Resetting the demo settings.');
$settings = Setting::first();
$settings->per_page = 20;
@ -73,7 +71,6 @@ class ResetDemoSettings extends Command
$settings->saml_slo = null;
$settings->saml_custom_settings = null;
$settings->save();
if ($user = User::where('username', '=', 'admin')->first()) {
@ -83,7 +80,5 @@ class ResetDemoSettings extends Command
\Storage::disk('local_public')->put('snipe-logo.png', file_get_contents(public_path('img/demo/snipe-logo.png')));
\Storage::disk('local_public')->put('snipe-logo-lg.png', file_get_contents(public_path('img/demo/snipe-logo-lg.png')));
}
}

View file

@ -43,16 +43,15 @@ class RestoreDeletedUsers extends Command
*/
public function handle()
{
$start_date = $this->option('start_date');
$end_date = $this->option('end_date');
$asset_totals = 0;
$license_totals = 0;
$user_count = 0;
if (($start_date == '') || ($end_date == '')) {
$this->info('ERROR: All fields are required.');
return false;
}
@ -79,7 +78,6 @@ class RestoreDeletedUsers extends Command
->update(['assigned_to' => $user->id, 'assigned_type'=> User::class]);
$this->info(' ** Asset '.$user_log->item->id.' ('.$user_log->item->asset_tag.') restored to user '.$user->id.'');
} elseif ($user_log->item_type == License::class) {
$license_totals++;
@ -91,27 +89,17 @@ class RestoreDeletedUsers extends Command
DB::table('license_seats')
->where('id', $avail_seat->id)
->update(['assigned_to' => $user->id]);
} else {
$this->warn('ERROR: No available seats for '.$user_log->item->name);
}
}
}
$this->warn('Restoring user '.$user->username.'!');
$user->restore();
}
$this->info($asset_totals.' assets affected');
$this->info($license_totals.' licenses affected');
}
}

View file

@ -3,7 +3,6 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use ZipArchive;
class RestoreFromBackup extends Command
@ -43,20 +42,20 @@ class RestoreFromBackup extends Command
public function handle()
{
$dir = getcwd();
print "Current working directory is: $dir\n";
echo "Current working directory is: $dir\n";
//
$filename = $this->argument('filename');
if (! $filename) {
return $this->error("Missing required filename");
return $this->error('Missing required filename');
}
if (! $this->option('force') && ! $this->confirm('Are you sure you wish to restore from the given backup file? This can lead to MASSIVE DATA LOSS!')) {
return $this->error("Data loss not confirmed");
return $this->error('Data loss not confirmed');
}
if (config('database.default') != 'mysql') {
return $this->error("DB_CONNECTION must be MySQL in order to perform a restore. Detected: ".config('database.default'));
return $this->error('DB_CONNECTION must be MySQL in order to perform a restore. Detected: '.config('database.default'));
}
$za = new ZipArchive();
@ -64,21 +63,20 @@ class RestoreFromBackup extends Command
$errcode = $za->open($filename, ZipArchive::RDONLY);
if ($errcode !== true) {
$errors = [
ZipArchive::ER_EXISTS => "File already exists.",
ZipArchive::ER_INCONS => "Zip archive inconsistent.",
ZipArchive::ER_INVAL => "Invalid argument.",
ZipArchive::ER_MEMORY => "Malloc failure.",
ZipArchive::ER_NOENT => "No such file.",
ZipArchive::ER_NOZIP => "Not a zip archive.",
ZipArchive::ER_EXISTS => 'File already exists.',
ZipArchive::ER_INCONS => 'Zip archive inconsistent.',
ZipArchive::ER_INVAL => 'Invalid argument.',
ZipArchive::ER_MEMORY => 'Malloc failure.',
ZipArchive::ER_NOENT => 'No such file.',
ZipArchive::ER_NOZIP => 'Not a zip archive.',
ZipArchive::ER_OPEN => "Can't open file.",
ZipArchive::ER_READ => "Read error.",
ZipArchive::ER_SEEK => "Seek error."
ZipArchive::ER_READ => 'Read error.',
ZipArchive::ER_SEEK => 'Seek error.',
];
return $this->error("Could not access file: ".$filename." - ".array_key_exists($errcode,$errors) ? $errors[$errcode] : " Unknown reason: $errcode");
return $this->error('Could not access file: '.$filename.' - '.array_key_exists($errcode, $errors) ? $errors[$errcode] : " Unknown reason: $errcode");
}
$private_dirs = [
'storage/private_uploads/assets', // these are asset _files_, not the pictures.
'storage/private_uploads/audits',
@ -86,11 +84,11 @@ class RestoreFromBackup extends Command
'storage/private_uploads/assetmodels',
'storage/private_uploads/users',
'storage/private_uploads/licenses',
'storage/private_uploads/signatures'
'storage/private_uploads/signatures',
];
$private_files = [
'storage/oauth-private.key',
'storage/oauth-public.key'
'storage/oauth-public.key',
];
$public_dirs = [
'public/uploads/companies',
@ -108,7 +106,7 @@ class RestoreFromBackup extends Command
'public/uploads/models',
'public/uploads/categories',
'public/uploads/avatars',
'public/uploads/manufacturers'
'public/uploads/manufacturers',
];
$public_files = [
@ -117,7 +115,7 @@ class RestoreFromBackup extends Command
'public/uploads/setting-label_logo*',
'public/uploads/setting-logo*',
'public/uploads/favicon.*',
'public/uploads/favicon-uploaded.*'
'public/uploads/favicon-uploaded.*',
];
$all_files = $private_dirs + $public_dirs;
@ -140,13 +138,13 @@ class RestoreFromBackup extends Command
}
// skip macOS resource fork files (?!?!?!)
if(strpos($raw_path,"__MACOSX")!==false && strpos($raw_path,"._") !== false) {
if (strpos($raw_path, '__MACOSX') !== false && strpos($raw_path, '._') !== false) {
//print "SKIPPING macOS Resource fork file: $raw_path\n";
$boring_files[] = $raw_path;
continue;
}
if(@pathinfo($raw_path)['extension'] == "sql") {
print "Found a sql file!\n";
if (@pathinfo($raw_path)['extension'] == 'sql') {
echo "Found a sql file!\n";
$sqlfiles[] = $raw_path;
$sqlfile_indices[] = $i;
continue;
@ -165,10 +163,10 @@ class RestoreFromBackup extends Command
}
}
}
$good_extensions = ["png","gif","jpg","svg","jpeg","doc","docx","pdf","txt",
"zip","rar","xls","xlsx","lic","xml","rtf", "webp","key","ico"];
$good_extensions = ['png', 'gif', 'jpg', 'svg', 'jpeg', 'doc', 'docx', 'pdf', 'txt',
'zip', 'rar', 'xls', 'xlsx', 'lic', 'xml', 'rtf', 'webp', 'key', 'ico', ];
foreach (array_merge($private_files, $public_files) as $file) {
$has_wildcard = (strpos($file,"*") !== false);
$has_wildcard = (strpos($file, '*') !== false);
if ($has_wildcard) {
$file = substr($file, 0, -1); //trim last character (which should be the wildcard)
}
@ -176,7 +174,7 @@ class RestoreFromBackup extends Command
if ($last_pos !== false) {
$extension = strtolower(pathinfo($raw_path, PATHINFO_EXTENSION));
if (! in_array($extension, $good_extensions)) {
$this->warn("Potentially unsafe file ".$raw_path." is being skipped");
$this->warn('Potentially unsafe file '.$raw_path.' is being skipped');
$boring_files[] = $raw_path;
continue 2;
}
@ -195,10 +193,10 @@ class RestoreFromBackup extends Command
// print_r($interesting_files);exit(-1);
if (count($sqlfiles) != 1) {
return $this->error("There should be exactly *one* sql backup file found, found: ".( count($sqlfiles) == 0 ? "None" : implode(", ",$sqlfiles)));
return $this->error('There should be exactly *one* sql backup file found, found: '.(count($sqlfiles) == 0 ? 'None' : implode(', ', $sqlfiles)));
}
if( strpos($sqlfiles[0], "db-dumps") === false ) {
if (strpos($sqlfiles[0], 'db-dumps') === false) {
//return $this->error("SQL backup file is missing 'db-dumps' component of full pathname: ".$sqlfiles[0]);
//older Snipe-IT installs don't have the db-dumps subdirectory component
}
@ -207,14 +205,14 @@ class RestoreFromBackup extends Command
$pipes = [];
$env_vars = getenv();
$env_vars['MYSQL_PWD'] = config("database.connections.mysql.password");
$proc_results = proc_open("mysql -h ".escapeshellarg(config('database.connections.mysql.host'))." -u ".escapeshellarg(config('database.connections.mysql.username'))." ".escapeshellarg(config('database.connections.mysql.database')), // yanked -p since we pass via ENV
$env_vars['MYSQL_PWD'] = config('database.connections.mysql.password');
$proc_results = proc_open('mysql -h '.escapeshellarg(config('database.connections.mysql.host')).' -u '.escapeshellarg(config('database.connections.mysql.username')).' '.escapeshellarg(config('database.connections.mysql.database')), // yanked -p since we pass via ENV
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
$pipes,
null,
$env_vars); // this is not super-duper awesome-secure, but definitely more secure than showing it on the CLI, or dropping temporary files with passwords in them.
if ($proc_results === false) {
return $this->error("Unable to invoke mysql via CLI");
return $this->error('Unable to invoke mysql via CLI');
}
// $this->info("Stdout says? ".fgets($pipes[1])); //FIXME: I think we might need to set non-blocking mode to use this properly?
@ -232,6 +230,7 @@ class RestoreFromBackup extends Command
$this->info($stdout);
$stderr = fgets($pipes[2]);
$this->info($stderr);
return false;
}
@ -243,6 +242,7 @@ class RestoreFromBackup extends Command
$this->info($stdout);
$stderr = fgets($pipes[2]);
$this->info($stderr);
return false;
}
}
@ -253,7 +253,7 @@ class RestoreFromBackup extends Command
//wait, have to do fclose() on all pipes first?
$close_results = proc_close($proc_results);
if ($close_results != 0) {
return $this->error("There may have been a problem with the database import: Error number ".$close_results);
return $this->error('There may have been a problem with the database import: Error number '.$close_results);
}
//and now copy the files over too (right?)
@ -263,11 +263,11 @@ class RestoreFromBackup extends Command
} else {
$bar = $this->output->createProgressBar(count($interesting_files));
}
foreach($interesting_files AS $pretty_file_name => $file_details) {
foreach ($interesting_files as $pretty_file_name => $file_details) {
$ugly_file_name = $za->statIndex($file_details['index'])['name'];
$fp = $za->getStream($ugly_file_name);
//$this->info("Weird problem, here are file details? ".print_r($file_details,true));
$migrated_file = fopen($file_details['dest']."/".basename($pretty_file_name),"w");
$migrated_file = fopen($file_details['dest'].'/'.basename($pretty_file_name), 'w');
while (($buffer = fgets($fp)) !== false) {
fwrite($migrated_file, $buffer);
}
@ -280,13 +280,12 @@ class RestoreFromBackup extends Command
}
if ($bar) {
$bar->finish();
$this->line("");
$this->line('');
} else {
$this->info(count($interesting_files)." files were succesfully transferred");
$this->info(count($interesting_files).' files were succesfully transferred');
}
foreach ($boring_files as $boring_file) {
$this->warn($boring_file." was skipped.");
}
$this->warn($boring_file.' was skipped.');
}
}
}

View file

@ -2,12 +2,12 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Artisan;
use App\Models\CustomField;
use App\Models\Asset;
use App\Models\CustomField;
use App\Models\Setting;
use \Illuminate\Encryption\Encrypter;
use Artisan;
use Illuminate\Console\Command;
use Illuminate\Encryption\Encrypter;
class RotateAppKey extends Command
{
@ -44,8 +44,6 @@ class RotateAppKey extends Command
{
if ($this->confirm("\n****************************************************\nTHIS WILL MODIFY YOUR APP_KEY AND DE-CRYPT YOUR ENCRYPTED CUSTOM FIELDS AND \nRE-ENCRYPT THEM WITH A NEWLY GENERATED KEY. \n\nThere is NO undo. \n\nMake SURE you have a database backup and a backup of your .env generated BEFORE running this command. \n\nIf you do not save the newly generated APP_KEY to your .env in this process, \nyour encrypted data will no longer be decryptable. \n\nAre you SURE you wish to continue, and have confirmed you have a database backup and an .env backup? ")) {
// Get the existing app_key and ciphers
// We put them in a variable since we clear the cache partway through here.
$old_app_key = config('app.key');
@ -73,21 +71,16 @@ class RotateAppKey extends Command
$fields = CustomField::where('field_encrypted', '1')->get();
foreach ($fields as $field) {
$assets = Asset::whereNotNull($field->db_column)->get();
foreach ($assets as $asset) {
$asset->{$field->db_column} = $oldEncrypter->decrypt($asset->{$field->db_column});
$this->line('DECRYPTED: '.$field->db_column);
$asset->{$field->db_column} = $newEncrypter->encrypt($asset->{$field->db_column});
$this->line('ENCRYPTED: '.$field->db_column);
$asset->save();
}
}
// Handle the LDAP password if one is provided
@ -98,8 +91,6 @@ class RotateAppKey extends Command
$setting->save();
$this->warn('LDAP password has been re-encrypted.');
}
} else {
$this->info('This operation has been canceled. No changes have been made.');
}
@ -113,7 +104,6 @@ class RotateAppKey extends Command
*/
protected function writeNewEnvironmentFileWith($key)
{
file_put_contents($this->laravel->environmentFilePath(), preg_replace(
$this->keyReplacementPattern(),
'APP_KEY='.$key,
@ -129,7 +119,7 @@ class RotateAppKey extends Command
protected function keyReplacementPattern()
{
$escaped = preg_quote('='.$this->laravel['config']['app.key'], '/');
return "/^APP_KEY{$escaped}/m";
}
}

View file

@ -39,22 +39,16 @@ class SendCurrentInventoryToUsers extends Command
*/
public function handle()
{
$users = User::whereNull('deleted_at')->whereNotNull('email')->with('assets', 'accessories', 'licenses')->get();
$count = 0;
foreach ($users as $user) {
if (($user->assets->count() > 0) || ($user->accessories->count() > 0) || ($user->licenses->count() > 0))
{
if (($user->assets->count() > 0) || ($user->accessories->count() > 0) || ($user->licenses->count() > 0)) {
$count++;
$user->notify((new CurrentInventory($user)));
}
}
$this->info($count.' users notified.');
}
}

View file

@ -3,12 +3,12 @@
namespace App\Console\Commands;
use App\Models\Asset;
use App\Models\Recipients\AlertRecipient;
use App\Models\Setting;
use App\Notifications\ExpectedCheckinAdminNotification;
use App\Notifications\ExpectedCheckinNotification;
use Carbon\Carbon;
use Illuminate\Console\Command;
use App\Models\Recipients\AlertRecipient;
class SendExpectedCheckinAlerts extends Command
{

View file

@ -4,13 +4,13 @@ namespace App\Console\Commands;
use App\Models\Asset;
use App\Models\License;
use App\Models\Recipients;
use App\Models\Setting;
use App\Notifications\ExpiringAssetsNotification;
use App\Models\Recipients;
use DB;
use Illuminate\Console\Command;
use App\Notifications\SendUpcomingAuditNotification;
use Carbon\Carbon;
use DB;
use Illuminate\Console\Command;
class SendUpcomingAuditReport extends Command
{
@ -54,7 +54,6 @@ class SendUpcomingAuditReport extends Command
return new \App\Models\Recipients\AlertRecipient($item);
});
// Assets due for auditing
$assets = Asset::whereNotNull('next_audit_date')
@ -62,7 +61,6 @@ class SendUpcomingAuditReport extends Command
->orderBy('last_audit_date', 'asc')->get();
if ($assets->count() > 0) {
$this->info(trans_choice('mail.upcoming-audits', $assets->count(),
['count' => $assets->count(), 'threshold' => $settings->audit_warning_days]));
\Notification::send($recipients, new SendUpcomingAuditNotification($assets, $settings->audit_warning_days));
@ -70,9 +68,6 @@ class SendUpcomingAuditReport extends Command
} else {
$this->info('No assets to be audited. No report sent.');
}
} elseif ($settings->alert_email == '') {
$this->error('Could not send email. No alert email configured in settings');
} elseif (! $settings->audit_warning_days) {
@ -85,7 +80,5 @@ class SendUpcomingAuditReport extends Command
$this->error('Admin Audit Warning Setting: '.$settings->audit_warning_days);
$this->error('Admin Alerts Emnabled: '.$settings->alerts_enabled);
}
}
}

View file

@ -63,14 +63,9 @@ class SyncAssetCounters extends Command
$time_elapsed_secs = microtime(true) - $start;
$this->info('Sync executed in '.$time_elapsed_secs.' seconds');
} else {
$this->info('No assets to sync');
}
}
}
}
}

View file

@ -38,7 +38,6 @@ class SyncAssetLocations extends Command
*/
public function handle()
{
$output['info'] = [];
$output['warn'] = [];
$output['error'] = [];
@ -51,7 +50,7 @@ class SyncAssetLocations extends Command
$output['info'][] = 'There are '.$rtd_assets->count().' unassigned assets.';
foreach ($rtd_assets as $rtd_asset) {
$output['info'][] = 'Setting Unassigned Asset ' . $rtd_asset->id . ' ('.$rtd_asset->asset_tag.') to location: ' . $rtd_asset->rtd_location_id . " because their default location is: " . $rtd_asset->rtd_location_id;
$output['info'][] = 'Setting Unassigned Asset '.$rtd_asset->id.' ('.$rtd_asset->asset_tag.') to location: '.$rtd_asset->rtd_location_id.' because their default location is: '.$rtd_asset->rtd_location_id;
$rtd_asset->location_id = $rtd_asset->rtd_location_id;
$rtd_asset->unsetEventDispatcher();
$rtd_asset->save();
@ -72,7 +71,6 @@ class SyncAssetLocations extends Command
$assigned_user_asset->unsetEventDispatcher();
$assigned_user_asset->save();
$bar->advance();
}
$assigned_location_assets = Asset::where('assigned_type', 'App\Models\Location')
@ -89,10 +87,8 @@ class SyncAssetLocations extends Command
$output['warn'][] = 'Asset '.$assigned_location_asset->id.' ('.$assigned_location_asset->asset_tag.') did not return a valid associated location - perhaps it was deleted?';
}
$bar->advance();
}
// Assigned to assets
$assigned_asset_assets = Asset::where('assigned_type', 'App\Models\Asset')
->whereNotNull('assigned_to')->whereNull('deleted_at')->get();
@ -111,10 +107,9 @@ class SyncAssetLocations extends Command
}
$bar->advance();
}
$unlocated_assets = Asset::whereNull("location_id")->whereNull('deleted_at')->get();
$unlocated_assets = Asset::whereNull('location_id')->whereNull('deleted_at')->get();
$output['info'][] = 'Assets still without a location: '.$unlocated_assets->count();
foreach ($unlocated_assets as $unlocated_asset) {
$output['warn'][] = 'Asset: '.$unlocated_asset->id.' still has no location. ';
@ -124,7 +119,6 @@ class SyncAssetLocations extends Command
$bar->finish();
$this->info("\n");
if (($this->option('output') == 'all') || ($this->option('output') == 'info')) {
foreach ($output['info'] as $key => $output_text) {
$this->info($output_text);
@ -140,7 +134,5 @@ class SyncAssetLocations extends Command
$this->error($output_text);
}
}
}
}

View file

@ -6,7 +6,6 @@ use Illuminate\Console\Command;
class SystemBackup extends Command
{
/**
* The console command name.
*
@ -40,6 +39,5 @@ class SystemBackup extends Command
{
//
$this->call('backup:run');
}
}

View file

@ -37,7 +37,6 @@ class Version extends Command
*/
public function handle()
{
$use_branch = $this->option('branch');
$use_type = $this->option('type');
$git_branch = trim(shell_exec('git rev-parse --abbrev-ref HEAD'));
@ -64,36 +63,33 @@ class Version extends Command
}
}
$app_version_raw = explode('.', $app_version);
$maj = str_replace('v', '', $app_version_raw[0]);
$min = $app_version_raw[1];
$patch = '';
// This is a major release that might not have a third .0
if (array_key_exists(2, $app_version_raw)) {
$patch = $app_version_raw[2];
}
if ($use_type == 'major') {
$app_version = "v".($maj + 1).".$min.$patch";
$app_version = 'v'.($maj + 1).".$min.$patch";
} elseif ($use_type == 'minor') {
$app_version = "v"."$maj.".($min + 1).".$patch";
$app_version = 'v'."$maj.".($min + 1).".$patch";
} elseif ($use_type == 'pre') {
$pre_raw = str_replace('beta', '', $prerelease_version);
$pre_raw = str_replace('alpha', '', $pre_raw);
$pre_raw = str_ireplace('rc', '', $pre_raw);
$pre_raw = $pre_raw++;
$this->line('Setting the pre-release to '.$prerelease_version.'-'.$pre_raw);
$app_version = "v"."$maj.".($min + 1).".$patch";
$app_version = 'v'."$maj.".($min + 1).".$patch";
} elseif ($use_type == 'patch') {
$app_version = "v" . "$maj.$min." . ($patch + 1);
$app_version = 'v'."$maj.$min.".($patch + 1);
// If nothing is passed, leave the version as it is, just increment the build
} else {
$app_version = "v" . "$maj.$min." . $patch;
$app_version = 'v'."$maj.$min.".$patch;
}
// Determine if this tag already exists, or if this prior to a release
@ -106,21 +102,18 @@ class Version extends Command
$full_app_version = $app_version.' - build '.$build_version.'-'.$hash_version;
$array = var_export(
array(
[
'app_version' => $app_version,
'full_app_version' => $full_app_version,
'build_version' => $build_version,
'prerelease_version' => $prerelease_version,
'hash_version' => $hash_version,
'full_hash' => $full_hash_version,
'branch' => $git_branch),
'branch' => $git_branch, ],
true
);
// Construct our file content
$content = <<<CON
<?php
@ -131,5 +124,4 @@ CON;
\File::put($versionFile, $content);
$this->info('Setting NEW version: '.$full_app_version.' ('.$git_branch.')');
}
}

View file

@ -10,7 +10,6 @@ use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*

View file

@ -6,17 +6,17 @@ use Exception;
class CheckoutNotAllowed extends Exception
{
private $errorMessage;
function __construct($errorMessage = null)
public function __construct($errorMessage = null)
{
$this->errorMessage = $errorMessage;
parent::__construct($errorMessage);
}
public function __toString()
{
return is_null($this->errorMessage) ? "A checkout is not allowed under these circumstances" : $this->errorMessage;
return is_null($this->errorMessage) ? 'A checkout is not allowed under these circumstances' : $this->errorMessage;
}
}

View file

@ -2,14 +2,13 @@
namespace App\Exceptions;
use App\Helpers\Helper;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use App\Helpers\Helper;
use Illuminate\Validation\ValidationException;
use Log;
class Handler extends ExceptionHandler
{
/**
@ -40,6 +39,7 @@ class Handler extends ExceptionHandler
{
if ($this->shouldReport($exception)) {
\Log::error($exception);
return parent::report($exception);
}
}
@ -54,23 +54,20 @@ class Handler extends ExceptionHandler
public function render($request, Exception $e)
{
// CSRF token mismatch error
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->back()->with('error', trans('general.token_expired'));
}
// Handle Ajax requests that fail because the model doesn't exist
if ($request->ajax() || $request->wantsJson()) {
if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
$className = last(explode('\\', $e->getModel()));
return response()->json(Helper::formatStandardApiResponse('error', null, $className.' not found'), 200);
}
if ($this->isHttpException($e)) {
$statusCode = $e->getStatusCode();
switch ($e->getStatusCode()) {
@ -85,15 +82,13 @@ class Handler extends ExceptionHandler
}
}
if ($this->isHttpException($e) && (isset($statusCode)) && ($statusCode == '404')) {
return response()->view('layouts/basic', [
'content' => view('errors/404')
'content' => view('errors/404'),
], $statusCode);
}
return parent::render($request, $e);
}
/**

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,13 @@
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Storage;
class StorageHelper
{
static function downloader($filename, $disk = 'default') {
public static function downloader($filename, $disk = 'default')
{
if ($disk == 'default') {
$disk = config('filesystems.default');
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Accessories;
use App\Helpers\Helper;
@ -30,10 +31,10 @@ class AccessoriesController extends Controller
public function index()
{
$this->authorize('index', Accessory::class);
return view('accessories/index');
}
/**
* Returns a view with a form to create a new Accessory.
*
@ -45,11 +46,11 @@ class AccessoriesController extends Controller
{
$this->authorize('create', Accessory::class);
$category_type = 'accessory';
return view('accessories/edit')->with('category_type', $category_type)
->with('item', new Accessory);
}
/**
* Validate and save new Accessory from form post
*
@ -86,6 +87,7 @@ class AccessoriesController extends Controller
// Redirect to the new accessory page
return redirect()->route('accessories.index')->with('success', trans('admin/accessories/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($accessory->getErrors());
}
@ -99,17 +101,15 @@ class AccessoriesController extends Controller
*/
public function edit($accessoryId = null)
{
if ($item = Accessory::find($accessoryId)) {
$this->authorize($item);
return view('accessories/edit', compact('item'))->with('category_type', 'accessory');
}
return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.does_not_exist'));
}
/**
* Save edited Accessory from form post
*
@ -147,6 +147,7 @@ class AccessoriesController extends Controller
if ($accessory->save()) {
return redirect()->route('accessories.index')->with('success', trans('admin/accessories/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($accessory->getErrors());
}
@ -166,9 +167,8 @@ class AccessoriesController extends Controller
$this->authorize($accessory);
if ($accessory->hasUsers() > 0) {
return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.assoc_users', array('count'=> $accessory->hasUsers())));
return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.assoc_users', ['count'=> $accessory->hasUsers()]));
}
if ($accessory->image) {
@ -180,10 +180,10 @@ class AccessoriesController extends Controller
}
$accessory->delete();
return redirect()->route('accessories.index')->with('success', trans('admin/accessories/message.delete.success'));
}
/**
* Returns a view that invokes the ajax table which contains
* the content for the accessory detail view, which is generated in getDataView.
@ -202,6 +202,7 @@ class AccessoriesController extends Controller
if (isset($accessory->id)) {
return view('accessories/view', compact('accessory'));
}
return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.does_not_exist', ['id' => $accessoryID]));
}
}

View file

@ -17,7 +17,7 @@ class AccessoryCheckinController extends Controller
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param Request $request
* @param integer $accessoryUserId
* @param int $accessoryUserId
* @param string $backto
* @return View
* @internal param int $accessoryId
@ -33,6 +33,7 @@ class AccessoryCheckinController extends Controller
$accessory = Accessory::find($accessory_user->accessory_id);
$this->authorize('checkin', $accessory);
return view('accessories/checkin', compact('accessory'))->with('backto', $backto);
}
@ -70,7 +71,7 @@ class AccessoryCheckinController extends Controller
event(new CheckoutableCheckedIn($accessory, User::find($return_to), Auth::user(), $request->input('note'), $checkin_at));
return redirect()->route("accessories.show", $accessory->id)->with('success', trans('admin/accessories/message.checkin.success'));
return redirect()->route('accessories.show', $accessory->id)->with('success', trans('admin/accessories/message.checkin.success'));
}
// Redirect to the accessory management page with error
return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.checkin.error'));

View file

@ -14,7 +14,6 @@ use Illuminate\Support\Facades\Input;
class AccessoryCheckoutController extends Controller
{
/**
* Return the form to checkout an Accessory to a user.
*
@ -32,7 +31,6 @@ class AccessoryCheckoutController extends Controller
}
if ($accessory->category) {
$this->authorize('checkout', $accessory);
// Get the dropdown of users and then pass it to the checkout view
@ -76,7 +74,7 @@ class AccessoryCheckoutController extends Controller
'created_at' => Carbon::now(),
'user_id' => Auth::id(),
'assigned_to' => $request->get('assigned_to'),
'note' => $request->input('note')
'note' => $request->input('note'),
]);
DB::table('accessories_users')->where('assigned_to', '=', $accessory->assigned_to)->where('accessory_id', '=', $accessory->id)->first();

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Account;
use App\Events\CheckoutAccepted;
@ -14,14 +15,15 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class AcceptanceController extends Controller {
class AcceptanceController extends Controller
{
/**
* Show a listing of pending checkout acceptances for the current user
*
* @return View
*/
public function index() {
public function index()
{
$acceptances = CheckoutAcceptance::forUser(Auth::user())->pending()->get();
return view('account/accept.index', compact('acceptances'));
@ -33,8 +35,8 @@ class AcceptanceController extends Controller {
* @param int $id
* @return mixed
*/
public function create($id) {
public function create($id)
{
$acceptance = CheckoutAcceptance::find($id);
if (is_null($acceptance)) {
@ -63,8 +65,8 @@ class AcceptanceController extends Controller {
* @param int $id
* @return Redirect
*/
public function store(Request $request, $id) {
public function store(Request $request, $id)
{
$acceptance = CheckoutAcceptance::find($id);
if (is_null($acceptance)) {
@ -90,36 +92,31 @@ class AcceptanceController extends Controller {
/**
* Get the signature and save it
*/
if (!Storage::exists('private_uploads/signatures')) Storage::makeDirectory('private_uploads/signatures', 775);
if (! Storage::exists('private_uploads/signatures')) {
Storage::makeDirectory('private_uploads/signatures', 775);
}
$sig_filename = '';
if ($request->filled('signature_output')) {
$sig_filename = "siglog-" .Str::uuid() . '-'.date('Y-m-d-his').".png";
$sig_filename = 'siglog-'.Str::uuid().'-'.date('Y-m-d-his').'.png';
$data_uri = e($request->input('signature_output'));
$encoded_image = explode(",", $data_uri);
$encoded_image = explode(',', $data_uri);
$decoded_image = base64_decode($encoded_image[1]);
Storage::put('private_uploads/signatures/'.$sig_filename, (string) $decoded_image);
}
if ($request->input('asset_acceptance') == 'accepted') {
$acceptance->accept($sig_filename);
event(new CheckoutAccepted($acceptance));
$return_msg = trans('admin/users/message.accepted');
} else {
$acceptance->decline($sig_filename);
event(new CheckoutDeclined($acceptance));
$return_msg = trans('admin/users/message.declined');
}
return redirect()->to('account/accept')->with('success', $return_msg);

View file

@ -13,6 +13,7 @@ class ActionlogController extends Controller
$file = config('app.private_uploads').'/signatures/'.$filename;
$filetype = Helper::checkUploadIsImage($file);
$contents = file_get_contents($file);
return Response::make($contents)->header('Content-Type', $filetype);
}
}

View file

@ -9,8 +9,8 @@ use App\Http\Transformers\SelectlistTransformer;
use App\Models\Accessory;
use App\Models\Company;
use App\Models\User;
use Carbon\Carbon;
use Auth;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
@ -57,7 +57,6 @@ class AccessoriesController extends Controller
// Check to make sure the limit is not higher than the max allowed
((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results');
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array($request->input('sort'), $allowed_columns) ? $request->input('sort') : 'created_at';
@ -77,10 +76,10 @@ class AccessoriesController extends Controller
$total = $accessories->count();
$accessories = $accessories->skip($offset)->take($limit)->get();
return (new AccessoriesTransformer)->transformAccessories($accessories, $total);
}
/**
* Store a newly created resource in storage.
*
@ -98,8 +97,8 @@ class AccessoriesController extends Controller
if ($accessory->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $accessory, trans('admin/accessories/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $accessory->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $accessory->getErrors()));
}
/**
@ -114,10 +113,10 @@ class AccessoriesController extends Controller
{
$this->authorize('view', Accessory::class);
$accessory = Accessory::findOrFail($id);
return (new AccessoriesTransformer)->transformAccessory($accessory);
}
/**
* Display the specified resource.
*
@ -130,10 +129,10 @@ class AccessoriesController extends Controller
{
$this->authorize('view', Accessory::class);
$accessory = Accessory::findOrFail($id);
return (new AccessoriesTransformer)->transformAccessory($accessory);
}
/**
* Display the specified resource.
*
@ -174,7 +173,6 @@ class AccessoriesController extends Controller
return (new AccessoriesTransformer)->transformCheckedoutAccessory($accessory, $accessory_users, $total);
}
/**
* Update the specified resource in storage.
*
@ -212,15 +210,14 @@ class AccessoriesController extends Controller
$this->authorize($accessory);
if ($accessory->hasUsers() > 0) {
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.assoc_users', array('count'=> $accessory->hasUsers()))));
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.assoc_users', ['count'=> $accessory->hasUsers()])));
}
$accessory->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/accessories/message.delete.success')));
}
/**
* Save the Accessory checkout information.
*
@ -240,9 +237,7 @@ class AccessoriesController extends Controller
$this->authorize('checkout', $accessory);
if ($accessory->numRemaining() > 0) {
if (! $user = User::find($request->input('assigned_to'))) {
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.checkout.user_does_not_exist')));
}
@ -255,7 +250,7 @@ class AccessoriesController extends Controller
'created_at' => Carbon::now(),
'user_id' => Auth::id(),
'assigned_to' => $request->get('assigned_to'),
'note' => $request->get('note')
'note' => $request->get('note'),
]);
$accessory->logCheckout($request->input('note'), $user);
@ -264,7 +259,6 @@ class AccessoriesController extends Controller
}
return response()->json(Helper::formatStandardApiResponse('error', null, 'No accessories remaining'));
}
/**
@ -273,7 +267,7 @@ class AccessoriesController extends Controller
* @uses Accessory::checkin_email() to determine if an email can and should be sent
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param Request $request
* @param integer $accessoryUserId
* @param int $accessoryUserId
* @param string $backto
* @return Redirect
* @internal param int $accessoryId
@ -307,22 +301,18 @@ class AccessoriesController extends Controller
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/accessories/message.checkin.error')));
}
/**
* Gets a paginated collection for the select2 menus
*
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$accessories = Accessory::select([
'accessories.id',
'accessories.name'
'accessories.name',
]);
if ($request->filled('search')) {
@ -331,10 +321,6 @@ class AccessoriesController extends Controller
$accessories = $accessories->orderBy('name', 'ASC')->paginate(50);
return (new SelectlistTransformer)->transformSelectlist($accessories);
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Api;
use App\Helpers\Helper;
@ -20,8 +21,6 @@ use Illuminate\Support\Facades\Input;
*/
class AssetMaintenancesController extends Controller
{
/**
* Generates the JSON response for asset maintenances listing view.
*
@ -29,7 +28,7 @@ class AssetMaintenancesController extends Controller
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
* @since [v1.8]
* @return String JSON
* @return string JSON
*/
public function index(Request $request)
{
@ -50,7 +49,6 @@ class AssetMaintenancesController extends Controller
// Check to make sure the limit is not higher than the max allowed
((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results');
$allowed_columns = [
'id',
'title',
@ -62,7 +60,7 @@ class AssetMaintenancesController extends Controller
'notes',
'asset_tag',
'asset_name',
'user_id'
'user_id',
];
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'created_at';
@ -84,12 +82,10 @@ class AssetMaintenancesController extends Controller
$total = $maintenances->count();
$maintenances = $maintenances->skip($offset)->take($limit)->get();
return (new AssetMaintenancesTransformer())->transformAssetMaintenances($maintenances, $total);
}
/**
* Validates and stores the new asset maintenance
*
@ -97,7 +93,7 @@ class AssetMaintenancesController extends Controller
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
* @since [v1.8]
* @return String JSON
* @return string JSON
*/
public function store(Request $request)
{
@ -122,8 +118,8 @@ class AssetMaintenancesController extends Controller
$assetMaintenance->user_id = Auth::id();
if (($assetMaintenance->completion_date !== null)
&& ( $assetMaintenance->start_date !== "" )
&& ( $assetMaintenance->start_date !== "0000-00-00" )
&& ($assetMaintenance->start_date !== '')
&& ($assetMaintenance->start_date !== '0000-00-00')
) {
$startDate = Carbon::parse($assetMaintenance->start_date);
$completionDate = Carbon::parse($assetMaintenance->completion_date);
@ -133,14 +129,11 @@ class AssetMaintenancesController extends Controller
// Was the asset maintenance created?
if ($assetMaintenance->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $assetMaintenance, trans('admin/asset_maintenances/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $assetMaintenance->getErrors()));
}
/**
* Validates and stores an update to an asset maintenance
*
@ -149,7 +142,7 @@ class AssetMaintenancesController extends Controller
* @param int $request
* @version v1.0
* @since [v4.0]
* @return String JSON
* @return string JSON
*/
public function update(Request $request, $assetMaintenanceId = null)
{
@ -188,8 +181,8 @@ class AssetMaintenancesController extends Controller
}
if (($assetMaintenance->completion_date !== null)
&& ( $assetMaintenance->start_date !== "" )
&& ( $assetMaintenance->start_date !== "0000-00-00" )
&& ($assetMaintenance->start_date !== '')
&& ($assetMaintenance->start_date !== '0000-00-00')
) {
$startDate = Carbon::parse($assetMaintenance->start_date);
$completionDate = Carbon::parse($assetMaintenance->completion_date);
@ -198,10 +191,9 @@ class AssetMaintenancesController extends Controller
// Was the asset maintenance created?
if ($assetMaintenance->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $assetMaintenance, trans('admin/asset_maintenances/message.edit.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $assetMaintenance->getErrors()));
}
@ -212,7 +204,7 @@ class AssetMaintenancesController extends Controller
* @param int $assetMaintenanceId
* @version v1.0
* @since [v4.0]
* @return String JSON
* @return string JSON
*/
public function destroy($assetMaintenanceId)
{
@ -226,8 +218,6 @@ class AssetMaintenancesController extends Controller
$assetMaintenance->delete();
return response()->json(Helper::formatStandardApiResponse('success', $assetMaintenance, trans('admin/asset_maintenances/message.delete.success')));
}
/**
@ -237,7 +227,7 @@ class AssetMaintenancesController extends Controller
* @param int $assetMaintenanceId
* @version v1.0
* @since [v4.0]
* @return String JSON
* @return string JSON
*/
public function show($assetMaintenanceId)
{
@ -245,7 +235,7 @@ class AssetMaintenancesController extends Controller
if (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) {
return response()->json(Helper::formatStandardApiResponse('error', null, 'You cannot view a maintenance for that asset'));
}
return (new AssetMaintenancesTransformer())->transformAssetMaintenance($assetMaintenance);
return (new AssetMaintenancesTransformer())->transformAssetMaintenance($assetMaintenance);
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Api;
use App\Helpers\Helper;
@ -42,7 +43,7 @@ class AssetModelsController extends Controller
'manufacturer',
'requestable',
'assets_count',
'category'
'category',
];
$assetmodels = AssetModel::select([
@ -64,8 +65,6 @@ class AssetModelsController extends Controller
->with('category', 'depreciation', 'manufacturer', 'fieldset')
->withCount('assets as assets_count');
if ($request->filled('status')) {
$assetmodels->onlyTrashed();
}
@ -98,10 +97,10 @@ class AssetModelsController extends Controller
$total = $assetmodels->count();
$assetmodels = $assetmodels->skip($offset)->take($limit)->get();
return (new AssetModelsTransformer)->transformAssetModels($assetmodels, $total);
}
/**
* Store a newly created resource in storage.
*
@ -119,8 +118,8 @@ class AssetModelsController extends Controller
if ($assetmodel->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $assetmodel, trans('admin/models/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $assetmodel->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $assetmodel->getErrors()));
}
/**
@ -135,6 +134,7 @@ class AssetModelsController extends Controller
{
$this->authorize('view', AssetModel::class);
$assetmodel = AssetModel::withCount('assets as assets_count')->findOrFail($id);
return (new AssetModelsTransformer)->transformAssetModel($assetmodel);
}
@ -150,10 +150,10 @@ class AssetModelsController extends Controller
{
$this->authorize('view', AssetModel::class);
$assets = Asset::where('model_id', '=', $id)->get();
return (new AssetsTransformer)->transformAssets($assets, $assets->count());
}
/**
* Update the specified resource in storage.
*
@ -178,10 +178,9 @@ class AssetModelsController extends Controller
* it, but I'll be damned if I can think of one. - snipe
*/
if ($request->filled('custom_fieldset_id')) {
$assetmodel->fieldset_id = $request->get("custom_fieldset_id");
$assetmodel->fieldset_id = $request->get('custom_fieldset_id');
}
if ($assetmodel->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $assetmodel, trans('admin/models/message.update.success')));
}
@ -216,8 +215,8 @@ class AssetModelsController extends Controller
}
$assetmodel->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/models/message.delete.success')));
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/models/message.delete.success')));
}
/**
@ -226,11 +225,9 @@ class AssetModelsController extends Controller
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$assetmodels = AssetModel::select([
'models.id',
'models.name',
@ -249,7 +246,6 @@ class AssetModelsController extends Controller
$assetmodels = $assetmodels->OrderCategory('ASC')->OrderManufacturer('ASC')->orderby('models.name', 'asc')->orderby('models.model_number', 'asc')->paginate(50);
foreach ($assetmodels as $assetmodel) {
$assetmodel->use_text = '';
if ($settings->modellistCheckedValue('category')) {
@ -271,5 +267,4 @@ class AssetModelsController extends Controller
return (new SelectlistTransformer)->transformSelectlist($assetmodels);
}
}

View file

@ -1,7 +1,7 @@
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Support\Facades\Gate;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Http\Requests\AssetCheckoutRequest;
@ -20,6 +20,7 @@ use Auth;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Input;
use Paginator;
use Slack;
@ -27,7 +28,6 @@ use Str;
use TCPDF;
use Validator;
/**
* This class controls all actions related to assets for
* the Snipe-IT Asset Management application.
@ -37,7 +37,6 @@ use Validator;
*/
class AssetsController extends Controller
{
/**
* Returns JSON listing of all assets
*
@ -48,7 +47,6 @@ class AssetsController extends Controller
*/
public function index(Request $request, $audit = null)
{
$this->authorize('index', Asset::class);
$settings = Setting::getSettings();
@ -76,7 +74,7 @@ class AssetsController extends Controller
'requests_counter',
];
$filter = array();
$filter = [];
if ($request->filled('filter')) {
$filter = json_decode($request->input('filter'), true);
@ -87,11 +85,10 @@ class AssetsController extends Controller
$allowed_columns[] = $field->db_column_name();
}
$assets = Company::scopeCompanyables(Asset::select('assets.*'),"company_id","assets")
$assets = Company::scopeCompanyables(Asset::select('assets.*'), 'company_id', 'assets')
->with('location', 'assetstatus', 'assetlog', 'company', 'defaultLoc','assignedTo',
'model.category', 'model.manufacturer', 'model.fieldset', 'supplier');
// These are used by the API to query against specific ID numbers.
// They are also used by the individual searches on detail pages like
// locations, etc.
@ -146,7 +143,6 @@ class AssetsController extends Controller
// case we override with the actual count, so we should return 0 items.
$offset = (($assets) && ($request->get('offset') > $assets->count())) ? $assets->count() : $request->get('offset', 0);
// Check to make sure the limit is not higher than the max allowed
((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results');
@ -154,7 +150,6 @@ class AssetsController extends Controller
// This is used by the audit reporting routes
if (Gate::allows('audit', Asset::class)) {
switch ($audit) {
case 'due':
$assets->DueOrOverdueForAudit($settings);
@ -165,8 +160,6 @@ class AssetsController extends Controller
}
}
// This is used by the sidenav, mostly
// We switched from using query scopes here because of a Laravel bug
@ -178,7 +171,7 @@ class AssetsController extends Controller
break;
case 'Pending':
$assets->join('status_labels AS status_alias', function ($join) {
$join->on('status_alias.id', "=", "assets.status_id")
$join->on('status_alias.id', '=', 'assets.status_id')
->where('status_alias.deployable', '=', 0)
->where('status_alias.pending', '=', 1)
->where('status_alias.archived', '=', 0);
@ -187,7 +180,7 @@ class AssetsController extends Controller
case 'RTD':
$assets->whereNull('assets.assigned_to')
->join('status_labels AS status_alias', function ($join) {
$join->on('status_alias.id', "=", "assets.status_id")
$join->on('status_alias.id', '=', 'assets.status_id')
->where('status_alias.deployable', '=', 1)
->where('status_alias.pending', '=', 0)
->where('status_alias.archived', '=', 0);
@ -198,7 +191,7 @@ class AssetsController extends Controller
break;
case 'Archived':
$assets->join('status_labels AS status_alias', function ($join) {
$join->on('status_alias.id', "=", "assets.status_id")
$join->on('status_alias.id', '=', 'assets.status_id')
->where('status_alias.deployable', '=', 0)
->where('status_alias.pending', '=', 0)
->where('status_alias.archived', '=', 1);
@ -207,7 +200,7 @@ class AssetsController extends Controller
case 'Requestable':
$assets->where('assets.requestable', '=', 1)
->join('status_labels AS status_alias', function ($join) {
$join->on('status_alias.id', "=", "assets.status_id")
$join->on('status_alias.id', '=', 'assets.status_id')
->where('status_alias.deployable', '=', 1)
->where('status_alias.pending', '=', 0)
->where('status_alias.archived', '=', 0);
@ -223,27 +216,25 @@ class AssetsController extends Controller
if ((! $request->filled('status_id')) && ($settings->show_archived_in_list != '1')) {
// terrible workaround for complex-query Laravel bug in fulltext
$assets->join('status_labels AS status_alias', function ($join) {
$join->on('status_alias.id', "=", "assets.status_id")
$join->on('status_alias.id', '=', 'assets.status_id')
->where('status_alias.archived', '=', 0);
});
// If there is a status ID, don't take show_archived_in_list into consideration
} else {
$assets->join('status_labels AS status_alias', function ($join) {
$join->on('status_alias.id', "=", "assets.status_id");
$join->on('status_alias.id', '=', 'assets.status_id');
});
}
}
if ((! is_null($filter)) && (count($filter)) > 0) {
$assets->ByFilter($filter);
} elseif ($request->filled('search')) {
$assets->TextSearch($request->input('search'));
}
// This is kinda gross, but we need to do this because the Bootstrap Tables
// API passes custom field ordering as custom_fields.fieldname, and we have to strip
// that out to let the default sorter below order them correctly on the assets table.
@ -253,7 +244,6 @@ class AssetsController extends Controller
// in the allowed_columns array)
$column_sort = in_array($sort_override, $allowed_columns) ? $sort_override : 'assets.created_at';
switch ($sort_override) {
case 'model':
$assets->OrderModels($order);
@ -289,14 +279,12 @@ class AssetsController extends Controller
break;
}
$total = $assets->count();
$assets = $assets->skip($offset)->take($limit)->get();
// dd($assets);
return (new AssetsTransformer)->transformAssets($assets, $total);
}
/**
* Returns JSON with information about an asset (by tag) for detail view.
*
@ -309,10 +297,11 @@ class AssetsController extends Controller
{
if ($asset = Asset::with('assetstatus')->with('assignedTo')->where('asset_tag', $tag)->first()) {
$this->authorize('view', $asset);
return (new AssetsTransformer)->transformAsset($asset);
}
return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200);
return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200);
}
/**
@ -330,11 +319,10 @@ class AssetsController extends Controller
->withTrashed()->where('serial', $serial)->get()) {
return (new AssetsTransformer)->transformAssets($assets, $assets->count());
}
return response()->json(Helper::formatStandardApiResponse('error', null, 'Asset not found'), 200);
}
/**
* Returns JSON with information about an asset for detail view.
*
@ -348,32 +336,30 @@ class AssetsController extends Controller
if ($asset = Asset::with('assetstatus')->with('assignedTo')->withTrashed()
->withCount('checkins as checkins_count', 'checkouts as checkouts_count', 'userRequests as user_requests_count')->findOrFail($id)) {
$this->authorize('view', $asset);
return (new AssetsTransformer)->transformAsset($asset);
}
}
public function licenses($id)
{
$this->authorize('view', Asset::class);
$this->authorize('view', License::class);
$asset = Asset::where('id', $id)->withTrashed()->first();
$licenses = $asset->licenses()->get();
return (new LicensesTransformer())->transformLicenses($licenses, $licenses->count());
}
/**
* Gets a paginated collection for the select2 menus
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$assets = Company::scopeCompanyables(Asset::select([
'assets.id',
'assets.name',
@ -381,7 +367,7 @@ class AssetsController extends Controller
'assets.model_id',
'assets.assigned_to',
'assets.assigned_type',
'assets.status_id'
'assets.status_id',
])->with('model', 'assetstatus', 'assignedTo')->NotArchived(), 'company_id', 'assets');
if ($request->filled('assetStatusType') && $request->input('assetStatusType') === 'RTD') {
@ -392,22 +378,18 @@ class AssetsController extends Controller
$assets = $assets->AssignedSearch($request->input('search'));
}
$assets = $assets->paginate(50);
// Loop through and set some custom properties for the transformer to use.
// This lets us have more flexibility in special cases like assets, where
// they may not have a ->name value but we want to display something anyway
foreach ($assets as $asset) {
$asset->use_text = $asset->present()->fullName;
if (($asset->checkedOutToUser()) && ($asset->assigned)) {
$asset->use_text .= ' → '.$asset->assigned->getFullNameAttribute();
}
if ($asset->assetstatus->getStatuslabelType() == 'pending') {
$asset->use_text .= '('.$asset->assetstatus->getStatuslabelType().')';
}
@ -416,10 +398,8 @@ class AssetsController extends Controller
}
return (new SelectlistTransformer)->transformSelectlist($assets);
}
/**
* Accepts a POST request to create a new asset
*
@ -430,7 +410,6 @@ class AssetsController extends Controller
*/
public function store(Request $request)
{
$this->authorize('create', Asset::class);
$asset = new Asset();
@ -457,7 +436,7 @@ class AssetsController extends Controller
$asset->rtd_location_id = $request->get('rtd_location_id', null);
$asset->location_id = $request->get('rtd_location_id', null);
if ($request->has('image_source') && $request->input('image_source') != "") {
if ($request->has('image_source') && $request->input('image_source') != '') {
$saved_image_path = Helper::processUploadedImage(
$request->input('image_source'), 'uploads/assets/'
);
@ -491,7 +470,6 @@ class AssetsController extends Controller
// if the field is set to encrypted, make sure we encrypt the value
if ($field->field_encrypted == '1') {
\Log::debug('This model field is encrypted in this fieldset.');
if (Gate::allows('admin')) {
@ -505,14 +483,11 @@ class AssetsController extends Controller
}
}
$asset->{$field->convertUnicodeDbSlug()} = $field_val;
}
}
if ($asset->save()) {
if ($request->get('assigned_user')) {
$target = User::find(request('assigned_user'));
} elseif ($request->get('assigned_asset')) {
@ -534,7 +509,6 @@ class AssetsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200);
}
/**
* Accepts a POST request to update an asset
*
@ -560,9 +534,8 @@ class AssetsController extends Controller
($request->filled('rtd_location_id')) ?
$asset->location_id = $request->get('rtd_location_id') : null;
if ($request->filled('image_source')) {
if ($request->input('image_source') == "") {
if ($request->input('image_source') == '') {
($request->filled('rtd_location_id')) ?
$asset->location_id = $request->get('rtd_location_id') : null;
$asset->image = null;
@ -598,9 +571,7 @@ class AssetsController extends Controller
}
}
if ($asset->save()) {
if (($request->filled('assigned_user')) && ($target = User::find($request->get('assigned_user')))) {
$location = $target->location_id;
} elseif (($request->filled('assigned_asset')) && ($target = Asset::find($request->get('assigned_asset')))) {
@ -608,7 +579,6 @@ class AssetsController extends Controller
Asset::where('assigned_type', '\\App\\Models\\Asset')->where('assigned_to', $id)
->update(['location_id' => $target->location_id]);
} elseif (($request->filled('assigned_location')) && ($target = Location::find($request->get('assigned_location')))) {
$location = $target->id;
}
@ -623,12 +593,13 @@ class AssetsController extends Controller
return response()->json(Helper::formatStandardApiResponse('success', $asset, trans('admin/hardware/message.update.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200);
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 200);
}
/**
* Delete a given asset (mark as deleted).
*
@ -642,12 +613,11 @@ class AssetsController extends Controller
$this->authorize('delete', Asset::class);
if ($asset = Asset::find($id)) {
$this->authorize('delete', $asset);
DB::table('assets')
->where('id', $asset->id)
->update(array('assigned_to' => null));
->update(['assigned_to' => null]);
$asset->delete();
@ -657,8 +627,6 @@ class AssetsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')), 200);
}
/**
* Checkout an asset
*
@ -684,14 +652,12 @@ class AssetsController extends Controller
'asset_tag' => $asset->asset_tag,
];
// This item is checked out to a location
if (request('checkout_to_type') == 'location') {
$target = Location::find(request('assigned_location'));
$asset->location_id = ($target) ? $target->id : '';
$error_payload['target_id'] = $request->input('assigned_location');
$error_payload['target_type'] = 'location';
} elseif (request('checkout_to_type') == 'asset') {
$target = Asset::where('id', '!=', $asset_id)->find(request('assigned_asset'));
$asset->location_id = $target->rtd_location_id;
@ -699,7 +665,6 @@ class AssetsController extends Controller
$asset->location_id = (($target) && (isset($target->location_id))) ? $target->location_id : '';
$error_payload['target_id'] = $request->input('assigned_asset');
$error_payload['target_type'] = 'asset';
} elseif (request('checkout_to_type') == 'user') {
// Fetch the target and set the asset's new location_id
$target = User::find(request('assigned_user'));
@ -708,15 +673,11 @@ class AssetsController extends Controller
$error_payload['target_type'] = 'user';
}
if (! isset($target)) {
return response()->json(Helper::formatStandardApiResponse('error', $error_payload, 'Checkout target for asset '.e($asset->asset_tag).' is invalid - '.$error_payload['target_type'].' does not exist.'));
}
$checkout_at = request('checkout_at', date("Y-m-d H:i:s"));
$checkout_at = request('checkout_at', date('Y-m-d H:i:s'));
$expected_checkin = request('expected_checkin', null);
$note = request('note', null);
$asset_name = request('name', null);
@ -725,13 +686,10 @@ class AssetsController extends Controller
// Wait, why are we doing this? This overrides the stuff we set further up, which makes no sense.
// TODO: Follow up here. WTF. Commented out for now.
// if ((isset($target->rtd_location_id)) && ($asset->rtd_location_id!='')) {
// $asset->location_id = $target->rtd_location_id;
// }
if ($asset->checkOut($target, Auth::user(), $checkout_at, $expected_checkin, $note, $asset_name, $asset->location_id)) {
return response()->json(Helper::formatStandardApiResponse('success', ['asset'=> e($asset->asset_tag)], trans('admin/hardware/message.checkout.success')));
}
@ -739,7 +697,6 @@ class AssetsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', ['asset'=> e($asset->asset_tag)], trans('admin/hardware/message.checkout.error')));
}
/**
* Checkin an asset
*
@ -754,7 +711,6 @@ class AssetsController extends Controller
$asset = Asset::findOrFail($asset_id);
$this->authorize('checkin', $asset);
$user = $asset->assignedUser;
if (is_null($target = $asset->assignedTo)) {
return response()->json(Helper::formatStandardApiResponse('error', ['asset'=> e($asset->asset_tag)], trans('admin/hardware/message.checkin.already_checked_in')));
@ -782,13 +738,13 @@ class AssetsController extends Controller
if ($asset->save()) {
$asset->logCheckin($target, e($request->input('note')));
return response()->json(Helper::formatStandardApiResponse('success', ['asset'=> e($asset->asset_tag)], trans('admin/hardware/message.checkin.success')));
}
return response()->json(Helper::formatStandardApiResponse('success', ['asset'=> e($asset->asset_tag)], trans('admin/hardware/message.checkin.error')));
}
/**
* Mark an asset as audited
*
@ -797,15 +753,14 @@ class AssetsController extends Controller
* @since [v4.0]
* @return JsonResponse
*/
public function audit(Request $request) {
public function audit(Request $request)
{
$this->authorize('audit', Asset::class);
$rules = array(
$rules = [
'asset_tag' => 'required',
'location_id' => 'exists:locations,id|nullable|numeric',
'next_audit_date' => 'date|nullable'
);
'next_audit_date' => 'date|nullable',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
@ -817,7 +772,6 @@ class AssetsController extends Controller
$asset = Asset::where('asset_tag', '=', $request->input('asset_tag'))->first();
if ($asset) {
// We don't want to log this as a normal update, so let's bypass that
$asset->unsetEventDispatcher();
@ -837,24 +791,18 @@ class AssetsController extends Controller
if ($asset->save()) {
$log = $asset->logAudit(request('note'), request('location_id'));
return response()->json(Helper::formatStandardApiResponse('success', [
'asset_tag'=> e($asset->asset_tag),
'note'=> e($request->input('note')),
'next_audit_date' => Helper::getFormattedDateObject($asset->next_audit_date)
'next_audit_date' => Helper::getFormattedDateObject($asset->next_audit_date),
], trans('admin/hardware/message.audit.success')));
}
}
return response()->json(Helper::formatStandardApiResponse('error', ['asset_tag'=> e($request->input('asset_tag'))], 'Asset with tag '.$request->input('asset_tag').' not found'));
}
/**
* Returns JSON listing of all requestable assets
*
@ -866,7 +814,7 @@ class AssetsController extends Controller
{
$this->authorize('viewRequestable', Asset::class);
$assets = Company::scopeCompanyables(Asset::select('assets.*'),"company_id","assets")
$assets = Company::scopeCompanyables(Asset::select('assets.*'), 'company_id', 'assets')
->with('location', 'assetstatus', 'assetlog', 'company', 'defaultLoc','assignedTo',
'model.category', 'model.manufacturer', 'model.fieldset', 'supplier')->where('assets.requestable', '=', '1');
@ -893,9 +841,9 @@ class AssetsController extends Controller
break;
}
$total = $assets->count();
$assets = $assets->skip($offset)->take($limit)->get();
return (new AssetsTransformer)->transformRequestedAssets($assets, $total);
}
}

View file

@ -44,11 +44,10 @@ class CategoriesController extends Controller
$total = $categories->count();
$categories = $categories->skip($offset)->take($limit)->get();
return (new CategoriesTransformer)->transformCategories($categories, $total);
}
/**
* Store a newly created resource in storage.
*
@ -66,8 +65,8 @@ class CategoriesController extends Controller
if ($category->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $category, trans('admin/categories/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $category->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $category->getErrors()));
}
/**
@ -82,11 +81,10 @@ class CategoriesController extends Controller
{
$this->authorize('view', Category::class);
$category = Category::findOrFail($id);
return (new CategoriesTransformer)->transformCategory($category);
}
/**
* Update the specified resource in storage.
*
@ -128,22 +126,19 @@ class CategoriesController extends Controller
);
}
$category->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/categories/message.delete.success')));
}
/**
* Gets a paginated collection for the select2 menus
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request, $category_type = 'asset')
{
$categories = Category::select([
'id',
'name',
@ -164,7 +159,5 @@ class CategoriesController extends Controller
}
return (new SelectlistTransformer)->transformSelectlist($categories);
}
}

View file

@ -55,11 +55,10 @@ class CompaniesController extends Controller
$total = $companies->count();
$companies = $companies->skip($offset)->take($limit)->get();
return (new CompaniesTransformer)->transformCompanies($companies, $total);
}
/**
* Store a newly created resource in storage.
*
@ -77,9 +76,9 @@ class CompaniesController extends Controller
if ($company->save()) {
return response()->json(Helper::formatStandardApiResponse('success', (new CompaniesTransformer)->transformCompany($company), trans('admin/companies/message.create.success')));
}
return response()
->json(Helper::formatStandardApiResponse('error', null, $company->getErrors()));
}
/**
@ -94,11 +93,10 @@ class CompaniesController extends Controller
{
$this->authorize('view', Company::class);
$company = Company::findOrFail($id);
return (new CompaniesTransformer)->transformCompany($company);
}
/**
* Update the specified resource in storage.
*
@ -142,6 +140,7 @@ class CompaniesController extends Controller
->json(Helper::formatStandardApiResponse('error', null, trans('admin/companies/message.assoc_users')));
}
$company->delete();
return response()
->json(Helper::formatStandardApiResponse('success', null, trans('admin/companies/message.delete.success')));
}
@ -152,11 +151,9 @@ class CompaniesController extends Controller
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$companies = Company::select([
'companies.id',
'companies.name',

View file

@ -69,10 +69,10 @@ class ComponentsController extends Controller
$total = $components->count();
$components = $components->skip($offset)->take($limit)->get();
return (new ComponentsTransformer)->transformComponents($components, $total);
}
/**
* Store a newly created resource in storage.
*
@ -90,6 +90,7 @@ class ComponentsController extends Controller
if ($component->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $component, trans('admin/components/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $component->getErrors()));
}
@ -110,7 +111,6 @@ class ComponentsController extends Controller
}
}
/**
* Update the specified resource in storage.
*
@ -147,6 +147,7 @@ class ComponentsController extends Controller
$component = Component::findOrFail($id);
$this->authorize('delete', $component);
$component->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/components/message.delete.success')));
}
@ -170,6 +171,7 @@ class ComponentsController extends Controller
$limit = $request->input('limit', 50);
$total = $assets->count();
$assets = $assets->skip($offset)->take($limit)->get();
return (new ComponentsTransformer)->transformCheckedoutComponents($assets, $total);
}
}

View file

@ -45,7 +45,6 @@ class ConsumablesController extends Controller
$consumables->where('manufacturer_id', '=', $request->input('manufacturer_id'));
}
// Set the offset to the API call's offset, unless the offset is higher than the actual count of items in which
// case we override with the actual count, so we should return 0 items.
$offset = (($consumables) && ($request->get('offset') > $consumables->count())) ? $consumables->count() : $request->get('offset', 0);
@ -57,7 +56,6 @@ class ConsumablesController extends Controller
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array($request->input('sort'), $allowed_columns) ? $request->input('sort') : 'created_at';
switch ($sort) {
case 'category':
$consumables = $consumables->OrderCategory($order);
@ -76,15 +74,12 @@ class ConsumablesController extends Controller
break;
}
$total = $consumables->count();
$consumables = $consumables->skip($offset)->take($limit)->get();
return (new ConsumablesTransformer)->transformConsumables($consumables, $total);
}
/**
* Store a newly created resource in storage.
*
@ -102,6 +97,7 @@ class ConsumablesController extends Controller
if ($consumable->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $consumable, trans('admin/consumables/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $consumable->getErrors()));
}
@ -116,10 +112,10 @@ class ConsumablesController extends Controller
{
$this->authorize('view', Consumable::class);
$consumable = Consumable::findOrFail($id);
return (new ConsumablesTransformer)->transformConsumable($consumable);
}
/**
* Update the specified resource in storage.
*
@ -156,6 +152,7 @@ class ConsumablesController extends Controller
$consumable = Consumable::findOrFail($id);
$this->authorize('delete', $consumable);
$consumable->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.delete.success')));
}
@ -170,21 +167,20 @@ class ConsumablesController extends Controller
*/
public function getDataView($consumableId)
{
$consumable = Consumable::with(array('consumableAssignments'=>
function ($query) {
$consumable = Consumable::with(['consumableAssignments'=> function ($query) {
$query->orderBy($query->getModel()->getTable().'.created_at', 'DESC');
},
'consumableAssignments.admin'=> function ($query) {
},
'consumableAssignments.user'=> function ($query) {
},
))->find($consumableId);
])->find($consumableId);
if (! Company::isCurrentUserHasAccess($consumable)) {
return ['total' => 0, 'rows' => []];
}
$this->authorize('view', Consumable::class);
$rows = array();
$rows = [];
foreach ($consumable->consumableAssignments as $consumable_assignment) {
$rows[] = [
@ -195,7 +191,8 @@ class ConsumablesController extends Controller
}
$consumableCount = $consumable->users->count();
$data = array('total' => $consumableCount, 'rows' => $rows);
$data = ['total' => $consumableCount, 'rows' => $rows];
return $data;
}
@ -231,7 +228,7 @@ class ConsumablesController extends Controller
$consumable->users()->attach($consumable->id, [
'consumable_id' => $consumable->id,
'user_id' => $user->id,
'assigned_to' => $assigned_to
'assigned_to' => $assigned_to,
]);
// Log checkout event
@ -254,14 +251,12 @@ class ConsumablesController extends Controller
* Gets a paginated collection for the select2 menus
*
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$consumables = Consumable::select([
'consumables.id',
'consumables.name'
'consumables.name',
]);
if ($request->filled('search')) {
@ -270,7 +265,6 @@ class ConsumablesController extends Controller
$consumables = $consumables->orderBy('name', 'ASC')->paginate(50);
return (new SelectlistTransformer)->transformSelectlist($consumables);
}
}

View file

@ -18,13 +18,13 @@ class CustomFieldsController extends Controller
* @author [Brady Wetherington] [<uberbrady@gmail.com>]
* @param int $id
* @since [v3.0]
* @return Array
* @return array
*/
public function index()
{
$this->authorize('index', CustomField::class);
$fields = CustomField::get();
return (new CustomFieldsTransformer)->transformCustomFields($fields, $fields->count());
}
@ -80,7 +80,6 @@ class CustomFieldsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, $field->getErrors()));
}
/**
* Store a newly created field.
*
@ -97,8 +96,8 @@ class CustomFieldsController extends Controller
$data = $request->all();
$regex_format = null;
if (str_contains($data["format"], "regex:")){
$regex_format = $data["format"];
if (str_contains($data['format'], 'regex:')) {
$regex_format = $data['format'];
}
$validator = Validator::make($data, $field->validationRules($regex_format));
@ -111,8 +110,8 @@ class CustomFieldsController extends Controller
if ($field->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $field, trans('admin/custom_fields/message.field.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $field->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $field->getErrors()));
}
public function postReorder(Request $request, $id)
@ -121,8 +120,8 @@ class CustomFieldsController extends Controller
$this->authorize('update', $fieldset);
$fields = array();
$order_array = array();
$fields = [];
$order_array = [];
$items = $request->input('item');
@ -135,7 +134,6 @@ class CustomFieldsController extends Controller
}
return $fieldset->fields()->sync($fields);
}
public function associate(Request $request, $field_id)
@ -152,7 +150,8 @@ class CustomFieldsController extends Controller
}
$fieldset = CustomFieldset::findOrFail($fieldset_id);
$fieldset->fields()->attach($field->id, ["required" => ($request->input('required') == "on"), "order" => $request->input('order', $fieldset->fields->count())]);
$fieldset->fields()->attach($field->id, ['required' => ($request->input('required') == 'on'), 'order' => $request->input('order', $fieldset->fields->count())]);
return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.update.success')));
}
@ -166,10 +165,12 @@ class CustomFieldsController extends Controller
foreach ($field->fieldset as $fieldset) {
if ($fieldset->id == $fieldset_id) {
$fieldset->fields()->detach($field->id);
return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.update.success')));
}
}
$fieldset = CustomFieldset::findOrFail($fieldset_id);
return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.update.success')));
}
@ -191,8 +192,7 @@ class CustomFieldsController extends Controller
}
$field->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/custom_fields/message.field.delete.success')));
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Api;
use App\Helpers\Helper;
@ -20,10 +21,8 @@ use View;
* @author [Brady Wetherington] [<uberbrady@gmail.com>]
* @author [Josh Gibson]
*/
class CustomFieldsetsController extends Controller
{
/**
* Shows the given fieldset and its fields
* @author [A. Gianotto] [<snipe@snipe.net>]
@ -36,8 +35,8 @@ class CustomFieldsetsController extends Controller
{
$this->authorize('index', CustomFieldset::class);
$fieldsets = CustomFieldset::withCount('fields as fields_count', 'models as models_count')->get();
return (new CustomFieldsetsTransformer)->transformCustomFieldsets($fieldsets, $fieldsets->count());
return (new CustomFieldsetsTransformer)->transformCustomFieldsets($fieldsets, $fieldsets->count());
}
/**
@ -56,10 +55,8 @@ class CustomFieldsetsController extends Controller
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/custom_fields/message.fieldset.does_not_exist')), 200);
}
/**
* Update the specified resource in storage.
*
@ -82,7 +79,6 @@ class CustomFieldsetsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, $fieldset->getErrors()));
}
/**
* Store a newly created resource in storage.
*
@ -100,11 +96,10 @@ class CustomFieldsetsController extends Controller
if ($fieldset->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $fieldset, trans('admin/custom_fields/message.fieldset.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $fieldset->getErrors()));
}
/**
* Delete a custom fieldset.
*
@ -129,9 +124,6 @@ class CustomFieldsetsController extends Controller
}
return response()->json(Helper::formatStandardApiResponse('error', null, 'Unspecified error'));
}
/**
@ -147,6 +139,7 @@ class CustomFieldsetsController extends Controller
$this->authorize('view', CustomFieldset::class);
$set = CustomFieldset::findOrFail($id);
$fields = $set->fields;
return (new CustomFieldsTransformer)->transformCustomFields($fields, $fields->count());
}

View file

@ -33,7 +33,7 @@ class DepartmentsController extends Controller
'departments.manager_id',
'departments.created_at',
'departments.updated_at',
'departments.image'
'departments.image',
])->with('users')->with('location')->with('manager')->with('company')->withCount('users as users_count');
if ($request->filled('search')) {
@ -64,8 +64,8 @@ class DepartmentsController extends Controller
$total = $departments->count();
$departments = $departments->skip($offset)->take($limit)->get();
return (new DepartmentsTransformer)->transformDepartments($departments, $total);
return (new DepartmentsTransformer)->transformDepartments($departments, $total);
}
/**
@ -87,8 +87,8 @@ class DepartmentsController extends Controller
if ($department->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $department, trans('admin/departments/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $department->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $department->getErrors()));
}
/**
@ -103,6 +103,7 @@ class DepartmentsController extends Controller
{
$this->authorize('view', Department::class);
$department = Department::findOrFail($id);
return (new DepartmentsTransformer)->transformDepartment($department);
}
@ -128,8 +129,6 @@ class DepartmentsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, $department->getErrors()));
}
/**
* Validates and deletes selected department.
*
@ -149,8 +148,8 @@ class DepartmentsController extends Controller
}
$department->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/departments/message.delete.success')));
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/departments/message.delete.success')));
}
/**
@ -159,11 +158,9 @@ class DepartmentsController extends Controller
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$departments = Department::select([
'id',
'name',
@ -184,7 +181,5 @@ class DepartmentsController extends Controller
}
return (new SelectlistTransformer)->transformSelectlist($departments);
}
}

View file

@ -41,10 +41,10 @@ class DepreciationsController extends Controller
$total = $depreciations->count();
$depreciations = $depreciations->skip($offset)->take($limit)->get();
return (new DepreciationsTransformer)->transformDepreciations($depreciations, $total);
}
/**
* Store a newly created resource in storage.
*
@ -62,8 +62,8 @@ class DepreciationsController extends Controller
if ($depreciation->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $depreciation, trans('admin/depreciations/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $depreciation->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $depreciation->getErrors()));
}
/**
@ -78,10 +78,10 @@ class DepreciationsController extends Controller
{
$this->authorize('view', Depreciation::class);
$depreciation = Depreciation::findOrFail($id);
return (new DepreciationsTransformer)->transformDepreciation($depreciation);
}
/**
* Update the specified resource in storage.
*
@ -123,10 +123,7 @@ class DepreciationsController extends Controller
}
$depreciation->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/depreciations/message.delete.success')));
}
}

View file

@ -41,10 +41,10 @@ class GroupsController extends Controller
$total = $groups->count();
$groups = $groups->skip($offset)->take($limit)->get();
return (new GroupsTransformer)->transformGroups($groups, $total);
}
/**
* Store a newly created resource in storage.
*
@ -62,8 +62,8 @@ class GroupsController extends Controller
if ($group->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $group, trans('admin/groups/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $group->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $group->getErrors()));
}
/**
@ -78,10 +78,10 @@ class GroupsController extends Controller
{
$this->authorize('view', Group::class);
$group = Group::findOrFail($id);
return (new GroupsTransformer)->transformGroup($group);
}
/**
* Update the specified resource in storage.
*
@ -118,9 +118,7 @@ class GroupsController extends Controller
$group = Group::findOrFail($id);
$this->authorize('delete', $group);
$group->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/groups/message.delete.success')));
}
}

View file

@ -27,8 +27,8 @@ class ImportController extends Controller
{
$this->authorize('import');
$imports = Import::latest()->get();
return (new ImportsTransformer)->transformImports($imports);
return (new ImportsTransformer)->transformImports($imports);
}
/**
@ -46,21 +46,22 @@ class ImportController extends Controller
$results = [];
$import = new Import;
foreach ($files as $file) {
if (!in_array($file->getMimeType(), array(
if (! in_array($file->getMimeType(), [
'application/vnd.ms-excel',
'text/csv',
'application/csv',
'text/x-Algol68', // because wtf CSV files?
'text/plain',
'text/comma-separated-values',
'text/tsv'))) {
'text/tsv', ])) {
$results['error'] = 'File type must be CSV. Uploaded file is '.$file->getMimeType();
return response()->json(Helper::formatStandardApiResponse('error', null, $results['error']), 500);
}
//TODO: is there a lighter way to do this?
if (! ini_get("auto_detect_line_endings")) {
ini_set("auto_detect_line_endings", '1');
if (! ini_get('auto_detect_line_endings')) {
ini_set('auto_detect_line_endings', '1');
}
$reader = Reader::createFromFileObject($file->openFile('r')); //file pointer leak?
$import->header_row = $reader->fetchOne(0);
@ -76,12 +77,12 @@ class ImportController extends Controller
//avoid reporting duplicates twice, e.g. "1 is same as 17! 17 is same as 1!!!"
//as well as "1 is same as 1!!!" (which is always true)
//has to be > because otherwise the first result of array_search will always be $i itself(!)
array_push($duplicate_headers,"Duplicate header '$header' detected, first at column: ".($found_at+1).", repeats at column: ".($i+1));
array_push($duplicate_headers, "Duplicate header '$header' detected, first at column: ".($found_at + 1).', repeats at column: '.($i + 1));
}
}
}
if (count($duplicate_headers) > 0) {
return response()->json(Helper::formatStandardApiResponse('error',null, implode("; ",$duplicate_headers)), 500); //should this be '4xx'?
return response()->json(Helper::formatStandardApiResponse('error', null, implode('; ', $duplicate_headers)), 500); //should this be '4xx'?
}
// Grab the first row to display via ajax as the user picks fields
@ -96,6 +97,7 @@ class ImportController extends Controller
if (config('app.debug')) {
$results['error'] .= ' '.$exception->getMessage();
}
return response()->json(Helper::formatStandardApiResponse('error', null, $results['error']), 500);
}
$file_name = date('Y-m-d-his').'-'.$fixed_filename;
@ -105,12 +107,15 @@ class ImportController extends Controller
$results[] = $import;
}
$results = (new ImportsTransformer)->transformImports($results);
return [
'files' => $results,
];
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.feature_disabled')), 500);
}
/**
* Processes the specified Import.
*
@ -130,25 +135,25 @@ class ImportController extends Controller
}
$errors = $request->import(Import::find($import_id));
$redirectTo = "hardware.index";
$redirectTo = 'hardware.index';
switch ($request->get('import-type')) {
case "asset":
$redirectTo = "hardware.index";
case 'asset':
$redirectTo = 'hardware.index';
break;
case "accessory":
$redirectTo = "accessories.index";
case 'accessory':
$redirectTo = 'accessories.index';
break;
case "consumable":
$redirectTo = "consumables.index";
case 'consumable':
$redirectTo = 'consumables.index';
break;
case "component":
$redirectTo = "components.index";
case 'component':
$redirectTo = 'components.index';
break;
case "license":
$redirectTo = "licenses.index";
case 'license':
$redirectTo = 'licenses.index';
break;
case "user":
$redirectTo = "users.index";
case 'user':
$redirectTo = 'users.index';
break;
}
@ -157,8 +162,8 @@ class ImportController extends Controller
}
//Flash message before the redirect
Session::flash('success', trans('admin/hardware/message.import.success'));
return response()->json(Helper::formatStandardApiResponse('success', null, ['redirect_url' => route($redirectTo)]));
return response()->json(Helper::formatStandardApiResponse('success', null, ['redirect_url' => route($redirectTo)]));
}
/**
@ -176,14 +181,14 @@ class ImportController extends Controller
// Try to delete the file
Storage::delete('imports/'.$import->file_path);
$import->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.import.file_delete_success')));
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.import.file_delete_success')));
} catch (\Exception $e) {
// If the file delete didn't work, remove it from the database anyway and return a warning
$import->delete();
return response()->json(Helper::formatStandardApiResponse('warning', null, trans('admin/hardware/message.import.file_not_deleted_warning')));
}
}
}
}

View file

@ -72,6 +72,7 @@ class LicenseSeatsController extends Controller
if (! $license = $licenseSeat->license()->first() || $license->id != intval($licenseId)) {
return response()->json(Helper::formatStandardApiResponse('error', null, 'Seat does not belong to the specified license'));
}
return (new LicenseSeatsTransformer)->transformLicenseSeat($licenseSeat);
}
@ -128,11 +129,13 @@ class LicenseSeatsController extends Controller
if ($is_checkin) {
$licenseSeat->logCheckin($target, $request->input('note'));
return response()->json(Helper::formatStandardApiResponse('success', $licenseSeat, trans('admin/licenses/message.update.success')));
}
// in this case, relevant fields are touched but it's not a checkin operation. so it must be a checkout operation.
$licenseSeat->logCheckout($request->input('note'), $target);
return response()->json(Helper::formatStandardApiResponse('success', $licenseSeat, trans('admin/licenses/message.update.success')));
}

View file

@ -28,7 +28,6 @@ class LicensesController extends Controller
$this->authorize('view', License::class);
$licenses = Company::scopeCompanyables(License::with('company', 'manufacturer', 'freeSeats', 'supplier', 'category')->withCount('freeSeats as free_seats_count'));
if ($request->filled('company_id')) {
$licenses->where('company_id', '=', $request->input('company_id'));
}
@ -77,12 +76,10 @@ class LicensesController extends Controller
$licenses->where('supplier_id', '=', $request->input('supplier_id'));
}
if ($request->filled('search')) {
$licenses = $licenses->TextSearch($request->input('search'));
}
// Set the offset to the API call's offset, unless the offset is higher than the actual count of items in which
// case we override with the actual count, so we should return 0 items.
$offset = (($licenses) && ($request->get('offset') > $licenses->count())) ? $licenses->count() : $request->get('offset', 0);
@ -92,7 +89,6 @@ class LicensesController extends Controller
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
switch ($request->input('sort')) {
case 'manufacturer':
$licenses = $licenses->leftJoin('manufacturers', 'licenses.manufacturer_id', '=', 'manufacturers.id')->orderBy('manufacturers.name', $order);
@ -128,25 +124,20 @@ class LicensesController extends Controller
'free_seats_count',
'seats',
'termination_date',
'depreciation_id'
'depreciation_id',
];
$sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'created_at';
$licenses = $licenses->orderBy($sort, $order);
break;
}
$total = $licenses->count();
$licenses = $licenses->skip($offset)->take($limit)->get();
return (new LicensesTransformer)->transformLicenses($licenses, $total);
}
/**
* Store a newly created resource in storage.
*
@ -165,6 +156,7 @@ class LicensesController extends Controller
if ($license->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $license, trans('admin/licenses/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $license->getErrors()));
}
@ -180,10 +172,10 @@ class LicensesController extends Controller
$this->authorize('view', License::class);
$license = License::withCount('freeSeats')->findOrFail($id);
$license = $license->load('assignedusers', 'licenseSeats.user', 'licenseSeats.asset');
return (new LicensesTransformer)->transformLicense($license);
}
/**
* Update the specified resource in storage.
*
@ -226,7 +218,7 @@ class LicensesController extends Controller
// Delete the license and the associated license seats
DB::table('license_seats')
->where('id', $license->id)
->update(array('assigned_to' => null,'asset_id' => null));
->update(['assigned_to' => null, 'asset_id' => null]);
$licenseSeats = $license->licenseseats();
$licenseSeats->delete();
@ -235,6 +227,7 @@ class LicensesController extends Controller
// Redirect to the licenses management page
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/licenses/message.delete.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/licenses/message.assoc_users')));
}
@ -245,10 +238,9 @@ class LicensesController extends Controller
*/
public function selectlist(Request $request)
{
$licenses = License::select([
'licenses.id',
'licenses.name'
'licenses.name',
]);
if ($request->filled('search')) {
@ -257,9 +249,6 @@ class LicensesController extends Controller
$licenses = $licenses->orderBy('name', 'ASC')->paginate(50);
return (new SelectlistTransformer)->transformSelectlist($licenses);
}
}

View file

@ -2,12 +2,12 @@
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Helpers\Helper;
use App\Models\Location;
use App\Http\Controllers\Controller;
use App\Http\Transformers\LocationsTransformer;
use App\Http\Transformers\SelectlistTransformer;
use App\Models\Location;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
@ -26,7 +26,7 @@ class LocationsController extends Controller
$allowed_columns = [
'id', 'name', 'address', 'address2', 'city', 'state', 'country', 'zip', 'created_at',
'updated_at', 'manager_id', 'image',
'assigned_assets_count','users_count','assets_count','currency','ldap_ou'];
'assigned_assets_count', 'users_count', 'assets_count', 'currency', 'ldap_ou', ];
$locations = Location::with('parent', 'manager', 'children')->select([
'locations.id',
@ -43,7 +43,7 @@ class LocationsController extends Controller
'locations.updated_at',
'locations.image',
'locations.ldap_ou',
'locations.currency'
'locations.currency',
])->withCount('assignedAssets as assigned_assets_count')
->withCount('assets as assets_count')
->withCount('users as users_count');
@ -52,8 +52,6 @@ class LocationsController extends Controller
$locations = $locations->TextSearch($request->input('search'));
}
$offset = (($locations) && (request('offset') > $locations->count())) ? $locations->count() : request('offset', 0);
// Check to make sure the limit is not higher than the max allowed
@ -74,13 +72,12 @@ class LocationsController extends Controller
break;
}
$total = $locations->count();
$locations = $locations->skip($offset)->take($limit)->get();
return (new LocationsTransformer)->transformLocations($locations, $total);
}
/**
* Store a newly created resource in storage.
*
@ -98,6 +95,7 @@ class LocationsController extends Controller
if ($location->save()) {
return response()->json(Helper::formatStandardApiResponse('success', (new LocationsTransformer)->transformLocation($location), trans('admin/locations/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $location->getErrors()));
}
@ -127,15 +125,15 @@ class LocationsController extends Controller
'locations.created_at',
'locations.updated_at',
'locations.image',
'locations.currency'
'locations.currency',
])
->withCount('assignedAssets as assigned_assets_count')
->withCount('assets as assets_count')
->withCount('users as users_count')->findOrFail($id);
return (new LocationsTransformer)->transformLocation($location);
}
/**
* Update the specified resource in storage.
*
@ -152,10 +150,9 @@ class LocationsController extends Controller
$location->fill($request->all());
if ($location->isValid()) {
$location->save();
return response()->json(
Helper::formatStandardApiResponse(
'success',
@ -186,6 +183,7 @@ class LocationsController extends Controller
}
$this->authorize('delete', $location);
$location->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/locations/message.delete.success')));
}
@ -216,11 +214,9 @@ class LocationsController extends Controller
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$locations = Location::select([
'locations.id',
'locations.name',
@ -253,15 +249,11 @@ class LocationsController extends Controller
} else {
$location_options = Location::indenter($locations_with_children);
$locations_formatted = new Collection($location_options);
}
$paginated_results = new LengthAwarePaginator($locations_formatted->forPage($page, 500), $locations_formatted->count(), 500, $page, []);
//return [];
return (new SelectlistTransformer)->transformSelectlist($paginated_results);
}
}

View file

@ -25,7 +25,7 @@ class ManufacturersController extends Controller
$allowed_columns = ['id', 'name', 'url', 'support_url', 'support_email', 'support_phone', 'created_at', 'updated_at', 'image', 'assets_count', 'consumables_count', 'components_count', 'licenses_count'];
$manufacturers = Manufacturer::select(
array('id','name','url','support_url','support_email','support_phone','created_at','updated_at','image', 'deleted_at')
['id', 'name', 'url', 'support_url', 'support_email', 'support_phone', 'created_at', 'updated_at', 'image', 'deleted_at']
)->withCount('assets as assets_count')->withCount('licenses as licenses_count')->withCount('consumables as consumables_count')->withCount('accessories as accessories_count');
if ($request->input('deleted') == 'true') {
@ -36,7 +36,6 @@ class ManufacturersController extends Controller
$manufacturers = $manufacturers->TextSearch($request->input('search'));
}
// Set the offset to the API call's offset, unless the offset is higher than the actual count of items in which
// case we override with the actual count, so we should return 0 items.
$offset = (($manufacturers) && ($request->get('offset') > $manufacturers->count())) ? $manufacturers->count() : $request->get('offset', 0);
@ -50,10 +49,10 @@ class ManufacturersController extends Controller
$total = $manufacturers->count();
$manufacturers = $manufacturers->skip($offset)->take($limit)->get();
return (new ManufacturersTransformer)->transformManufacturers($manufacturers, $total);
}
/**
* Store a newly created resource in storage.
*
@ -71,8 +70,8 @@ class ManufacturersController extends Controller
if ($manufacturer->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $manufacturer, trans('admin/manufacturers/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $manufacturer->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $manufacturer->getErrors()));
}
/**
@ -87,10 +86,10 @@ class ManufacturersController extends Controller
{
$this->authorize('view', Manufacturer::class);
$manufacturer = Manufacturer::withCount('assets as assets_count')->withCount('licenses as licenses_count')->withCount('consumables as consumables_count')->withCount('accessories as accessories_count')->findOrFail($id);
return (new ManufacturersTransformer)->transformManufacturer($manufacturer);
}
/**
* Update the specified resource in storage.
*
@ -123,22 +122,17 @@ class ManufacturersController extends Controller
*/
public function destroy($id)
{
$this->authorize('delete', Manufacturer::class);
$manufacturer = Manufacturer::findOrFail($id);
$this->authorize('delete', $manufacturer);
if ($manufacturer->isDeletable()) {
$manufacturer->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/manufacturers/message.delete.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/manufacturers/message.assoc_users')));
}
/**
@ -147,11 +141,9 @@ class ManufacturersController extends Controller
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$manufacturers = Manufacturer::select([
'id',
'name',
@ -173,6 +165,5 @@ class ManufacturersController extends Controller
}
return (new SelectlistTransformer)->transformSelectlist($manufacturers);
}
}

View file

@ -37,11 +37,10 @@ class PredefinedKitsController extends Controller
$total = $kits->count();
$kits = $kits->skip($offset)->take($limit)->get();
return (new PredefinedKitsTransformer)->transformPredefinedKits($kits, $total);
}
/**
* Store a newly created resource in storage.
*
@ -57,8 +56,8 @@ class PredefinedKitsController extends Controller
if ($kit->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.create_success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $kit->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $kit->getErrors()));
}
/**
@ -71,10 +70,10 @@ class PredefinedKitsController extends Controller
{
$this->authorize('view', PredefinedKit::class);
$kit = PredefinedKit::findOrFail($id);
return (new PredefinedKitsTransformer)->transformPredefinedKit($kit);
}
/**
* Update the specified resource in storage.
*
@ -113,23 +112,20 @@ class PredefinedKitsController extends Controller
$kit->accessories()->detach();
$kit->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/kits/general.delete_success'))); // TODO: trans
}
/**
* Gets a paginated collection for the select2 menus
*
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$kits = PredefinedKit::select([
'id',
'name'
'name',
]);
if ($request->filled('search')) {
@ -139,7 +135,6 @@ class PredefinedKitsController extends Controller
$kits = $kits->orderBy('name', 'ASC')->paginate(50);
return (new SelectlistTransformer)->transformSelectlist($kits);
}
/**
@ -148,14 +143,15 @@ class PredefinedKitsController extends Controller
* @param int $id
* @return \Illuminate\Http\Response
*/
public function indexLicenses($kit_id) {
public function indexLicenses($kit_id)
{
$this->authorize('view', PredefinedKit::class);
$kit = PredefinedKit::findOrFail($kit_id);
$licenses = $kit->licenses;
return (new PredefinedKitsTransformer)->transformElements($licenses, $licenses->count());
}
/**
* Store the specified resource.
*
@ -179,6 +175,7 @@ class PredefinedKitsController extends Controller
}
$relation->attach($license_id, ['quantity' => $quantity]);
return response()->json(Helper::formatStandardApiResponse('success', $kit, 'License added successfull')); // TODO: trans
}
@ -214,6 +211,7 @@ class PredefinedKitsController extends Controller
$kit = PredefinedKit::findOrFail($kit_id);
$kit->licenses()->detach($license_id);
return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.delete_success')));
}
@ -223,10 +221,12 @@ class PredefinedKitsController extends Controller
* @param int $kit_id
* @return \Illuminate\Http\Response
*/
public function indexModels($kit_id) {
public function indexModels($kit_id)
{
$this->authorize('view', PredefinedKit::class);
$kit = PredefinedKit::findOrFail($kit_id);
$models = $kit->models;
return (new PredefinedKitsTransformer)->transformElements($models, $models->count());
}
@ -238,8 +238,6 @@ class PredefinedKitsController extends Controller
*/
public function storeModel(Request $request, $kit_id)
{
$this->authorize('update', PredefinedKit::class);
$kit = PredefinedKit::findOrFail($kit_id);
@ -291,25 +289,25 @@ class PredefinedKitsController extends Controller
$kit = PredefinedKit::findOrFail($kit_id);
$kit->models()->detach($model_id);
return response()->json(Helper::formatStandardApiResponse('success', $kit, trans('admin/kits/general.model_removed_success')));
}
/**
* Display the specified resource.
*
* @param int $kit_id
* @return \Illuminate\Http\Response
*/
public function indexConsumables($kit_id) {
public function indexConsumables($kit_id)
{
$this->authorize('view', PredefinedKit::class);
$kit = PredefinedKit::findOrFail($kit_id);
$consumables = $kit->consumables;
return (new PredefinedKitsTransformer)->transformElements($consumables, $consumables->count());
}
/**
* Store the specified resource.
*
@ -333,6 +331,7 @@ class PredefinedKitsController extends Controller
}
$relation->attach($consumable_id, ['quantity' => $quantity]);
return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Consumable added successfull')); // TODO: trans
}
@ -368,24 +367,25 @@ class PredefinedKitsController extends Controller
$kit = PredefinedKit::findOrFail($kit_id);
$kit->consumables()->detach($consumable_id);
return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Delete was successfull')); // TODO: trans
}
/**
* Display the specified resource.
*
* @param int $kit_id
* @return \Illuminate\Http\Response
*/
public function indexAccessories($kit_id) {
public function indexAccessories($kit_id)
{
$this->authorize('view', PredefinedKit::class);
$kit = PredefinedKit::findOrFail($kit_id);
$accessories = $kit->accessories;
return (new PredefinedKitsTransformer)->transformElements($accessories, $accessories->count());
}
/**
* Store the specified resource.
*
@ -409,6 +409,7 @@ class PredefinedKitsController extends Controller
}
$relation->attach($accessory_id, ['quantity' => $quantity]);
return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Accessory added successfull')); // TODO: trans
}
@ -444,6 +445,7 @@ class PredefinedKitsController extends Controller
$kit = PredefinedKit::findOrFail($kit_id);
$kit->accessories()->detach($accessory_id);
return response()->json(Helper::formatStandardApiResponse('success', $kit, 'Delete was successfull')); // TODO: trans
}
}

View file

@ -15,7 +15,7 @@ class ProfileController extends Controller
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.3.0]
*
* @return Array
* @return array
*/
public function requestedAssets()
{
@ -24,7 +24,6 @@ class ProfileController extends Controller
$results = [];
$results['total'] = $checkoutRequests->count();
foreach ($checkoutRequests as $checkoutRequest) {
// Make sure the asset and request still exist
@ -39,10 +38,8 @@ class ProfileController extends Controller
'request_date' => Helper::getFormattedDateObject($checkoutRequest->created_at, 'datetime'),
];
}
}
return $results;
}
}

View file

@ -28,12 +28,12 @@ class ReportsController extends Controller
if (($request->filled('target_type')) && ($request->filled('target_id'))) {
$actionlogs = $actionlogs->where('target_id', '=', $request->input('target_id'))
->where('target_type','=',"App\\Models\\".ucwords($request->input('target_type')));
->where('target_type', '=', 'App\\Models\\'.ucwords($request->input('target_type')));
}
if (($request->filled('item_type')) && ($request->filled('item_id'))) {
$actionlogs = $actionlogs->where('item_id', '=', $request->input('item_id'))
->where('item_type','=',"App\\Models\\".ucwords($request->input('item_type')));
->where('item_type', '=', 'App\\Models\\'.ucwords($request->input('item_type')));
}
if ($request->filled('action_type')) {
@ -51,7 +51,7 @@ class ReportsController extends Controller
'user_id',
'accept_signature',
'action_type',
'note'
'note',
];
$sort = in_array($request->input('sort'), $allowed_columns) ? e($request->input('sort')) : 'created_at';
@ -62,6 +62,5 @@ class ReportsController extends Controller
$actionlogs = $actionlogs->orderBy($sort, $order)->skip($offset)->take($limit)->get();
return response()->json((new ActionlogsTransformer)->transformActionlogs($actionlogs, $total), 200, ['Content-Type' => 'application/json;charset=utf8'], JSON_UNESCAPED_UNICODE);
}
}

View file

@ -4,24 +4,22 @@ namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Transformers\LoginAttemptsTransformer;
use App\Models\Ldap;
use App\Models\Setting;
use App\Notifications\MailTest;
use App\Services\LdapAd;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Models\Ldap; // forward-port of v4 LDAP model for Sync
use Illuminate\Support\Facades\Validator; // forward-port of v4 LDAP model for Sync
class SettingsController extends Controller
{
/**
* Test the ldap settings
*
@ -37,13 +35,13 @@ class SettingsController extends Controller
{
if (! $ldap->init()) {
Log::info('LDAP is not enabled so we cannot test.');
return response()->json(['message' => 'LDAP is not enabled, cannot test.'], 400);
}
// The connect, bind and resulting users message
$message = [];
// This is all kinda fucked right now. The connection test doesn't actually do what you think,
// // and the way we parse the errors
// on the JS side is horrible.
@ -52,12 +50,13 @@ class SettingsController extends Controller
try {
$ldap->testLdapAdUserConnection();
$message['login'] = [
'message' => 'Successfully connected to LDAP server.'
'message' => 'Successfully connected to LDAP server.',
];
} catch (\Exception $ex) {
\Log::debug('Connection to LDAP server '.Setting::getSettings()->ldap_server.' failed. Please check your LDAP settings and try again. Server Responded with error: '.$ex->getMessage());
return response()->json(
['message' => 'Connection to LDAP server '.Setting::getSettings()->ldap_server." failed. Verify that the LDAP hostname is entered correctly and that it can be reached from this web server. \n\nServer Responded with error: " . $ex->getMessage()
['message' => 'Connection to LDAP server '.Setting::getSettings()->ldap_server." failed. Verify that the LDAP hostname is entered correctly and that it can be reached from this web server. \n\nServer Responded with error: ".$ex->getMessage(),
], 400);
}
@ -68,15 +67,15 @@ class SettingsController extends Controller
Log::info('Testing Bind');
$ldap->testLdapAdBindConnection();
$message['bind'] = [
'message' => 'Successfully bound to LDAP server.'
'message' => 'Successfully bound to LDAP server.',
];
} catch (\Exception $ex) {
Log::info('LDAP Bind failed');
return response()->json(['message' => 'Connection to LDAP successful, but we were unable to Bind the LDAP user '.Setting::getSettings()->ldap_uname.". Verify your that your LDAP Bind username and password are correct. \n\nServer Responded with error: " . $ex->getMessage()
return response()->json(['message' => 'Connection to LDAP successful, but we were unable to Bind the LDAP user '.Setting::getSettings()->ldap_uname.". Verify your that your LDAP Bind username and password are correct. \n\nServer Responded with error: ".$ex->getMessage(),
], 400);
}
Log::info('Preparing to get sample user set from LDAP directory');
// Get a sample of 10 users so user can verify the data is correct
$settings = Setting::getSettings();
@ -97,20 +96,21 @@ class SettingsController extends Controller
});
if ($users->count() > 0) {
$message['user_sync'] = [
'users' => $users
'users' => $users,
];
} else {
$message['user_sync'] = [
'message' => 'Connection to LDAP was successful, however there were no users returned from your query. You should confirm the Base Bind DN above.'
'message' => 'Connection to LDAP was successful, however there were no users returned from your query. You should confirm the Base Bind DN above.',
];
return response()->json($message, 400);
}
} catch (\Exception $ex) {
Log::info('LDAP sync failed');
$message['user_sync'] = [
'message' => 'Error getting users from LDAP directory, error: ' . $ex->getMessage()
'message' => 'Error getting users from LDAP directory, error: '.$ex->getMessage(),
];
return response()->json($message, 400);
}
@ -119,26 +119,25 @@ class SettingsController extends Controller
public function ldaptestlogin(Request $request, LdapAd $ldap)
{
if (Setting::getSettings()->ldap_enabled != '1') {
\Log::debug('LDAP is not enabled. Cannot test.');
return response()->json(['message' => 'LDAP is not enabled, cannot test.'], 400);
}
$rules = array(
$rules = [
'ldaptest_user' => 'required',
'ldaptest_password' => 'required'
);
'ldaptest_password' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
\Log::debug('LDAP Validation test failed.');
$validation_errors = implode(' ', $validator->errors()->all());
return response()->json(['message' => $validator->errors()->all()], 400);
}
\Log::debug('Preparing to test LDAP login');
try {
DB::beginTransaction(); //this was the easiest way to invoke a full test of an LDAP login without adding new users to the DB (which may not be desired)
@ -154,45 +153,41 @@ class SettingsController extends Controller
}
} catch (\Exception $e) {
\Log::debug('Connection failed');
return response()->json(['message' => $e->getMessage()], 400);
} finally {
DB::rollBack(); // ALWAYS rollback, whether success or failure
}
}
public function slacktest(Request $request)
{
$slack = new Client([
'base_url' => e($request->input('slack_endpoint')),
'defaults' => [
'exceptions' => false
]
'exceptions' => false,
],
]);
$payload = json_encode(
[
'channel' => e($request->input('slack_channel')),
'text' => trans('general.slack_test_msg'),
'username' => e($request->input('slack_botname')),
'icon_emoji' => ':heart:'
'icon_emoji' => ':heart:',
]);
try {
$slack->post($request->input('slack_endpoint'), ['body' => $payload]);
return response()->json(['message' => 'Success'], 200);
} catch (\Exception $e) {
return response()->json(['message' => 'Oops! Please check the channel name and webhook endpoint URL. Slack responded with: '.$e->getMessage()], 400);
}
return response()->json(['message' => 'Something went wrong :( '], 400);
}
/**
* Test the email configuration
*
@ -205,16 +200,16 @@ class SettingsController extends Controller
if (! config('app.lock_passwords')) {
try {
Notification::send(Setting::first(), new MailTest());
return response()->json(['message' => 'Mail sent to '.config('mail.reply_to.address')], 200);
} catch (\Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
}
return response()->json(['message' => 'Mail would have been sent, but this application is in demo mode! '], 200);
}
/**
* Delete server-cached barcodes
*
@ -224,22 +219,19 @@ class SettingsController extends Controller
*/
public function purgeBarcodes()
{
$file_count = 0;
$files = Storage::disk('public')->files('barcodes');
foreach ($files as $file) { // iterate files
$file_parts = explode(".", $file);
$file_parts = explode('.', $file);
$extension = end($file_parts);
\Log::debug($extension);
// Only generated barcodes would have a .png file extension
if ($extension == 'png') {
\Log::debug('Deleting: '.$file);
try {
Storage::disk('public')->delete($file);
\Log::debug('Deleting: '.$file);
@ -248,17 +240,11 @@ class SettingsController extends Controller
\Log::debug($e);
}
}
}
return response()->json(['message' => 'Deleted '.$file_count.' barcodes'], 200);
}
/**
* Get a list of login attempts
*
@ -280,9 +266,5 @@ class SettingsController extends Controller
$login_attempt_results = $login_attempts->skip(request('offset', 0))->take(request('limit', 20))->get();
return (new LoginAttemptsTransformer)->transformLoginAttempts($login_attempt_results, $total);
}
}

View file

@ -43,10 +43,10 @@ class StatuslabelsController extends Controller
$total = $statuslabels->count();
$statuslabels = $statuslabels->skip($offset)->take($limit)->get();
return (new StatuslabelsTransformer)->transformStatuslabels($statuslabels, $total);
}
/**
* Store a newly created resource in storage.
*
@ -61,7 +61,7 @@ class StatuslabelsController extends Controller
$request->except('deployable', 'pending', 'archived');
if (! $request->filled('type')) {
return response()->json(Helper::formatStandardApiResponse('error', null, ["type" => ["Status label type is required."]]),500);
return response()->json(Helper::formatStandardApiResponse('error', null, ['type' => ['Status label type is required.']]), 500);
}
$statuslabel = new Statuslabel;
@ -75,8 +75,8 @@ class StatuslabelsController extends Controller
if ($statuslabel->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $statuslabel, trans('admin/statuslabels/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $statuslabel->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $statuslabel->getErrors()));
}
/**
@ -91,10 +91,10 @@ class StatuslabelsController extends Controller
{
$this->authorize('view', Statuslabel::class);
$statuslabel = Statuslabel::findOrFail($id);
return (new StatuslabelsTransformer)->transformStatuslabel($statuslabel);
}
/**
* Update the specified resource in storage.
*
@ -146,15 +146,13 @@ class StatuslabelsController extends Controller
// Check that there are no assets associated
if ($statuslabel->assets()->count() == 0) {
$statuslabel->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/statuslabels/message.delete.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/statuslabels/message.assoc_assets')));
}
/**
* Show a count of assets by status label for pie chart
*
@ -162,7 +160,6 @@ class StatuslabelsController extends Controller
* @since [v3.0]
* @return \Illuminate\Http\Response
*/
public function getAssetCountByStatuslabel()
{
$this->authorize('view', Statuslabel::class);
@ -175,11 +172,10 @@ class StatuslabelsController extends Controller
$labels = [];
$points = [];
$default_color_count = 0;
$colors_array = array();
$colors_array = [];
foreach ($statuslabels as $statuslabel) {
if ($statuslabel->assets_count > 0) {
$labels[] = $statuslabel->name.' ('.number_format($statuslabel->assets_count).')';
$points[] = $statuslabel->assets_count;
@ -193,13 +189,14 @@ class StatuslabelsController extends Controller
}
$result = [
"labels" => $labels,
"datasets" => [ [
"data" => $points,
"backgroundColor" => $colors_array,
"hoverBackgroundColor" => $colors_array
]]
'labels' => $labels,
'datasets' => [[
'data' => $points,
'backgroundColor' => $colors_array,
'hoverBackgroundColor' => $colors_array,
]],
];
return $result;
}
@ -231,11 +228,9 @@ class StatuslabelsController extends Controller
$total = $assets->count();
$assets = $assets->skip($offset)->take($limit)->get();
return (new AssetsTransformer)->transformAssets($assets, $total);
}
/**
* Returns a boolean response based on whether the status label
* is one that is deployable.
@ -245,9 +240,10 @@ class StatuslabelsController extends Controller
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0]
* @return Bool
* @return bool
*/
public function checkIfDeployable($id) {
public function checkIfDeployable($id)
{
$statuslabel = Statuslabel::findOrFail($id);
if ($statuslabel->getStatuslabelType() == 'deployable') {
return '1';

View file

@ -25,10 +25,9 @@ class SuppliersController extends Controller
$allowed_columns = ['id', 'name', 'address', 'phone', 'contact', 'fax', 'email', 'image', 'assets_count', 'licenses_count', 'accessories_count', 'url'];
$suppliers = Supplier::select(
array('id','name','address','address2','city','state','country','fax', 'phone','email','contact','created_at','updated_at','deleted_at','image','notes')
['id', 'name', 'address', 'address2', 'city', 'state', 'country', 'fax', 'phone', 'email', 'contact', 'created_at', 'updated_at', 'deleted_at', 'image', 'notes']
)->withCount('assets as assets_count')->withCount('licenses as licenses_count')->withCount('accessories as accessories_count');
if ($request->filled('search')) {
$suppliers = $suppliers->TextSearch($request->input('search'));
}
@ -46,10 +45,10 @@ class SuppliersController extends Controller
$total = $suppliers->count();
$suppliers = $suppliers->skip($offset)->take($limit)->get();
return (new SuppliersTransformer)->transformSuppliers($suppliers, $total);
}
/**
* Store a newly created resource in storage.
*
@ -67,8 +66,8 @@ class SuppliersController extends Controller
if ($supplier->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $supplier, trans('admin/suppliers/message.create.success')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $supplier->getErrors()));
return response()->json(Helper::formatStandardApiResponse('error', null, $supplier->getErrors()));
}
/**
@ -83,10 +82,10 @@ class SuppliersController extends Controller
{
$this->authorize('view', Supplier::class);
$supplier = Supplier::findOrFail($id);
return (new SuppliersTransformer)->transformSupplier($supplier);
}
/**
* Update the specified resource in storage.
*
@ -123,7 +122,6 @@ class SuppliersController extends Controller
$supplier = Supplier::with('asset_maintenances', 'assets', 'licenses')->withCount('asset_maintenances as asset_maintenances_count', 'assets as assets_count', 'licenses as licenses_count')->findOrFail($id);
$this->authorize('delete', $supplier);
if ($supplier->assets_count > 0) {
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/suppliers/message.delete.assoc_assets', ['asset_count' => (int) $supplier->assets_count])));
}
@ -137,8 +135,8 @@ class SuppliersController extends Controller
}
$supplier->delete();
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/suppliers/message.delete.success')));
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/suppliers/message.delete.success')));
}
/**
@ -147,11 +145,9 @@ class SuppliersController extends Controller
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$suppliers = Supplier::select([
'id',
'name',
@ -173,7 +169,5 @@ class SuppliersController extends Controller
}
return (new SelectlistTransformer)->transformSelectlist($suppliers);
}
}

View file

@ -67,7 +67,6 @@ class UsersController extends Controller
->withCount('assets as assets_count', 'licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count');
$users = Company::scopeCompanyables($users);
if (($request->filled('deleted')) && ($request->input('deleted') == 'true')) {
$users = $users->onlyTrashed();
} elseif (($request->filled('all')) && ($request->input('all') == 'true')) {
@ -112,7 +111,6 @@ class UsersController extends Controller
// Check to make sure the limit is not higher than the max allowed
((config('app.max_results') >= $request->input('limit')) && ($request->filled('limit'))) ? $limit = $request->input('limit') : $limit = config('app.max_results');
switch ($request->input('sort')) {
case 'manager':
$users = $users->OrderManager($order);
@ -133,7 +131,7 @@ class UsersController extends Controller
'assets', 'accessories', 'consumables', 'licenses', 'groups', 'activated', 'created_at',
'two_factor_enrolled', 'two_factor_optin', 'last_login', 'assets_count', 'licenses_count',
'consumables_count', 'accessories_count', 'phone', 'address', 'city', 'state',
'country', 'zip', 'id', 'ldap_import'
'country', 'zip', 'id', 'ldap_import',
];
$sort = in_array($request->get('sort'), $allowed_columns) ? $request->get('sort') : 'first_name';
@ -141,24 +139,21 @@ class UsersController extends Controller
break;
}
$total = $users->count();
$users = $users->skip($offset)->take($limit)->get();
return (new UsersTransformer)->transformUsers($users, $total);
}
/**
* Gets a paginated collection for the select2 menus
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v4.0.16]
* @see \App\Http\Transformers\SelectlistTransformer
*
*/
public function selectlist(Request $request)
{
$users = User::select(
[
'users.id',
@ -203,11 +198,8 @@ class UsersController extends Controller
}
return (new SelectlistTransformer)->transformSelectlist($users);
}
/**
* Store a newly created resource in storage.
*
@ -224,7 +216,6 @@ class UsersController extends Controller
$user->fill($request->all());
if ($request->has('permissions')) {
$permissions_array = $request->input('permissions');
// Strip out the superuser permission if the API user isn't a superadmin
@ -234,19 +225,19 @@ class UsersController extends Controller
$user->permissions = $permissions_array;
}
$tmp_pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
$tmp_pass = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20);
$user->password = bcrypt($request->get('password', $tmp_pass));
if ($user->save()) {
if ($request->filled('groups')) {
$user->groups()->sync($request->input('groups'));
} else {
$user->groups()->sync(array());
$user->groups()->sync([]);
}
return response()->json(Helper::formatStandardApiResponse('success', (new UsersTransformer)->transformUser($user), trans('admin/users/message.success.create')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, $user->getErrors()));
}
@ -261,10 +252,10 @@ class UsersController extends Controller
{
$this->authorize('view', User::class);
$user = User::withCount('assets as assets_count', 'licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count')->findOrFail($id);
return (new UsersTransformer)->transformUser($user);
}
/**
* Update the specified resource in storage.
*
@ -288,7 +279,6 @@ class UsersController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, 'Permission denied. You cannot update user information via API on the demo.'));
}
$user->fill($request->all());
if ($user->id == $request->input('manager_id')) {
@ -303,7 +293,6 @@ class UsersController extends Controller
// here because we need to overwrite permissions
// if someone needs to null them out
if ($request->has('permissions')) {
$permissions_array = $request->input('permissions');
// Strip out the superuser permission if the API user isn't a superadmin
@ -313,9 +302,6 @@ class UsersController extends Controller
$user->permissions = $permissions_array;
}
// Update the location of any assets checked out to this user
Asset::where('assigned_type', User::class)
->where('assigned_to', $user->id)->update(['location_id' => $request->input('location_id', null)]);
@ -333,10 +319,9 @@ class UsersController extends Controller
$user->groups()->sync($request->input('groups'));
// The groups field has been passed but it is null, so we should blank it out
} elseif ($request->has('groups')) {
$user->groups()->sync(array());
$user->groups()->sync([]);
}
return response()->json(Helper::formatStandardApiResponse('success', (new UsersTransformer)->transformUser($user), trans('admin/users/message.success.update')));
}
@ -357,7 +342,6 @@ class UsersController extends Controller
$user = User::findOrFail($id);
$this->authorize('delete', $user);
if (($user->assets) && ($user->assets->count() > 0)) {
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/users/message.error.delete_has_assets')));
}
@ -384,8 +368,10 @@ class UsersController extends Controller
\Log::debug($e);
}
}
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/users/message.success.delete')));
}
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/users/message.error.delete')));
}
@ -402,6 +388,7 @@ class UsersController extends Controller
$this->authorize('view', User::class);
$this->authorize('view', Asset::class);
$assets = Asset::where('assigned_to', '=', $id)->where('assigned_type', '=', User::class)->with('model')->get();
return (new AssetsTransformer)->transformAssets($assets, $assets->count());
}
@ -419,6 +406,7 @@ class UsersController extends Controller
$user = User::findOrFail($id);
$this->authorize('view', Accessory::class);
$accessories = $user->accessories;
return (new AccessoriesTransformer)->transformAccessories($accessories, $accessories->count());
}
@ -436,12 +424,11 @@ class UsersController extends Controller
$this->authorize('view', License::class);
$user = User::where('id', $id)->withTrashed()->first();
$licenses = $user->licenses()->get();
return (new LicensesTransformer())->transformLicenses($licenses, $licenses->count());
}
/**
* Reset the user's two-factor status
*
* @author [A. Gianotto] [<snipe@snipe.net>]
@ -451,7 +438,6 @@ class UsersController extends Controller
*/
public function postTwoFactorReset(Request $request)
{
$this->authorize('update', User::class);
if ($request->filled('id')) {
@ -460,13 +446,14 @@ class UsersController extends Controller
$user->two_factor_secret = null;
$user->two_factor_enrolled = 0;
$user->save();
return response()->json(['message' => trans('admin/settings/general.two_factor_reset_success')], 200);
} catch (\Exception $e) {
return response()->json(['message' => trans('admin/settings/general.two_factor_reset_error')], 500);
}
}
return response()->json(['message' => 'No ID provided'], 500);
return response()->json(['message' => 'No ID provided'], 500);
}
/**

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Helpers\Helper;
@ -21,7 +22,6 @@ use View;
*/
class AssetMaintenancesController extends Controller
{
/**
* Checks for permissions for this action.
*
@ -53,8 +53,6 @@ class AssetMaintenancesController extends Controller
return view('asset_maintenances/index');
}
/**
* Returns a form view to create a new asset maintenance.
*
@ -117,8 +115,8 @@ class AssetMaintenancesController extends Controller
$assetMaintenance->user_id = Auth::id();
if (($assetMaintenance->completion_date !== null)
&& ( $assetMaintenance->start_date !== "" )
&& ( $assetMaintenance->start_date !== "0000-00-00" )
&& ($assetMaintenance->start_date !== '')
&& ($assetMaintenance->start_date !== '0000-00-00')
) {
$startDate = Carbon::parse($assetMaintenance->start_date);
$completionDate = Carbon::parse($assetMaintenance->completion_date);
@ -133,7 +131,6 @@ class AssetMaintenancesController extends Controller
}
return redirect()->back()->withInput()->withErrors($assetMaintenance->getErrors());
}
/**
@ -156,7 +153,6 @@ class AssetMaintenancesController extends Controller
} elseif (! $assetMaintenance->asset) {
return redirect()->route('maintenances.index')
->with('error', 'The asset associated with this maintenance does not exist.');
} elseif (! Company::isCurrentUserHasAccess($assetMaintenance->asset)) {
return static::getInsufficientPermissionsRedirect();
}
@ -184,7 +180,6 @@ class AssetMaintenancesController extends Controller
->with('selectedAsset', null)
->with('assetMaintenanceType', $assetMaintenanceType)
->with('item', $assetMaintenance);
}
/**
@ -237,8 +232,8 @@ class AssetMaintenancesController extends Controller
}
if (($assetMaintenance->completion_date !== null)
&& ( $assetMaintenance->start_date !== "" )
&& ( $assetMaintenance->start_date !== "0000-00-00" )
&& ($assetMaintenance->start_date !== '')
&& ($assetMaintenance->start_date !== '0000-00-00')
) {
$startDate = Carbon::parse($assetMaintenance->start_date);
$completionDate = Carbon::parse($assetMaintenance->completion_date);
@ -252,6 +247,7 @@ class AssetMaintenancesController extends Controller
return redirect()->route('maintenances.index')
->with('success', trans('admin/asset_maintenances/message.edit.success'));
}
return redirect()->back()->withInput()->withErrors($assetMaintenance->getErrors());
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Helpers\Helper;
@ -10,7 +11,6 @@ use Illuminate\Support\Facades\View;
use Redirect;
use Request;
use Storage;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
@ -34,6 +34,7 @@ class AssetModelsController extends Controller
public function index()
{
$this->authorize('index', AssetModel::class);
return view('models/index');
}
@ -48,12 +49,12 @@ class AssetModelsController extends Controller
public function create()
{
$this->authorize('create', AssetModel::class);
return view('models/edit')->with('category_type', 'asset')
->with('depreciation_list', Helper::depreciationList())
->with('item', new AssetModel);
}
/**
* Validate and process the new Asset Model data.
*
@ -65,7 +66,6 @@ class AssetModelsController extends Controller
*/
public function store(ImageUploadRequest $request)
{
$this->authorize('create', AssetModel::class);
// Create a new asset model
$model = new AssetModel;
@ -94,8 +94,9 @@ class AssetModelsController extends Controller
}
// Redirect to the new model page
return redirect()->route("models.index")->with('success', trans('admin/models/message.create.success'));
return redirect()->route('models.index')->with('success', trans('admin/models/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($model->getErrors());
}
@ -115,14 +116,13 @@ class AssetModelsController extends Controller
$category_type = 'asset';
$view = View::make('models/edit', compact('item', 'category_type'));
$view->with('depreciation_list', Helper::depreciationList());
return $view;
}
return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));
}
/**
* Validates and processes form data from the edit
* Asset Model form based on the model ID passed.
@ -154,8 +154,6 @@ class AssetModelsController extends Controller
$model->notes = $request->input('notes');
$model->requestable = $request->input('requestable', '0');
$this->removeCustomFieldsDefaultValues($model);
if ($request->input('custom_fieldset') == '') {
@ -168,10 +166,10 @@ class AssetModelsController extends Controller
}
}
if ($model->save()) {
return redirect()->route("models.index")->with('success', trans('admin/models/message.update.success'));
return redirect()->route('models.index')->with('success', trans('admin/models/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($model->getErrors());
}
@ -213,7 +211,6 @@ class AssetModelsController extends Controller
return redirect()->route('models.index')->with('success', trans('admin/models/message.delete.success'));
}
/**
* Restore a given Asset Model (mark as un-deleted)
*
@ -231,13 +228,13 @@ class AssetModelsController extends Controller
if (isset($model->id)) {
$model->restore();
return redirect()->route('models.index')->with('success', trans('admin/models/message.restore.success'));
}
return redirect()->back()->with('error', trans('admin/models/message.not_found'));
}
/**
* Get the model information to present to the model view page
*
@ -284,7 +281,6 @@ class AssetModelsController extends Controller
->with('clone_model', $model_to_clone);
}
/**
* Get the custom fields form
*
@ -295,12 +291,9 @@ class AssetModelsController extends Controller
*/
public function getCustomFields($modelId)
{
return view("models.custom_fields_form")->with("model", AssetModel::find($modelId));
return view('models.custom_fields_form')->with('model', AssetModel::find($modelId));
}
/**
* Returns a view that allows the user to bulk edit model attrbutes
*
@ -310,13 +303,10 @@ class AssetModelsController extends Controller
*/
public function postBulkEdit(Request $request)
{
$models_raw_array = $request->input('ids');
// Make sure some IDs have been selected
if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) {
$models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->orderBy('assets_count', 'ASC')->get();
// If deleting....
@ -327,11 +317,11 @@ class AssetModelsController extends Controller
$valid_count++;
}
}
return view('models/bulk-delete', compact('models'))->with('valid_count', $valid_count);
// Otherwise display the bulk edit screen
} else {
$nochange = ['NC' => 'No Change'];
$fieldset_list = $nochange + Helper::customFieldsetList();
$depreciation_list = $nochange + Helper::depreciationList();
@ -340,16 +330,12 @@ class AssetModelsController extends Controller
->with('fieldset_list', $fieldset_list)
->with('depreciation_list', $depreciation_list);
}
}
return redirect()->route('models.index')
->with('error', 'You must select at least one model to edit.');
}
/**
* Returns a view that allows the user to bulk edit model attrbutes
*
@ -359,10 +345,8 @@ class AssetModelsController extends Controller
*/
public function postBulkEditSave(Request $request)
{
$models_raw_array = $request->input('ids');
$update_array = array();
$update_array = [];
if (($request->filled('manufacturer_id') && ($request->input('manufacturer_id') != 'NC'))) {
$update_array['manufacturer_id'] = $request->input('manufacturer_id');
@ -377,17 +361,15 @@ class AssetModelsController extends Controller
$update_array['depreciation_id'] = $request->input('depreciation_id');
}
if (count($update_array) > 0) {
AssetModel::whereIn('id', $models_raw_array)->update($update_array);
return redirect()->route('models.index')
->with('success', trans('admin/models/message.bulkedit.success'));
}
return redirect()->route('models.index')
->with('warning', trans('admin/models/message.bulkedit.error'));
}
/**
@ -404,7 +386,6 @@ class AssetModelsController extends Controller
$models_raw_array = $request->input('ids');
if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) {
$models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->get();
$del_error_count = 0;
@ -435,7 +416,6 @@ class AssetModelsController extends Controller
return redirect()->route('models.index')
->with('error', trans('admin/models/message.bulkdelete.error'));
}
/**
@ -443,7 +423,7 @@ class AssetModelsController extends Controller
* any default values were entered into the form.
*
* @param array $input
* @return boolean
* @return bool
*/
private function shouldAddDefaultValues(array $input)
{

View file

@ -13,7 +13,6 @@ use Illuminate\Support\Facades\View;
class AssetCheckinController extends Controller
{
/**
* Returns a view that presents a form to check an asset back into inventory.
*
@ -33,6 +32,7 @@ class AssetCheckinController extends Controller
}
$this->authorize('checkin', $asset);
return view('hardware/checkin', compact('asset'))->with('statusLabel_list', Helper::statusLabelList())->with('backto', $backto);
}
@ -99,7 +99,6 @@ class AssetCheckinController extends Controller
\Log::debug('After Location ID: '.$asset->location_id);
\Log::debug('After RTD Location ID: '.$asset->rtd_location_id);
if ($request->filled('location_id')) {
\Log::debug('NEW Location ID: '.$request->get('location_id'));
$asset->location_id = e($request->get('location_id'));
@ -115,11 +114,12 @@ class AssetCheckinController extends Controller
event(new CheckoutableCheckedIn($asset, $target, Auth::user(), $request->input('note'), $checkin_at));
if ((isset($user)) && ($backto == 'user')) {
return redirect()->route("users.show", $user->id)->with('success', trans('admin/hardware/message.checkin.success'));
return redirect()->route('users.show', $user->id)->with('success', trans('admin/hardware/message.checkin.success'));
}
return redirect()->route("hardware.index")->with('success', trans('admin/hardware/message.checkin.success'));
return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.checkin.success'));
}
// Redirect to the asset management page with error
return redirect()->route("hardware.index")->with('error', trans('admin/hardware/message.checkin.error').$asset->getErrors());
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.checkin.error').$asset->getErrors());
}
}

View file

@ -2,7 +2,6 @@
namespace App\Http\Controllers\Assets;
use App\Exceptions\CheckoutNotAllowed;
use App\Helpers\Helper;
use App\Http\Controllers\CheckInOutRequest;
@ -15,6 +14,7 @@ use Illuminate\Support\Facades\Auth;
class AssetCheckoutController extends Controller
{
use CheckInOutRequest;
/**
* Returns a view that presents a form to check an asset out to a
* user.
@ -37,9 +37,8 @@ class AssetCheckoutController extends Controller
return view('hardware/checkout', compact('asset'))
->with('statusLabel_list', Helper::deployableStatusLabelList());
}
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.checkout.not_available'));
}
/**
@ -67,8 +66,8 @@ class AssetCheckoutController extends Controller
$asset = $this->updateAssetLocation($asset, $target);
$checkout_at = date("Y-m-d H:i:s");
if (($request->filled('checkout_at')) && ($request->get('checkout_at')!= date("Y-m-d"))) {
$checkout_at = date('Y-m-d H:i:s');
if (($request->filled('checkout_at')) && ($request->get('checkout_at') != date('Y-m-d'))) {
$checkout_at = $request->get('checkout_at');
}
@ -82,7 +81,7 @@ class AssetCheckoutController extends Controller
}
if ($asset->checkOut($target, $admin, $checkout_at, $expected_checkin, e($request->get('note')), $request->get('name'))) {
return redirect()->route("hardware.index")->with('success', trans('admin/hardware/message.checkout.success'));
return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.checkout.success'));
}
// Redirect to the asset management page with error
@ -93,5 +92,4 @@ class AssetCheckoutController extends Controller
return redirect()->back()->with('error', $e->getMessage());
}
}
}

View file

@ -2,14 +2,13 @@
namespace App\Http\Controllers\Assets;
use App\Helpers\StorageHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\AssetFileRequest;
use App\Models\Actionlog;
use App\Models\Asset;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use App\Helpers\StorageHelper;
class AssetFilesController extends Controller
{
@ -32,8 +31,9 @@ class AssetFilesController extends Controller
$this->authorize('update', $asset);
if ($request->hasFile('file')) {
if (!Storage::exists('private_uploads/assets')) Storage::makeDirectory('private_uploads/assets', 775);
if (! Storage::exists('private_uploads/assets')) {
Storage::makeDirectory('private_uploads/assets', 775);
}
foreach ($request->file('file') as $file) {
$extension = $file->getClientOriginalExtension();
@ -41,6 +41,7 @@ class AssetFilesController extends Controller
Storage::put('private_uploads/assets/'.$file_name, file_get_contents($file));
$asset->logUpload($file_name, e($request->get('notes')));
}
return redirect()->back()->with('success', trans('admin/hardware/message.upload.success'));
}
@ -85,8 +86,10 @@ class AssetFilesController extends Controller
if ($contents = file_get_contents(Storage::url($file))) {
return Response::make(Storage::url($file)->header('Content-Type', mime_content_type($file)));
}
return JsonResponse::create(["error" => "Failed validation: "], 500);
return JsonResponse::create(['error' => 'Failed validation: '], 500);
}
return StorageHelper::downloader($file);
}
// Prepare the error message
@ -121,9 +124,11 @@ class AssetFilesController extends Controller
Storage::delete($rel_path.'/'.$log->filename);
}
$log->delete();
return redirect()->back()->with('success', trans('admin/hardware/message.deletefile.success'));
}
$log->delete();
return redirect()->back()
->with('success', trans('admin/hardware/message.deletefile.success'));
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Assets;
use App\Helpers\Helper;
@ -14,13 +15,13 @@ use App\Models\Setting;
use App\Models\User;
use Auth;
use Carbon\Carbon;
use Intervention\Image\Facades\Image;
use DB;
use Gate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Input;
use Intervention\Image\Facades\Image;
use League\Csv\Reader;
use League\Csv\Statement;
use Paginator;
@ -40,9 +41,8 @@ use View;
*/
class AssetsController extends Controller
{
protected $qrCodeDimensions = array( 'height' => 3.5, 'width' => 3.5);
protected $barCodeDimensions = array( 'height' => 2, 'width' => 22);
protected $qrCodeDimensions = ['height' => 3.5, 'width' => 3.5];
protected $barCodeDimensions = ['height' => 2, 'width' => 22];
public function __construct()
{
@ -65,6 +65,7 @@ class AssetsController extends Controller
{
$this->authorize('index', Asset::class);
$company = Company::find($request->input('company_id'));
return view('hardware/index')->with('company', $company);
}
@ -89,6 +90,7 @@ class AssetsController extends Controller
$selected_model = AssetModel::find($request->input('model_id'));
$view->with('selected_model', $selected_model);
}
return $view;
}
@ -114,7 +116,6 @@ class AssetsController extends Controller
$serials = $request->input('serials');
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');
@ -170,7 +171,8 @@ class AssetsController extends Controller
$asset->{$field->convertUnicodeDbSlug()} = \Crypt::encrypt(e(implode(', ', $request->input($field->convertUnicodeDbSlug()))));
} else {
$asset->{$field->convertUnicodeDbSlug()} = \Crypt::encrypt(e($request->input($field->convertUnicodeDbSlug())));
} }
}
}
} else {
if (is_array($request->input($field->convertUnicodeDbSlug()))) {
$asset->{$field->convertUnicodeDbSlug()} = implode(', ', $request->input($field->convertUnicodeDbSlug()));
@ -183,7 +185,6 @@ class AssetsController extends Controller
// Validate the asset before saving
if ($asset->isValid() && $asset->save()) {
if (request('assigned_user')) {
$target = User::find(request('assigned_user'));
$location = $target->location_id;
@ -200,10 +201,7 @@ class AssetsController extends Controller
}
$success = true;
}
}
if ($success) {
@ -213,7 +211,6 @@ class AssetsController extends Controller
}
return redirect()->back()->withInput()->withErrors($asset->getErrors());
}
/**
@ -238,7 +235,6 @@ class AssetsController extends Controller
->with('statuslabel_types', Helper::statusTypeList());
}
/**
* Returns a view that presents information about an asset for detail view.
*
@ -269,10 +265,10 @@ class AssetsController extends Controller
}
}
$qr_code = (object) array(
$qr_code = (object) [
'display' => $settings->qr_code == '1',
'url' => route('qr_code/hardware', $asset->id)
);
'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);
@ -281,7 +277,6 @@ class AssetsController extends Controller
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
}
/**
* Validate and process asset edit form.
*
@ -290,7 +285,6 @@ class AssetsController extends Controller
* @since [v1.0]
* @return Redirect
*/
public function update(ImageUploadRequest $request, $assetId = null)
{
// Check if the asset exists
@ -315,7 +309,6 @@ class AssetsController extends Controller
$asset->location_id = $request->input('rtd_location_id', null);
}
if ($request->filled('image_delete')) {
try {
unlink(public_path().'/uploads/assets/'.$asset->image);
@ -323,10 +316,8 @@ class AssetsController extends Controller
} catch (\Exception $e) {
\Log::info($e);
}
}
// Update the asset data
$asset_tag = $request->input('asset_tags');
$serial = $request->input('serials');
@ -366,9 +357,8 @@ class AssetsController extends Controller
}
}
if ($asset->save()) {
return redirect()->route("hardware.show", $assetId)
return redirect()->route('hardware.show', $assetId)
->with('success', trans('admin/hardware/message.update.success'));
}
@ -395,7 +385,7 @@ class AssetsController extends Controller
DB::table('assets')
->where('id', $asset->id)
->update(array('assigned_to' => null));
->update(['assigned_to' => null]);
if ($asset->image) {
try {
@ -410,8 +400,6 @@ class AssetsController extends Controller
return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.delete.success'));
}
/**
* Searches the assets table by asset tag, and redirects if it finds one
*
@ -421,14 +409,16 @@ class AssetsController extends Controller
*/
public function getAssetByTag(Request $request)
{
$topsearch = ($request->get('topsearch')=="true");
$topsearch = ($request->get('topsearch') == 'true');
if (! $asset = Asset::where('asset_tag', '=', $request->get('assetTag'))->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);
}
/**
* Return a QR code for the asset
*
@ -450,20 +440,22 @@ class AssetsController extends Controller
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', array(-2, -2, -2, -2));
$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');
}
}
}
return 'That asset is invalid';
}
}
/**
* Return a 2D barcode for the asset
*
@ -481,6 +473,7 @@ class AssetsController extends Controller
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)
@ -490,18 +483,17 @@ class AssetsController extends Controller
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) {
\Log::debug('The barcode format is invalid.');
return response(file_get_contents(public_path('uploads/barcodes/invalid_barcode.gif')))->header('Content-type', 'image/gif');
}
}
}
}
/**
* Return a label for an individual asset.
*
@ -523,7 +515,6 @@ class AssetsController extends Controller
}
}
/**
* Returns a view that presents a form to clone an asset.
*
@ -564,6 +555,7 @@ class AssetsController extends Controller
public function getImportHistory()
{
$this->authorize('admin');
return view('hardware/history');
}
@ -584,37 +576,36 @@ class AssetsController extends Controller
*/
public function postImportHistory(Request $request)
{
if (! $request->hasFile('user_import_csv')) {
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');
if (! ini_get('auto_detect_line_endings')) {
ini_set('auto_detect_line_endings', '1');
}
$csv = Reader::createFromPath($request->file('user_import_csv'));
$csv->setHeaderOffset(0);
$header = $csv->getHeader();
$isCheckinHeaderExplicit = in_array("checkin date", (array_map('strtolower', $header)));
$isCheckinHeaderExplicit = in_array('checkin date', (array_map('strtolower', $header)));
$results = $csv->getRecords();
$item = array();
$status = array();
$status['error'] = array();
$status['success'] = array();
$item = [];
$status = [];
$status['error'] = [];
$status['success'] = [];
foreach ($results as $row) {
if (is_array($row)) {
$row = array_change_key_case($row, CASE_LOWER);
$asset_tag = Helper::array_smart_fetch($row, "asset tag");
$asset_tag = Helper::array_smart_fetch($row, 'asset tag');
if (! array_key_exists($asset_tag, $item)) {
$item[$asset_tag] = array();
$item[$asset_tag] = [];
}
$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');
$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');
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'] = '';
}
@ -623,9 +614,9 @@ class AssetsController extends Controller
$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");
$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');
if ($asset = Asset::where('asset_tag', '=', $asset_tag)->first()) {
$item[$asset_tag][$batch_counter]['asset_id'] = $asset->id;
$base_username = User::generateFormattedNameFromFullName(Setting::getSettings()->username_format, $item[$asset_tag][$batch_counter]['name']);
@ -668,7 +659,7 @@ class AssetsController extends Controller
//$user is now matched user from db
$item[$asset_tag][$batch_counter]['user_id'] = $user->id;
Actionlog::firstOrCreate(array(
Actionlog::firstOrCreate([
'item_id' => $asset->id,
'item_type' => Asset::class,
'user_id' => Auth::user()->id,
@ -677,7 +668,7 @@ class AssetsController extends Controller
'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'];
@ -696,27 +687,25 @@ class AssetsController extends Controller
if (! empty($checkin_date)) {
//only make a checkin there is a valid checkin date or we created one on import.
Actionlog::firstOrCreate(array(
'item_id' =>
$item[$asset_tag][$batch_counter]['asset_id'],
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'
));
'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'];
$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.';
}
} 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.';
$status['error'][]['user'][Helper::array_smart_fetch($row, 'name')]['msg'] = 'User does not exist so no checkin log was created.';
}
} else {
$item[$asset_tag][$batch_counter]['asset_id'] = null;
@ -724,6 +713,7 @@ class AssetsController extends Controller
}
}
}
return view('hardware/history')->with('status', $status);
}
@ -752,12 +742,13 @@ class AssetsController extends Controller
$logaction = new Actionlog();
$logaction->item_type = Asset::class;
$logaction->item_id = $asset->id;
$logaction->created_at = date("Y-m-d H:i:s");
$logaction->created_at = date('Y-m-d H:i:s');
$logaction->user_id = Auth::user()->id;
$logaction->logaction('restored');
return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.restore.success'));
}
return redirect()->route('hardware.index')->with('error', trans('admin/hardware/message.does_not_exist'));
}
@ -765,41 +756,42 @@ class AssetsController extends Controller
{
$this->authorize('audit', Asset::class);
$dt = Carbon::now()->addMonths(12)->toDateString();
return view('hardware/quickscan')->with('next_audit_date', $dt);
}
public function audit($id)
{
$settings = Setting::getSettings();
$this->authorize('audit', Asset::class);
$dt = Carbon::now()->addMonths($settings->audit_interval)->toDateString();
$asset = Asset::findOrFail($id);
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');
}
public function auditStore(Request $request, $id)
{
$this->authorize('audit', Asset::class);
$rules = array(
$rules = [
'location_id' => 'exists:locations,id|nullable|numeric',
'next_audit_date' => 'date|nullable'
);
'next_audit_date' => 'date|nullable',
];
$validator = \Validator::make($request->all(), $rules);
@ -822,22 +814,23 @@ class AssetsController extends Controller
$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);
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);
}
$asset->logAudit($request->input('note'), $request->input('location_id'), $file_name);
return redirect()->to("hardware")->with('success', trans('admin/hardware/message.audit.success'));
return redirect()->to('hardware')->with('success', trans('admin/hardware/message.audit.success'));
}
}
@ -853,5 +846,4 @@ class AssetsController extends Controller
return view('hardware/requested', compact('requestedItems'));
}
}

View file

@ -47,6 +47,7 @@ class BulkAssetsController extends Controller
$assets->each(function ($asset) {
$this->authorize('delete', $asset);
});
return view('hardware/bulk-delete')->with('assets', $assets);
case 'edit':
return view('hardware/bulk')
@ -54,6 +55,7 @@ class BulkAssetsController extends Controller
->with('statuslabel_list', Helper::statusLabelList());
}
}
return redirect()->back()->with('error', 'No action selected');
}
@ -72,7 +74,7 @@ class BulkAssetsController extends Controller
\Log::debug($request->input('ids'));
if (! $request->filled('ids') || count($request->input('ids')) <= 0) {
return redirect()->route("hardware.index")->with('warning', trans('No assets selected, so nothing was updated.'));
return redirect()->route('hardware.index')->with('warning', trans('No assets selected, so nothing was updated.'));
}
$assets = array_keys($request->input('ids'));
@ -107,7 +109,7 @@ class BulkAssetsController extends Controller
if ($request->filled('company_id')) {
$this->update_array['company_id'] = $request->input('company_id');
if ($request->input('company_id')=="clear") {
if ($request->input('company_id') == 'clear') {
$this->update_array['company_id'] = null;
}
}
@ -123,22 +125,23 @@ class BulkAssetsController extends Controller
->where('id', $assetId)
->update($this->update_array);
} // endforeach
return redirect()->route("hardware.index")->with('success', trans('admin/hardware/message.update.success'));
return redirect()->route('hardware.index')->with('success', trans('admin/hardware/message.update.success'));
// no values given, nothing to update
}
return redirect()->route("hardware.index")->with('warning', trans('admin/hardware/message.update.nothing_updated'));
return redirect()->route('hardware.index')->with('warning', trans('admin/hardware/message.update.nothing_updated'));
}
/**
* Array to store update data per item
* @var Array
* @var array
*/
private $update_array;
/**
* Adds parameter to update array for an item if it exists in request
* @param String $field field name
* @param string $field field name
* @return BulkAssetsController Model for Chaining
*/
protected function conditionallyAddItem($field)
@ -146,6 +149,7 @@ class BulkAssetsController extends Controller
if (request()->filled($field)) {
$this->update_array[$field] = request()->input($field);
}
return $this;
}
@ -173,10 +177,12 @@ class BulkAssetsController extends Controller
->where('id', $asset->id)
->update($update_array);
} // endforeach
return redirect()->to("hardware")->with('success', trans('admin/hardware/message.delete.success'));
return redirect()->to('hardware')->with('success', trans('admin/hardware/message.delete.success'));
// no values given, nothing to update
}
return redirect()->to("hardware")->with('info', trans('admin/hardware/message.delete.nothing_updated'));
return redirect()->to('hardware')->with('info', trans('admin/hardware/message.delete.nothing_updated'));
}
/**
@ -215,8 +221,8 @@ class BulkAssetsController extends Controller
}
}
}
$checkout_at = date("Y-m-d H:i:s");
if (($request->filled('checkout_at')) && ($request->get('checkout_at')!= date("Y-m-d"))) {
$checkout_at = date('Y-m-d H:i:s');
if (($request->filled('checkout_at')) && ($request->get('checkout_at') != date('Y-m-d'))) {
$checkout_at = e($request->get('checkout_at'));
}
@ -228,7 +234,6 @@ class BulkAssetsController extends Controller
$errors = [];
DB::transaction(function () use ($target, $admin, $checkout_at, $expected_checkin, $errors, $asset_ids, $request) {
foreach ($asset_ids as $asset_id) {
$asset = Asset::findOrFail($asset_id);
$this->authorize('checkout', $asset);
@ -248,12 +253,12 @@ class BulkAssetsController extends Controller
if (! $errors) {
// Redirect to the new asset page
return redirect()->to("hardware")->with('success', trans('admin/hardware/message.checkout.success'));
return redirect()->to('hardware')->with('success', trans('admin/hardware/message.checkout.success'));
}
// Redirect to the asset management page with error
return redirect()->to("hardware/bulk-checkout")->with('error', trans('admin/hardware/message.checkout.error'))->withErrors($errors);
return redirect()->to('hardware/bulk-checkout')->with('error', trans('admin/hardware/message.checkout.error'))->withErrors($errors);
} catch (ModelNotFoundException $e) {
return redirect()->to("hardware/bulk-checkout")->with('error', $e->getErrors());
return redirect()->to('hardware/bulk-checkout')->with('error', $e->getErrors());
}
}
}

View file

@ -41,8 +41,6 @@ class ForgotPasswordController extends Controller
return property_exists($this, 'subject') ? $this->subject : \Lang::get('mail.reset_link');
}
/**
* Send a reset link to the given user.
*
@ -57,13 +55,10 @@ class ForgotPasswordController extends Controller
* buffer overflow issues with attackers sending very large
* payloads through.
*/
$request->validate([
'username' => ['required', 'max:255'],
]);
/**
* If we find a matching email with an activated user, we will
* send the password reset link to the user.
@ -85,7 +80,6 @@ class ForgotPasswordController extends Controller
\Log::info('Password reset attempt: User matching username '.$request->input('username').' NOT FOUND or user is inactive');
}
/**
* If an error was returned by the password broker, we will get this message
* translated so we can notify a user of the problem. We'll redirect back
@ -103,6 +97,4 @@ class ForgotPasswordController extends Controller
// so we give them a generic "If this exists, we're TOTALLY gonna email you" response
return redirect()->route('login')->with('success', trans('passwords.sent'));
}
}

View file

@ -27,7 +27,6 @@ use Redirect;
*/
class LoginController extends Controller
{
use ThrottlesLogins;
// This tells the auth controller to use username instead of email address
@ -67,7 +66,7 @@ class LoginController extends Controller
$this->saml = $saml;
}
function showLoginForm(Request $request)
public function showLoginForm(Request $request)
{
$this->loginViaRemoteUser($request);
$this->loginViaSaml($request);
@ -75,11 +74,11 @@ class LoginController extends Controller
return redirect()->intended('/');
}
if ($this->saml->isEnabled() && Setting::getSettings()->saml_forcelogin == "1" && !($request->has('nosaml') || $request->session()->has('error'))) {
if ($this->saml->isEnabled() && Setting::getSettings()->saml_forcelogin == '1' && ! ($request->has('nosaml') || $request->session()->has('error'))) {
return redirect()->route('saml.login');
}
if (Setting::getSettings()->login_common_disabled == "1") {
if (Setting::getSettings()->login_common_disabled == '1') {
return view('errors.403');
}
@ -105,7 +104,7 @@ class LoginController extends Controller
$samlData = $request->session()->get('saml_login');
if ($saml->isEnabled() && ! empty($samlData)) {
try {
Log::debug("Attempting to log user in by SAML authentication.");
Log::debug('Attempting to log user in by SAML authentication.');
$user = $saml->samlLogin($samlData);
if (! is_null($user)) {
Auth::login($user);
@ -121,7 +120,7 @@ class LoginController extends Controller
$user->save();
}
} catch (\Exception $e) {
\Log::warning("There was an error authenticating the SAML user: " . $e->getMessage());
\Log::warning('There was an error authenticating the SAML user: '.$e->getMessage());
throw new \Exception($e->getMessage());
}
}
@ -146,7 +145,7 @@ class LoginController extends Controller
try {
return $ldap->ldapLogin($request->input('username'), $request->input('password'));
} catch (\Exception $ex) {
LOG::debug("LDAP user login: " . $ex->getMessage());
LOG::debug('LDAP user login: '.$ex->getMessage());
throw new \Exception($ex->getMessage());
}
}
@ -155,7 +154,7 @@ class LoginController extends Controller
{
$header_name = Setting::getSettings()->login_remote_user_header_name ?: 'REMOTE_USER';
$remote_user = $request->server($header_name);
if (Setting::getSettings()->login_remote_user_enabled == "1" && isset($remote_user) && !empty($remote_user)) {
if (Setting::getSettings()->login_remote_user_enabled == '1' && isset($remote_user) && ! empty($remote_user)) {
Log::debug("Authenticating via HTTP header $header_name.");
$strip_prefixes = [
@ -170,7 +169,7 @@ class LoginController extends Controller
$pos = 0;
foreach ($strip_prefixes as $needle) {
if (($pos = strpos($remote_user, $needle)) !== FALSE) {
if (($pos = strpos($remote_user, $needle)) !== false) {
$pos += strlen($needle);
break;
}
@ -178,14 +177,16 @@ class LoginController extends Controller
if ($pos > 0) {
$remote_user = substr($remote_user, $pos);
};
}
try {
$user = User::where('username', '=', $remote_user)->whereNull('deleted_at')->where('activated', '=', '1')->first();
Log::debug("Remote user auth lookup complete");
if(!is_null($user)) Auth::login($user, $request->input('remember'));
Log::debug('Remote user auth lookup complete');
if (! is_null($user)) {
Auth::login($user, $request->input('remember'));
}
} catch (Exception $e) {
Log::debug("There was an error authenticating the Remote user: " . $e->getMessage());
Log::debug('There was an error authenticating the Remote user: '.$e->getMessage());
}
}
}
@ -197,7 +198,7 @@ class LoginController extends Controller
*/
public function login(Request $request)
{
if (Setting::getSettings()->login_common_disabled == "1") {
if (Setting::getSettings()->login_common_disabled == '1') {
return view('errors.403');
}
@ -212,6 +213,7 @@ class LoginController extends Controller
if ($lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
@ -219,33 +221,32 @@ class LoginController extends Controller
// Should we even check for LDAP users?
if (Setting::getSettings()->ldap_enabled) { // avoid hitting the $this->ldap
LOG::debug("LDAP is enabled.");
LOG::debug('LDAP is enabled.');
try {
LOG::debug("Attempting to log user in by LDAP authentication.");
LOG::debug('Attempting to log user in by LDAP authentication.');
$user = $this->loginViaLdap($request);
Auth::login($user, $request->input('remember'));
// If the user was unable to login via LDAP, log the error and let them fall through to
// local authentication.
} catch (\Exception $e) {
Log::debug("There was an error authenticating the LDAP user: ".$e->getMessage());
Log::debug('There was an error authenticating the LDAP user: '.$e->getMessage());
}
}
// If the user wasn't authenticated via LDAP, skip to local auth
if (! $user) {
Log::debug("Authenticating user against database.");
Log::debug('Authenticating user against database.');
// Try to log the user in
if (! Auth::attempt(['username' => $request->input('username'), 'password' => $request->input('password'), 'activated' => 1], $request->input('remember'))) {
if (! $lockedOut) {
$this->incrementLoginAttempts($request);
}
Log::debug("Local authentication failed.");
Log::debug('Local authentication failed.');
return redirect()->back()->withInput()->with('error', trans('auth/message.account_not_found'));
} else {
$this->clearLoginAttempts($request);
}
}
@ -259,7 +260,6 @@ class LoginController extends Controller
return redirect()->intended()->with('success', trans('auth/message.signin.success'));
}
/**
* Two factor enrollment page
*
@ -273,7 +273,6 @@ class LoginController extends Controller
return redirect()->route('login')->with('error', trans('auth/general.login_prompt'));
}
$settings = Setting::getSettings();
$user = Auth::user();
@ -310,7 +309,6 @@ class LoginController extends Controller
return view('auth.two_factor_enroll')->with('barcode_obj', $barcode_obj);
}
/**
* Two factor code form page
*
@ -344,7 +342,6 @@ class LoginController extends Controller
*/
public function postTwoFactorAuth(Request $request)
{
if (! Auth::check()) {
return redirect()->route('login')->with('error', trans('auth/general.login_prompt'));
}
@ -364,15 +361,13 @@ class LoginController extends Controller
$user->two_factor_enrolled = 1;
$user->save();
$request->session()->put('2fa_authed', 'true');
return redirect()->route('home')->with('success', 'You are logged in!');
}
return redirect()->route('two-factor')->with('error', trans('auth/message.two_factor.invalid_code'));
}
/**
* Logout page.
*
@ -392,7 +387,7 @@ class LoginController extends Controller
$sloRedirectUrl = $request->session()->get('saml_slo_redirect_url');
if (! empty($auth->getSLOurl()) && $settings->saml_slo == '1' && $saml->isAuthenticated() && empty($sloRedirectUrl)) {
$sloRequestUrl = $auth->logout(null, array(), $saml->getNameId(), $saml->getSessionIndex(), true, $saml->getNameIdFormat(), $saml->getNameIdNameQualifier(), $saml->getNameIdSPNameQualifier());
$sloRequestUrl = $auth->logout(null, [], $saml->getNameId(), $saml->getSessionIndex(), true, $saml->getNameIdFormat(), $saml->getNameIdNameQualifier(), $saml->getNameIdSPNameQualifier());
}
$saml->clearData();
@ -419,7 +414,6 @@ class LoginController extends Controller
return redirect()->route('login')->with(['success' => trans('auth/message.logout.success'), 'loggedout' => true]);
}
/**
* Get a validator for an incoming registration request.
*
@ -434,7 +428,6 @@ class LoginController extends Controller
]);
}
public function username()
{
return 'username';
@ -461,7 +454,6 @@ class LoginController extends Controller
->withErrors([$this->username() => $message]);
}
/**
* Override the lockout time and duration
*
@ -480,7 +472,8 @@ class LoginController extends Controller
);
}
public function legacyAuthRedirect() {
public function legacyAuthRedirect()
{
return redirect()->route('login');
}
@ -488,5 +481,4 @@ class LoginController extends Controller
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
}

View file

@ -6,17 +6,18 @@ use App\Http\Controllers\Controller;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function showRegistrationForm() {
public function showRegistrationForm()
{
abort(404, 'Page not found');
}
public function register() {
public function register()
{
abort(404, 'Page not found');
}
}

View file

@ -54,7 +54,6 @@ class ResetPasswordController extends Controller
];
}
protected function credentials(Request $request)
{
return $request->only(
@ -62,21 +61,18 @@ class ResetPasswordController extends Controller
);
}
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
[
'token' => $token,
'username' => $request->input('username')
'username' => $request->input('username'),
]
);
}
public function reset(Request $request)
{
$messages = [
'password.not_in' => trans('validation.disallow_same_pwd_as_user_fields'),
];
@ -87,15 +83,13 @@ class ResetPasswordController extends Controller
$user = User::where('username', '=', $request->input('username'))->first();
$broker = $this->broker();
if (strpos(Setting::passwordComplexityRulesSaving('store'), 'disallow_same_pwd_as_user_fields') !== FALSE) {
if (strpos(Setting::passwordComplexityRulesSaving('store'), 'disallow_same_pwd_as_user_fields') !== false) {
$request->validate(
[
'password' => 'required|notIn:["'.$user->email.'","'.$user->username.'","'.$user->first_name.'","'.$user->last_name.'"'
'password' => 'required|notIn:["'.$user->email.'","'.$user->username.'","'.$user->first_name.'","'.$user->last_name.'"',
], $messages);
}
$response = $broker->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
@ -107,14 +101,10 @@ class ResetPasswordController extends Controller
: $this->sendResetFailedResponse($request, $response);
}
protected function sendResetFailedResponse(Request $request, $response)
{
return redirect()->back()
->withInput(['username'=> $request->input('username')])
->withErrors(['username' => trans($response), 'password' => trans($response)]);
}
}

View file

@ -2,9 +2,9 @@
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\Saml;
use Illuminate\Http\Request;
use Log;
/**
@ -75,7 +75,8 @@ class SamlController extends Controller
public function login(Request $request)
{
$auth = $this->saml->getAuth();
$ssoUrl = $auth->login(null, array(), false, false, false, false);
$ssoUrl = $auth->login(null, [], false, false, false, false);
return redirect()->away($ssoUrl);
}
@ -101,8 +102,9 @@ class SamlController extends Controller
$errors = $auth->getErrors();
if (! empty($errors)) {
Log::error("There was an error with SAML ACS: " . implode(', ', $errors));
Log::error("Reason: " . $auth->getLastErrorReason());
Log::error('There was an error with SAML ACS: '.implode(', ', $errors));
Log::error('Reason: '.$auth->getLastErrorReason());
return redirect()->route('login')->with('error', trans('auth/message.signin.error'));
}
@ -133,8 +135,9 @@ class SamlController extends Controller
$errors = $auth->getErrors();
if (! empty($errors)) {
Log::error("There was an error with SAML SLS: " . implode(', ', $errors));
Log::error("Reason: " . $auth->getLastErrorReason());
Log::error('There was an error with SAML SLS: '.implode(', ', $errors));
Log::error('Reason: '.$auth->getLastErrorReason());
return view('errors.403');
}

View file

@ -24,7 +24,6 @@ class BulkAssetModelsController extends Controller
// Make sure some IDs have been selected
if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) {
$models = AssetModel::whereIn('id', $models_raw_array)
->withCount('assets as assets_count')
->orderBy('assets_count', 'ASC')
@ -38,12 +37,14 @@ class BulkAssetModelsController extends Controller
$valid_count++;
}
}
return view('models/bulk-delete', compact('models'))->with('valid_count', $valid_count);
// Otherwise display the bulk edit screen
}
$nochange = ['NC' => 'No Change'];
return view('models/bulk-edit', compact('models'))
->with('fieldset_list', $nochange + Helper::customFieldsetList())
->with('depreciation_list', $nochange + Helper::depreciationList());
@ -63,9 +64,8 @@ class BulkAssetModelsController extends Controller
*/
public function update(Request $request)
{
$models_raw_array = $request->input('ids');
$update_array = array();
$update_array = [];
if (($request->filled('manufacturer_id') && ($request->input('manufacturer_id') != 'NC'))) {
$update_array['manufacturer_id'] = $request->input('manufacturer_id');
@ -80,17 +80,15 @@ class BulkAssetModelsController extends Controller
$update_array['depreciation_id'] = $request->input('depreciation_id');
}
if (count($update_array) > 0) {
AssetModel::whereIn('id', $models_raw_array)->update($update_array);
return redirect()->route('models.index')
->with('success', trans('admin/models/message.bulkedit.success'));
}
return redirect()->route('models.index')
->with('warning', trans('admin/models/message.bulkedit.error'));
}
/**
@ -106,7 +104,6 @@ class BulkAssetModelsController extends Controller
$models_raw_array = $request->input('ids');
if ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) {
$models = AssetModel::whereIn('id', $models_raw_array)->withCount('assets as assets_count')->get();
$del_error_count = 0;
@ -132,7 +129,5 @@ class BulkAssetModelsController extends Controller
return redirect()->route('models.index')
->with('error', trans('admin/models/message.bulkdelete.error'));
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Helpers\Helper;
@ -17,7 +18,6 @@ use Str;
*/
class CategoriesController extends Controller
{
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the categories listing, which is generated in getDatatable.
@ -32,10 +32,10 @@ class CategoriesController extends Controller
{
// Show the page
$this->authorize('view', Category::class);
return view('categories/index');
}
/**
* Returns a form view to create a new category.
*
@ -49,11 +49,11 @@ class CategoriesController extends Controller
{
// Show the page
$this->authorize('create', Category::class);
return view('categories/edit')->with('item', new Category)
->with('category_types', Helper::categoryTypeList());
}
/**
* Validates and stores the new category data.
*
@ -100,11 +100,11 @@ class CategoriesController extends Controller
if (is_null($item = Category::find($categoryId))) {
return redirect()->route('categories.index')->with('error', trans('admin/categories/message.does_not_exist'));
}
return view('categories/edit', compact('item'))
->with('category_types', Helper::categoryTypeList());
}
/**
* Validates and stores the updated category data.
*
@ -134,7 +134,6 @@ class CategoriesController extends Controller
$category->require_acceptance = $request->input('require_acceptance', '0');
$category->checkin_email = $request->input('checkin_email', '0');
$category = $request->handleImages($category);
if ($category->save()) {
@ -172,7 +171,6 @@ class CategoriesController extends Controller
return redirect()->route('categories.index')->with('success', trans('admin/categories/message.delete.success'));
}
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the categories detail view, which is generated in getDataView.
@ -188,7 +186,6 @@ class CategoriesController extends Controller
{
$this->authorize('view', Category::class);
if ($category = Category::find($id)) {
if ($category->category_type == 'asset') {
$category_type = 'hardware';
$category_type_route = 'assets';
@ -199,6 +196,7 @@ class CategoriesController extends Controller
$category_type = $category->category_type;
$category_type_route = $category->category_type.'s';
}
return view('categories/view', compact('category'))
->with('category_type', $category_type)
->with('category_type_route', $category_type_route);

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Models\Asset;
@ -15,8 +16,7 @@ trait CheckInOutRequest
protected function determineCheckoutTarget()
{
// This item is checked out to a location
switch(request('checkout_to_type'))
{
switch (request('checkout_to_type')) {
case 'location':
return Location::findOrFail(request('assigned_location'));
case 'asset':
@ -24,6 +24,7 @@ trait CheckInOutRequest
case 'user':
return User::findOrFail(request('assigned_user'));
}
return null;
}
@ -35,8 +36,7 @@ trait CheckInOutRequest
*/
protected function updateAssetLocation($asset, $target)
{
switch(request('checkout_to_type'))
{
switch (request('checkout_to_type')) {
case 'location':
$asset->location_id = $target->id;
break;
@ -51,6 +51,7 @@ trait CheckInOutRequest
$asset->location_id = $target->location_id;
break;
}
return $asset;
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ImageUploadRequest;
@ -12,10 +13,8 @@ use Illuminate\Support\Facades\Storage;
*
* @version v1.0
*/
final class CompaniesController extends Controller
{
/**
* Returns view to display listing of companies.
*
@ -68,10 +67,10 @@ final class CompaniesController extends Controller
return redirect()->route('companies.index')
->with('success', trans('admin/companies/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($company->getErrors());
}
/**
* Return form to edit existing company.
*
@ -113,14 +112,13 @@ final class CompaniesController extends Controller
$company->name = $request->input('name');
$company = $request->handleImages($company);
if ($company->save()) {
return redirect()->route('companies.index')
->with('success', trans('admin/companies/message.update.success'));
}
return redirect()->route('companies.edit', ['company' => $companyId])
->with('error', trans('admin/companies/message.update.error'));
}
@ -156,11 +154,13 @@ final class CompaniesController extends Controller
}
$company->delete();
return redirect()->route('companies.index')
->with('success', trans('admin/companies/message.delete.success'));
}
public function show($id) {
public function show($id)
{
$this->authorize('view', Company::class);
if (is_null($company = Company::find($id))) {

View file

@ -15,7 +15,6 @@ use Illuminate\Support\Facades\Validator;
class ComponentCheckinController extends Controller
{
/**
* Returns a view that allows the checkin of a component from an asset.
*
@ -39,14 +38,13 @@ class ComponentCheckinController extends Controller
trans('admin/components/message.not_found'));
}
$this->authorize('checkin', $component);
return view('components/checkin', compact('component_assets', 'component', 'asset'));
}
return redirect()->route('components.index')->with('error', trans('admin/components/messages.not_found'));
}
/**
* Validate and store checkin data.
*
@ -66,12 +64,11 @@ class ComponentCheckinController extends Controller
trans('admin/components/message.not_found'));
}
$this->authorize('checkin', $component);
$max_to_checkin = $component_assets->assigned_qty;
$validator = Validator::make($request->all(), [
"checkin_qty" => "required|numeric|between:1,$max_to_checkin"
'checkin_qty' => "required|numeric|between:1,$max_to_checkin",
]);
if ($validator->fails()) {
@ -102,7 +99,7 @@ class ComponentCheckinController extends Controller
return redirect()->route('components.index')->with('success',
trans('admin/components/message.checkin.success'));
}
return redirect()->route('components.index')->with('error', trans('admin/components/message.does_not_exist'));
}
}

View file

@ -32,6 +32,7 @@ class ComponentCheckoutController extends Controller
return redirect()->route('components.index')->with('error', trans('admin/components/message.not_found'));
}
$this->authorize('checkout', $component);
return view('components/checkout', compact('component'));
}
@ -58,8 +59,8 @@ class ComponentCheckoutController extends Controller
$max_to_checkout = $component->numRemaining();
$validator = Validator::make($request->all(), [
"asset_id" => "required",
"assigned_qty" => "required|numeric|between:1,$max_to_checkout"
'asset_id' => 'required',
'assigned_qty' => "required|numeric|between:1,$max_to_checkout",
]);
if ($validator->fails()) {
@ -85,7 +86,7 @@ class ComponentCheckoutController extends Controller
'user_id' => $admin_user->id,
'created_at' => date('Y-m-d H:i:s'),
'assigned_qty' => $request->input('assigned_qty'),
'asset_id' => $asset_id
'asset_id' => $asset_id,
]);
event(new CheckoutableCheckedOut($component, $asset, Auth::user(), $request->input('note')));

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Components;
use App\Http\Controllers\Controller;
@ -31,10 +32,10 @@ class ComponentsController extends Controller
public function index()
{
$this->authorize('view', Component::class);
return view('components/index');
}
/**
* Returns a form to create a new component.
*
@ -47,11 +48,11 @@ class ComponentsController extends Controller
public function create()
{
$this->authorize('create', Component::class);
return view('components/edit')->with('category_type', 'component')
->with('item', new Component);
}
/**
* Validate and store data for new component.
*
@ -83,6 +84,7 @@ class ComponentsController extends Controller
if ($component->save()) {
return redirect()->route('components.index')->with('success', trans('admin/components/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($component->getErrors());
}
@ -100,12 +102,13 @@ class ComponentsController extends Controller
{
if ($item = Component::find($componentId)) {
$this->authorize('update', $item);
return view('components/edit', compact('item'))->with('category_type', 'component');
}
return redirect()->route('components.index')->with('error', trans('admin/components/message.does_not_exist'));
}
/**
* Return a view to edit a component.
*
@ -124,7 +127,7 @@ class ComponentsController extends Controller
}
$min = $component->numCHeckedOut();
$validator = Validator::make($request->all(), [
"qty" => "required|numeric|min:$min"
'qty' => "required|numeric|min:$min",
]);
if ($validator->fails()) {
@ -152,6 +155,7 @@ class ComponentsController extends Controller
if ($component->save()) {
return redirect()->route('components.index')->with('success', trans('admin/components/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($component->getErrors());
}
@ -182,6 +186,7 @@ class ComponentsController extends Controller
}
$component->delete();
return redirect()->route('components.index')->with('success', trans('admin/components/message.delete.success'));
}
@ -201,6 +206,7 @@ class ComponentsController extends Controller
if (isset($component->id)) {
$this->authorize('view', $component);
return view('components/view', compact('component'));
}
// Redirect to the user management page

View file

@ -12,7 +12,6 @@ use Illuminate\Support\Facades\Input;
class ConsumableCheckoutController extends Controller
{
/**
* Return a view to checkout a consumable to a user.
*
@ -29,6 +28,7 @@ class ConsumableCheckoutController extends Controller
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.does_not_exist'));
}
$this->authorize('checkout', $consumable);
return view('consumables/checkout', compact('consumable'));
}
@ -65,13 +65,12 @@ class ConsumableCheckoutController extends Controller
$consumable->users()->attach($consumable->id, [
'consumable_id' => $consumable->id,
'user_id' => $admin_user->id,
'assigned_to' => e($request->input('assigned_to'))
'assigned_to' => e($request->input('assigned_to')),
]);
event(new CheckoutableCheckedOut($consumable, $user, Auth::user(), $request->input('note')));
// Redirect to the new consumable page
return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.checkout.success'));
}
}

View file

@ -30,10 +30,10 @@ class ConsumablesController extends Controller
public function index()
{
$this->authorize('index', Consumable::class);
return view('consumables/index');
}
/**
* Return a view to display the form view to create a new consumable
*
@ -46,11 +46,11 @@ class ConsumablesController extends Controller
public function create()
{
$this->authorize('create', Consumable::class);
return view('consumables/edit')->with('category_type', 'consumable')
->with('item', new Consumable);
}
/**
* Validate and store new consumable data.
*
@ -79,7 +79,6 @@ class ConsumablesController extends Controller
$consumable->qty = $request->input('qty');
$consumable->user_id = Auth::id();
$consumable = $request->handleImages($consumable);
if ($consumable->save()) {
@ -87,7 +86,6 @@ class ConsumablesController extends Controller
}
return redirect()->back()->withInput()->withErrors($consumable->getErrors());
}
/**
@ -104,14 +102,13 @@ class ConsumablesController extends Controller
{
if ($item = Consumable::find($consumableId)) {
$this->authorize($item);
return view('consumables/edit', compact('item'))->with('category_type', 'consumable');
}
return redirect()->route('consumables.index')->with('error', trans('admin/consumables/message.does_not_exist'));
}
/**
* Returns a form view to edit a consumable.
*
@ -149,6 +146,7 @@ class ConsumablesController extends Controller
if ($consumable->save()) {
return redirect()->route('consumables.index')->with('success', trans('admin/consumables/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($consumable->getErrors());
}
@ -189,8 +187,8 @@ class ConsumablesController extends Controller
if (isset($consumable->id)) {
return view('consumables/view', compact('consumable'));
}
return redirect()->route('consumables.index')
->with('error', trans('admin/consumables/message.does_not_exist'));
}
}

View file

@ -19,6 +19,7 @@
* etc have been included in this documentation (excluding vendors, Laravel core, etc)
* for simplicity.
*/
namespace App\Http\Controllers;
use Auth;

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Helpers\Helper;
@ -17,10 +18,8 @@ use Redirect;
* @version v2.0
* @author [Brady Wetherington] [<uberbrady@gmail.com>]
*/
class CustomFieldsController extends Controller
{
/**
* Returns a view with a listing of custom fields.
*
@ -33,13 +32,12 @@ class CustomFieldsController extends Controller
{
$this->authorize('view', CustomField::class);
$fieldsets = CustomFieldset::with("fields", "models")->get();
$fields = CustomField::with("fieldset")->get();
$fieldsets = CustomFieldset::with('fields', 'models')->get();
$fields = CustomField::with('fieldset')->get();
return view("custom_fields.index")->with("custom_fieldsets", $fieldsets)->with("custom_fields", $fields);
return view('custom_fields.index')->with('custom_fieldsets', $fieldsets)->with('custom_fields', $fields);
}
/**
* Just redirect the user back if they try to view the details of a field.
* We already show those details on the listing page.
@ -50,14 +48,11 @@ class CustomFieldsController extends Controller
* @return Redirect
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function show()
{
return redirect()->route("fields.index");
return redirect()->route('fields.index');
}
/**
* Returns a view with a form to create a new custom field.
*
@ -71,13 +66,12 @@ class CustomFieldsController extends Controller
{
$this->authorize('create', CustomField::class);
return view("custom_fields.fields.edit",[
return view('custom_fields.fields.edit', [
'predefinedFormats' => Helper::predefined_formats(),
'customFormat' => ''
'customFormat' => '',
])->with('field', new CustomField());
}
/**
* Validates and stores a new custom field.
*
@ -92,33 +86,29 @@ class CustomFieldsController extends Controller
$this->authorize('create', CustomField::class);
$field = new CustomField([
"name" => $request->get("name"),
"element" => $request->get("element"),
"help_text" => $request->get("help_text"),
"field_values" => $request->get("field_values"),
"field_encrypted" => $request->get("field_encrypted", 0),
"show_in_email" => $request->get("show_in_email", 0),
"user_id" => Auth::id()
'name' => $request->get('name'),
'element' => $request->get('element'),
'help_text' => $request->get('help_text'),
'field_values' => $request->get('field_values'),
'field_encrypted' => $request->get('field_encrypted', 0),
'show_in_email' => $request->get('show_in_email', 0),
'user_id' => Auth::id(),
]);
if ($request->filled("custom_format")) {
$field->format = e($request->get("custom_format"));
if ($request->filled('custom_format')) {
$field->format = e($request->get('custom_format'));
} else {
$field->format = e($request->get("format"));
$field->format = e($request->get('format'));
}
if ($field->save()) {
return redirect()->route("fields.index")->with("success", trans('admin/custom_fields/message.field.create.success'));
return redirect()->route('fields.index')->with('success', trans('admin/custom_fields/message.field.create.success'));
}
return redirect()->back()->withInput()
->with('error', trans('admin/custom_fields/message.field.create.error'));
}
/**
* Detach a custom field from a fieldset.
*
@ -135,10 +125,10 @@ class CustomFieldsController extends Controller
if ($field->fieldset()->detach($fieldset_id)) {
return redirect()->route('fieldsets.show', ['fieldset' => $fieldset_id])
->with("success", trans('admin/custom_fields/message.field.delete.success'));
->with('success', trans('admin/custom_fields/message.field.delete.success'));
}
return redirect()->back()->withErrors(['message' => "Field is in-use"]);
return redirect()->back()->withErrors(['message' => 'Field is in-use']);
}
/**
@ -152,21 +142,20 @@ class CustomFieldsController extends Controller
public function destroy($field_id)
{
if ($field = CustomField::find($field_id)) {
$this->authorize('delete', $field);
if (($field->fieldset) && ($field->fieldset->count() > 0)) {
return redirect()->back()->withErrors(['message' => "Field is in-use"]);
return redirect()->back()->withErrors(['message' => 'Field is in-use']);
}
$field->delete();
return redirect()->route("fields.index")
->with("success", trans('admin/custom_fields/message.field.delete.success'));
return redirect()->route('fields.index')
->with('success', trans('admin/custom_fields/message.field.delete.success'));
}
return redirect()->back()->withErrors(['message' => "Field does not exist"]);
return redirect()->back()->withErrors(['message' => 'Field does not exist']);
}
/**
* Return a view to edit a custom field
*
@ -187,14 +176,13 @@ class CustomFieldsController extends Controller
$customFormat = $field->format;
}
return view("custom_fields.fields.edit",[
return view('custom_fields.fields.edit', [
'field' => $field,
'customFormat' => $customFormat,
'predefinedFormats' => Helper::predefined_formats()
'predefinedFormats' => Helper::predefined_formats(),
]);
}
/**
* Store the updated field
*
@ -212,26 +200,23 @@ class CustomFieldsController extends Controller
$this->authorize('update', $field);
$field->name = e($request->get("name"));
$field->element = e($request->get("element"));
$field->field_values = e($request->get("field_values"));
$field->name = e($request->get('name'));
$field->element = e($request->get('element'));
$field->field_values = e($request->get('field_values'));
$field->user_id = Auth::id();
$field->help_text = $request->get("help_text");
$field->show_in_email = $request->get("show_in_email", 0);
$field->help_text = $request->get('help_text');
$field->show_in_email = $request->get('show_in_email', 0);
if ($request->get('format') == 'CUSTOM REGEX') {
$field->format = e($request->get("custom_format"));
$field->format = e($request->get('custom_format'));
} else {
$field->format = e($request->get("format"));
$field->format = e($request->get('format'));
}
if ($field->save()) {
return redirect()->route("fields.index")->with("success", trans('admin/custom_fields/message.field.update.success'));
return redirect()->route('fields.index')->with('success', trans('admin/custom_fields/message.field.update.success'));
}
return redirect()->back()->withInput()->with('error', trans('admin/custom_fields/message.field.update.error'));
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Models\AssetModel;
@ -19,10 +20,8 @@ use Redirect;
* @version v2.0
* @author [Brady Wetherington] [<uberbrady@gmail.com>]
*/
class CustomFieldsetsController extends Controller
{
/**
* Validates and stores a new custom field.
*
@ -40,8 +39,7 @@ class CustomFieldsetsController extends Controller
$this->authorize('view', $cfset);
if ($cfset) {
$custom_fields_list = ["" => "Add New Field to Fieldset"] + CustomField::pluck("name", "id")->toArray();
$custom_fields_list = ['' => 'Add New Field to Fieldset'] + CustomField::pluck('name', 'id')->toArray();
$maxid = 0;
foreach ($cfset->fields as $field) {
@ -53,15 +51,13 @@ class CustomFieldsetsController extends Controller
}
}
return view("custom_fields.fieldsets.view")->with("custom_fieldset", $cfset)->with("maxid", $maxid+1)->with("custom_fields_list", $custom_fields_list);
return view('custom_fields.fieldsets.view')->with('custom_fieldset', $cfset)->with('maxid', $maxid + 1)->with('custom_fields_list', $custom_fields_list);
}
return redirect()->route("fields.index")
->with("error", trans('admin/custom_fields/message.fieldset.does_not_exist'));
return redirect()->route('fields.index')
->with('error', trans('admin/custom_fields/message.fieldset.does_not_exist'));
}
/**
* Returns a view with a form for creating a new custom fieldset.
*
@ -74,10 +70,9 @@ class CustomFieldsetsController extends Controller
{
$this->authorize('create', CustomFieldset::class);
return view("custom_fields.fieldsets.edit");
return view('custom_fields.fieldsets.edit');
}
/**
* Validates and stores a new custom fieldset.
*
@ -92,22 +87,21 @@ class CustomFieldsetsController extends Controller
$this->authorize('create', CustomFieldset::class);
$cfset = new CustomFieldset([
"name" => e($request->get("name")),
"user_id" => Auth::user()->id
'name' => e($request->get('name')),
'user_id' => Auth::user()->id,
]);
$validator = Validator::make($request->all(), $cfset->rules);
if ($validator->passes()) {
$cfset->save();
return redirect()->route("fieldsets.show", [$cfset->id])
return redirect()->route('fieldsets.show', [$cfset->id])
->with('success', trans('admin/custom_fields/message.fieldset.create.success'));
}
return redirect()->back()->withInput()->withErrors($validator);
}
/**
* What the actual fuck, Brady?
*
@ -122,7 +116,6 @@ class CustomFieldsetsController extends Controller
//
}
/**
* GET IN THE SEA BRADY.
*
@ -137,7 +130,6 @@ class CustomFieldsetsController extends Controller
//
}
/**
* Validates a custom fieldset and then deletes if it has no models associated.
*
@ -154,19 +146,18 @@ class CustomFieldsetsController extends Controller
$this->authorize('delete', $fieldset);
if ($fieldset) {
$models = AssetModel::where("fieldset_id", "=", $id);
$models = AssetModel::where('fieldset_id', '=', $id);
if ($models->count() == 0) {
$fieldset->delete();
return redirect()->route("fields.index")->with("success", trans('admin/custom_fields/message.fieldset.delete.success'));
}
return redirect()->route("fields.index")->with("error", trans('admin/custom_fields/message.fieldset.delete.in_use'));
return redirect()->route('fields.index')->with('success', trans('admin/custom_fields/message.fieldset.delete.success'));
}
return redirect()->route("fields.index")->with("error", trans('admin/custom_fields/message.fieldset.does_not_exist'));
return redirect()->route('fields.index')->with('error', trans('admin/custom_fields/message.fieldset.delete.in_use'));
}
return redirect()->route('fields.index')->with('error', trans('admin/custom_fields/message.fieldset.does_not_exist'));
}
/**
* Associate the custom field with a custom fieldset.
@ -177,7 +168,6 @@ class CustomFieldsetsController extends Controller
*/
public function associate(Request $request, $id)
{
$set = CustomFieldset::find($id);
$this->authorize('update', $set);
@ -185,17 +175,16 @@ class CustomFieldsetsController extends Controller
if ($request->filled('field_id')) {
foreach ($set->fields as $field) {
if ($field->id == $request->input('field_id')) {
return redirect()->route("fieldsets.show", [$id])->withInput()->withErrors(['field_id' => trans('admin/custom_fields/message.field.already_added')]);
return redirect()->route('fieldsets.show', [$id])->withInput()->withErrors(['field_id' => trans('admin/custom_fields/message.field.already_added')]);
}
}
$results = $set->fields()->attach($request->input('field_id'), ["required" => ($request->input('required') == "on"),"order" => $request->input('order', 1)]);
$results = $set->fields()->attach($request->input('field_id'), ['required' => ($request->input('required') == 'on'), 'order' => $request->input('order', 1)]);
return redirect()->route("fieldsets.show", [$id])->with("success", trans('admin/custom_fields/message.field.create.assoc_success'));
return redirect()->route('fieldsets.show', [$id])->with('success', trans('admin/custom_fields/message.field.create.assoc_success'));
}
return redirect()->route("fieldsets.show", [$id])->with("error", 'No field selected.');
return redirect()->route('fieldsets.show', [$id])->with('error', 'No field selected.');
}
/**
@ -206,7 +195,6 @@ class CustomFieldsetsController extends Controller
*/
public function makeFieldRequired($fieldset_id, $field_id)
{
$this->authorize('update', CustomFieldset::class);
$field = CustomField::findOrFail($field_id);
$fieldset = CustomFieldset::findOrFail($fieldset_id);
@ -214,8 +202,7 @@ class CustomFieldsetsController extends Controller
$fieldset->fields()->syncWithoutDetaching($fields);
return redirect()->route('fieldsets.show', ['fieldset' => $fieldset_id])
->with("success", trans('Field successfully set to required'));
->with('success', trans('Field successfully set to required'));
}
/**
@ -233,7 +220,6 @@ class CustomFieldsetsController extends Controller
$fieldset->fields()->syncWithoutDetaching($fields);
return redirect()->route('fieldsets.show', ['fieldset' => $fieldset_id])
->with("success", trans('Field successfully set to optional'));
->with('success', trans('Field successfully set to optional'));
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\AdminController;
@ -25,7 +26,6 @@ class DashboardController extends Controller
{
// Show the page
if (Auth::user()->hasAccess('admin')) {
$asset_stats = null;
$counts['asset'] = \App\Models\Asset::count();

View file

@ -34,10 +34,10 @@ class DepartmentsController extends Controller
if ($request->filled('company_id')) {
$company = Company::find($request->input('company_id'));
}
return view('departments/index')->with('company', $company);
}
/**
* Store a newly created resource in storage.
*
@ -58,8 +58,9 @@ class DepartmentsController extends Controller
$department = $request->handleImages($department);
if ($department->save()) {
return redirect()->route("departments.index")->with('success', trans('admin/departments/message.create.success'));
return redirect()->route('departments.index')->with('success', trans('admin/departments/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($department->getErrors());
}
@ -82,10 +83,10 @@ class DepartmentsController extends Controller
if (isset($department->id)) {
return view('departments/view', compact('department'));
}
return redirect()->route('departments.index')->with('error', trans('admin/departments/message.does_not_exist'));
}
/**
* Returns a form view used to create a new department.
*
@ -102,7 +103,6 @@ class DepartmentsController extends Controller
return view('departments/edit')->with('item', new Department);
}
/**
* Validates and deletes selected department.
*
@ -134,7 +134,6 @@ class DepartmentsController extends Controller
$department->delete();
return redirect()->back()->with('success', trans('admin/departments/message.delete.success'));
}
/**
@ -158,8 +157,8 @@ class DepartmentsController extends Controller
return view('departments/edit', compact('item'));
}
public function update(ImageUploadRequest $request, $id) {
public function update(ImageUploadRequest $request, $id)
{
if (is_null($department = Department::find($id))) {
return redirect()->route('departments.index')->with('error', trans('admin/departments/message.does_not_exist'));
}
@ -172,8 +171,9 @@ class DepartmentsController extends Controller
$department = $request->handleImages($department);
if ($department->save()) {
return redirect()->route("departments.index")->with('success', trans('admin/departments/message.update.success'));
return redirect()->route('departments.index')->with('success', trans('admin/departments/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($department->getErrors());
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Models\Depreciation;
@ -31,7 +32,6 @@ class DepreciationsController extends Controller
return view('depreciations/index');
}
/**
* Returns a view that displays a form to create a new depreciation.
*
@ -49,7 +49,6 @@ class DepreciationsController extends Controller
return view('depreciations/edit')->with('item', new Depreciation);
}
/**
* Validates and stores the new depreciation data.
*
@ -76,6 +75,7 @@ class DepreciationsController extends Controller
// Redirect to the new depreciation page
return redirect()->route('depreciations.index')->with('success', trans('admin/depreciations/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($depreciation->getErrors());
}
@ -102,7 +102,6 @@ class DepreciationsController extends Controller
return view('depreciations/edit', compact('item'));
}
/**
* Validates and stores the updated depreciation data.
*
@ -131,8 +130,9 @@ class DepreciationsController extends Controller
// Was the asset created?
if ($depreciation->save()) {
// Redirect to the depreciation page
return redirect()->route("depreciations.index")->with('success', trans('admin/depreciations/message.update.success'));
return redirect()->route('depreciations.index')->with('success', trans('admin/depreciations/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($depreciation->getErrors());
}
@ -143,7 +143,7 @@ class DepreciationsController extends Controller
*
* @author [A. Gianotto] [<snipe@snipe.net]
* @since [v1.0]
* @param integer $depreciationId
* @param int $depreciationId
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
@ -187,6 +187,4 @@ class DepreciationsController extends Controller
return view('depreciations/view', compact('depreciation'));
}
}

View file

@ -1,11 +1,11 @@
<?php
namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Models\Group;
use Illuminate\Http\Request;
/**
* This controller handles all actions related to User Groups for
* the Snipe-IT Asset Management application.
@ -65,8 +65,9 @@ class GroupsController extends Controller
$group->permissions = json_encode($request->input('permission'));
if ($group->save()) {
return redirect()->route("groups.index")->with('success', trans('admin/groups/message.success.create'));
return redirect()->route('groups.index')->with('success', trans('admin/groups/message.success.create'));
}
return redirect()->back()->withInput()->withErrors($group->getErrors());
}
@ -87,6 +88,7 @@ class GroupsController extends Controller
$permissions = config('permissions');
$groupPermissions = $group->decodePermissions();
$selected_array = Helper::selectedPermissionsArray($permissions, $groupPermissions);
return view('groups.edit', compact('group', 'permissions', 'selected_array', 'groupPermissions'));
}
@ -114,8 +116,10 @@ class GroupsController extends Controller
if ($group->save()) {
return redirect()->route('groups.index')->with('success', trans('admin/groups/message.success.update'));
}
return redirect()->back()->withInput()->withErrors($group->getErrors());
}
return redirect()->route('groups.index')->with('error', trans('general.feature_disabled'));
}
@ -139,6 +143,7 @@ class GroupsController extends Controller
// Redirect to the group management page
return redirect()->route('groups.index')->with('success', trans('admin/groups/message.success.delete'));
}
return redirect()->route('groups.index')->with('error', trans('general.feature_disabled'));
}
@ -161,5 +166,4 @@ class GroupsController extends Controller
return redirect()->route('groups.index')->with('error', trans('admin/groups/message.group_not_found', compact('id')));
}
}

View file

@ -1,9 +1,9 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
/**
* This controller provide the healthz route for
* the Snipe-IT Asset Management application.
@ -15,9 +15,10 @@ class HealthController extends BaseController
/**
* Returns a fixed JSON content ({ "status": "ok"}) which indicate the app is up and running
*/
public function get() {
public function get()
{
return response()->json([
"status" => "ok"
'status' => 'ok',
]);
}
}

View file

@ -16,6 +16,7 @@ class ImportsController extends Controller
{
$this->authorize('import');
$imports = (new ImportsTransformer)->transformImports(Import::latest()->get());
return view('importer/import')->with('imports', $imports);
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Kits;
use App\Http\Controllers\CheckInOutRequest;
@ -19,7 +20,6 @@ use Illuminate\Support\Arr;
*/
class CheckoutKitController extends Controller
{
public $kitService;
use CheckInOutRequest;
@ -39,6 +39,7 @@ class CheckoutKitController extends Controller
$this->authorize('checkout', Asset::class);
$kit = PredefinedKit::findOrFail($kit_id);
return view('kits/checkout')->with('kit', $kit);
}
@ -62,10 +63,10 @@ class CheckoutKitController extends Controller
if (Arr::has($checkout_result, 'errors') && count($checkout_result['errors']) > 0) {
return redirect()->back()->with('error', 'Checkout error')->with('error_messages', $checkout_result['errors']); // TODO: trans
}
return redirect()->back()->with('success', 'Checkout was successful')
->with('assets', Arr::get($checkout_result, 'assets', null))
->with('accessories', Arr::get($checkout_result, 'accessories', null))
->with('consumables', Arr::get($checkout_result, 'consumables', null)); // TODO: trans
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Kits;
use App\Http\Controllers\Controller;
@ -24,6 +25,7 @@ class PredefinedKitsController extends Controller
public function index()
{
$this->authorize('index', PredefinedKit::class);
return view('kits/index');
}
@ -37,6 +39,7 @@ class PredefinedKitsController extends Controller
public function create()
{
$this->authorize('create', PredefinedKit::class);
return view('kits/create')->with('item', new PredefinedKit);
}
@ -60,7 +63,8 @@ class PredefinedKitsController extends Controller
if (! $success) {
return redirect()->back()->withInput()->withErrors($kit->getErrors());
}
return redirect()->route("kits.index")->with('success', 'Kit was successfully created.'); // TODO: trans()
return redirect()->route('kits.index')->with('success', 'Kit was successfully created.'); // TODO: trans()
}
/**
@ -80,10 +84,10 @@ class PredefinedKitsController extends Controller
->with('models', $kit->models)
->with('licenses', $kit->licenses);
}
return redirect()->route('kits.index')->with('error', 'Kit does not exist'); // TODO: trans
}
/**
* Validates and processes form data from the edit
* Predefined Kit form based on the kit ID passed.
@ -105,8 +109,9 @@ class PredefinedKitsController extends Controller
$kit->name = $request->input('name');
if ($kit->save()) {
return redirect()->route("kits.index")->with('success', 'Kit was successfully updated'); // TODO: trans
return redirect()->route('kits.index')->with('success', 'Kit was successfully updated'); // TODO: trans
}
return redirect()->back()->withInput()->withErrors($kit->getErrors());
}
@ -152,7 +157,6 @@ class PredefinedKitsController extends Controller
return $this->edit($kit_id);
}
/**
* Returns a view containing the Predefined Kit edit form.
*
@ -165,13 +169,13 @@ class PredefinedKitsController extends Controller
$this->authorize('update', PredefinedKit::class);
if (($kit = PredefinedKit::find($kit_id))
&& ($model = $kit->models()->find($model_id))) {
return view('kits/model-edit', [
'kit' => $kit,
'model' => $model,
'item' => $model->pivot
'item' => $model->pivot,
]);
}
return redirect()->route('kits.index')->with('error', 'Kit does not exist'); // TODO: trans
}
@ -184,7 +188,6 @@ class PredefinedKitsController extends Controller
*/
public function updateModel(Request $request, $kit_id, $model_id)
{
$this->authorize('update', PredefinedKit::class);
if (is_null($kit = PredefinedKit::find($kit_id))) {
// Redirect to the kits management page
@ -249,7 +252,7 @@ class PredefinedKitsController extends Controller
return view('kits/license-edit', [
'kit' => $kit,
'license' => $license,
'item' => $license->pivot
'item' => $license->pivot,
]);
}
@ -263,7 +266,6 @@ class PredefinedKitsController extends Controller
*/
public function updateLicense(Request $request, $kit_id, $license_id)
{
$this->authorize('update', PredefinedKit::class);
if (is_null($kit = PredefinedKit::find($kit_id))) {
// Redirect to the kits management page
@ -308,7 +310,6 @@ class PredefinedKitsController extends Controller
return redirect()->route('kits.edit', $kit_id)->with('success', 'License was successfully detached'); // TODO: trans
}
/**
* Returns a view containing attached accessory edit form.
*
@ -330,7 +331,7 @@ class PredefinedKitsController extends Controller
return view('kits/accessory-edit', [
'kit' => $kit,
'accessory' => $accessory,
'item' => $accessory->pivot
'item' => $accessory->pivot,
]);
}
@ -344,7 +345,6 @@ class PredefinedKitsController extends Controller
*/
public function updateAccessory(Request $request, $kit_id, $accessory_id)
{
$this->authorize('update', PredefinedKit::class);
if (is_null($kit = PredefinedKit::find($kit_id))) {
// Redirect to the kits management page
@ -409,7 +409,7 @@ class PredefinedKitsController extends Controller
return view('kits/consumable-edit', [
'kit' => $kit,
'consumable' => $consumable,
'item' => $consumable->pivot
'item' => $consumable->pivot,
]);
}
@ -423,7 +423,6 @@ class PredefinedKitsController extends Controller
*/
public function updateConsumable(Request $request, $kit_id, $consumable_id)
{
$this->authorize('update', PredefinedKit::class);
if (is_null($kit = PredefinedKit::find($kit_id))) {
// Redirect to the kits management page

View file

@ -15,7 +15,6 @@ use Illuminate\Support\Facades\Validator;
class LicenseCheckinController extends Controller
{
/**
* Makes the form view to check a license seat back into inventory.
*
@ -35,10 +34,10 @@ class LicenseCheckinController extends Controller
}
$this->authorize('checkout', $license);
return view('licenses/checkin', compact('licenseSeat'))->with('backto', $backTo);
}
/**
* Validates and stores the license checkin action.
*
@ -64,6 +63,7 @@ class LicenseCheckinController extends Controller
if (! $license->reassignable) {
// Not allowed to checkin
Session::flash('error', 'License not reassignable.');
return redirect()->back()->withInput();
}
@ -88,17 +88,16 @@ class LicenseCheckinController extends Controller
// Was the asset updated?
if ($licenseSeat->save()) {
event(new CheckoutableCheckedIn($licenseSeat, $return_to, Auth::user(), $request->input('note')));
if ($backTo == 'user') {
return redirect()->route("users.show", $return_to->id)->with('success', trans('admin/licenses/message.checkin.success'));
return redirect()->route('users.show', $return_to->id)->with('success', trans('admin/licenses/message.checkin.success'));
}
return redirect()->route("licenses.show", $licenseSeat->license_id)->with('success', trans('admin/licenses/message.checkin.success'));
return redirect()->route('licenses.show', $licenseSeat->license_id)->with('success', trans('admin/licenses/message.checkin.success'));
}
// Redirect to the license page with error
return redirect()->route("licenses.index")->with('error', trans('admin/licenses/message.checkin.error'));
return redirect()->route('licenses.index')->with('error', trans('admin/licenses/message.checkin.error'));
}
}

View file

@ -37,10 +37,10 @@ class LicenseCheckoutController extends Controller
}
$this->authorize('checkout', $license);
return view('licenses/checkout', compact('license'));
}
/**
* Validates and stores the license checkout action.
*
@ -51,7 +51,6 @@ class LicenseCheckoutController extends Controller
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function store(LicenseCheckoutRequest $request, $licenseId, $seatId = null)
{
if (! $license = License::find($licenseId)) {
@ -65,10 +64,10 @@ class LicenseCheckoutController extends Controller
$checkoutMethod = 'checkoutTo'.ucwords(request('checkout_to_type'));
if ($this->$checkoutMethod($licenseSeat)) {
return redirect()->route("licenses.index")->with('success', trans('admin/licenses/message.checkout.success'));
return redirect()->route('licenses.index')->with('success', trans('admin/licenses/message.checkout.success'));
}
return redirect()->route("licenses.index")->with('error', trans('Something went wrong handling this checkout.'));
return redirect()->route('licenses.index')->with('error', trans('Something went wrong handling this checkout.'));
}
protected function findLicenseSeatToCheckout($license, $seatId)
@ -79,6 +78,7 @@ class LicenseCheckoutController extends Controller
if ($seatId) {
return redirect()->route('licenses.index')->with('error', 'This Seat is not available for checkout.');
}
return redirect()->route('licenses.index')->with('error', 'There are no available seats for this license');
}
@ -101,11 +101,11 @@ class LicenseCheckoutController extends Controller
$licenseSeat->assigned_to = $target->assigned_to;
}
if ($licenseSeat->save()) {
event(new CheckoutableCheckedOut($licenseSeat, $target, Auth::user(), request('note')));
return true;
}
return false;
}
@ -118,11 +118,11 @@ class LicenseCheckoutController extends Controller
$licenseSeat->assigned_to = request('assigned_to');
if ($licenseSeat->save()) {
event(new CheckoutableCheckedOut($licenseSeat, $target, Auth::user(), request('note')));
return true;
}
return false;
}
}

View file

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Licenses;
use App\Helpers\StorageHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\AssetFileRequest;
use App\Models\Actionlog;
@ -10,11 +11,9 @@ use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Helpers\StorageHelper;
class LicenseFilesController extends Controller
{
/**
* Validates and stores files associated with a license.
*
@ -34,16 +33,14 @@ class LicenseFilesController extends Controller
$this->authorize('update', $license);
if ($request->hasFile('file')) {
if (!Storage::exists('private_uploads/licenses')) Storage::makeDirectory('private_uploads/licenses', 775);
if (! Storage::exists('private_uploads/licenses')) {
Storage::makeDirectory('private_uploads/licenses', 775);
}
$upload_success = false;
foreach ($request->file('file') as $file) {
$file_name = 'license-'.$license->id.'-'.str_random(8).'-'.str_slug(basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension())).'.'.$file->getClientOriginalExtension();
$upload_success = $file->storeAs('private_uploads/licenses', $file_name);
// $upload_success = $file->storeAs('private_uploads/licenses/'.$file_name, $file);
@ -58,8 +55,10 @@ class LicenseFilesController extends Controller
if ($upload_success) {
return redirect()->route('licenses.show', $license->id)->with('success', trans('admin/licenses/message.upload.success'));
}
return redirect()->route('licenses.show', $license->id)->with('error', trans('admin/licenses/message.upload.error'));
}
return redirect()->route('licenses.show', $license->id)->with('error', trans('admin/licenses/message.upload.nofiles'));
}
// Prepare the error message
@ -67,7 +66,6 @@ class LicenseFilesController extends Controller
->with('error', trans('admin/licenses/message.does_not_exist'));
}
/**
* Deletes the selected license file.
*
@ -97,6 +95,7 @@ class LicenseFilesController extends Controller
}
$log->delete();
return redirect()->back()
->with('success', trans('admin/hardware/message.deletefile.success'));
}
@ -105,8 +104,6 @@ class LicenseFilesController extends Controller
return redirect()->route('licenses.index')->with('error', trans('admin/licenses/message.does_not_exist'));
}
/**
* Allows the selected file to be viewed.
*
@ -119,7 +116,6 @@ class LicenseFilesController extends Controller
*/
public function show($licenseId = null, $fileId = null, $download = true)
{
\Log::info('Private filesystem is: '.config('filesystems.default'));
$license = License::find($licenseId);
@ -134,10 +130,10 @@ class LicenseFilesController extends Controller
$file = 'private_uploads/licenses/'.$log->filename;
if (Storage::missing($file)) {
\Log::debug('NOT EXISTS for '.$file);
\Log::debug('NOT EXISTS URL should be '.Storage::url($file));
return response('File '.$file.' ('.Storage::url($file).') not found on server', 404)
->header('Content-Type', 'text/plain');
} else {
@ -152,20 +148,15 @@ class LicenseFilesController extends Controller
if ($contents = file_get_contents(Storage::url($file))) { // TODO - this will fail on private S3 files or large public ones
return Response::make(Storage::url($file)->header('Content-Type', mime_content_type($file)));
}
return JsonResponse::create(["error" => "Failed validation: "], 500);
return JsonResponse::create(['error' => 'Failed validation: '], 500);
}
return StorageHelper::downloader($file);
}
}
}
}
return redirect()->route('license.index')->with('error', trans('admin/licenses/message.does_not_exist', ['id' => $fileId]));
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers\Licenses;
use App\Helpers\Helper;
@ -17,7 +18,6 @@ use Illuminate\Support\Facades\DB;
*/
class LicensesController extends Controller
{
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the licenses listing, which is generated in getDatatable.
@ -31,10 +31,10 @@ class LicensesController extends Controller
public function index()
{
$this->authorize('view', License::class);
return view('licenses/index');
}
/**
* Returns a form view that allows an admin to create a new licence.
*
@ -50,17 +50,15 @@ class LicensesController extends Controller
$maintained_list = [
'' => 'Maintained',
'1' => 'Yes',
'0' => 'No'
'0' => 'No',
];
return view('licenses/edit')
->with('depreciation_list', Helper::depreciationList())
->with('maintained_list', $maintained_list)
->with('item', new License);
}
/**
* Validates and stores the license form data submitted from the new
* license form.
@ -101,8 +99,9 @@ class LicensesController extends Controller
$license->user_id = Auth::id();
if ($license->save()) {
return redirect()->route("licenses.index")->with('success', trans('admin/licenses/message.create.success'));
return redirect()->route('licenses.index')->with('success', trans('admin/licenses/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($license->getErrors());
}
@ -127,7 +126,7 @@ class LicensesController extends Controller
$maintained_list = [
'' => 'Maintained',
'1' => 'Yes',
'0' => 'No'
'0' => 'No',
];
return view('licenses/edit', compact('item'))
@ -135,7 +134,6 @@ class LicensesController extends Controller
->with('maintained_list', $maintained_list);
}
/**
* Validates and stores the license form data submitted from the edit
* license form.
@ -207,7 +205,7 @@ class LicensesController extends Controller
// Delete the license and the associated license seats
DB::table('license_seats')
->where('id', $license->id)
->update(array('assigned_to' => null,'asset_id' => null));
->update(['assigned_to' => null, 'asset_id' => null]);
$licenseSeats = $license->licenseseats();
$licenseSeats->delete();
@ -219,10 +217,8 @@ class LicensesController extends Controller
}
// There are still licenses in use.
return redirect()->route('licenses.index')->with('error', trans('admin/licenses/message.assoc_users'));
}
/**
* Makes the license detail page.
*
@ -234,18 +230,18 @@ class LicensesController extends Controller
*/
public function show($licenseId = null)
{
$license = License::with('assignedusers', 'licenseSeats.user', 'licenseSeats.asset')->find($licenseId);
if ($license) {
$this->authorize('view', $license);
return view('licenses/view', compact('license'));
}
return redirect()->route('licenses.index')
->with('error', trans('admin/licenses/message.does_not_exist'));
}
public function getClone($licenseId = null)
{
if (is_null($license_to_clone = License::find($licenseId))) {
@ -257,7 +253,7 @@ class LicensesController extends Controller
$maintained_list = [
'' => 'Maintained',
'1' => 'Yes',
'0' => 'No'
'0' => 'No',
];
//clone the orig
$license = clone $license_to_clone;

View file

@ -1,12 +1,12 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ImageUploadRequest;
use App\Models\Asset;
use App\Models\Location;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Models\Asset;
use Illuminate\Support\Facades\Storage;
/**
@ -17,7 +17,6 @@ use Illuminate\Support\Facades\Storage;
*/
class LocationsController extends Controller
{
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the locations listing, which is generated in getDatatable.
@ -36,7 +35,6 @@ class LocationsController extends Controller
return view('locations/index');
}
/**
* Returns a form view used to create a new location.
*
@ -49,11 +47,11 @@ class LocationsController extends Controller
public function create()
{
$this->authorize('create', Location::class);
return view('locations/edit')
->with('item', new Location);
}
/**
* Validates and stores a new location.
*
@ -85,11 +83,11 @@ class LocationsController extends Controller
$location = $request->handleImages($location);
if ($location->save()) {
return redirect()->route("locations.index")->with('success', trans('admin/locations/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($location->getErrors());
return redirect()->route('locations.index')->with('success', trans('admin/locations/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($location->getErrors());
}
/**
* Makes a form view to edit location information.
@ -109,11 +107,9 @@ class LocationsController extends Controller
return redirect()->route('locations.index')->with('error', trans('admin/locations/message.does_not_exist'));
}
return view('locations/edit', compact('item'));
}
/**
* Validates and stores updated location data from edit form.
*
@ -148,10 +144,10 @@ class LocationsController extends Controller
$location = $request->handleImages($location);
if ($location->save()) {
return redirect()->route("locations.index")->with('success', trans('admin/locations/message.update.success'));
return redirect()->route('locations.index')->with('success', trans('admin/locations/message.update.success'));
}
return redirect()->back()->withInput()->withInput()->withErrors($location->getErrors());
}
@ -189,10 +185,10 @@ class LocationsController extends Controller
}
}
$location->delete();
return redirect()->to(route('locations.index'))->with('success', trans('admin/locations/message.delete.success'));
}
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the locations detail page.
@ -215,26 +211,23 @@ class LocationsController extends Controller
public function print_assigned($id)
{
$location = Location::where('id', $id)->first();
$parent = Location::where('id', $location->parent_id)->first();
$manager = User::where('id', $location->manager_id)->first();
$users = User::where('location_id', $id)->with('company', 'department', 'location')->get();
$assets = Asset::where('assigned_to', $id)->where('assigned_type', Location::class)->with('model', 'model.category')->get();
return view('locations/print')->with('assets', $assets)->with('users',$users)->with('location', $location)->with('parent', $parent)->with('manager', $manager);
return view('locations/print')->with('assets', $assets)->with('users', $users)->with('location', $location)->with('parent', $parent)->with('manager', $manager);
}
public function print_all_assigned($id)
{
$location = Location::where('id', $id)->first();
$parent = Location::where('id', $location->parent_id)->first();
$manager = User::where('id', $location->manager_id)->first();
$users = User::where('location_id', $id)->with('company', 'department', 'location')->get();
$assets = Asset::where('location_id', $id)->with('model', 'model.category')->get();
return view('locations/print')->with('assets', $assets)->with('users', $users)->with('location', $location)->with('parent', $parent)->with('manager', $manager);
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ImageUploadRequest;
@ -29,10 +30,10 @@ class ManufacturersController extends Controller
public function index()
{
$this->authorize('index', Manufacturer::class);
return view('manufacturers/index');
}
/**
* Returns a view that displays a form to create a new manufacturer.
*
@ -45,10 +46,10 @@ class ManufacturersController extends Controller
public function create()
{
$this->authorize('create', Manufacturer::class);
return view('manufacturers/edit')->with('item', new Manufacturer);
}
/**
* Validates and stores the data for a new manufacturer.
*
@ -61,7 +62,6 @@ class ManufacturersController extends Controller
*/
public function store(ImageUploadRequest $request)
{
$this->authorize('create', Manufacturer::class);
$manufacturer = new Manufacturer;
$manufacturer->name = $request->input('name');
@ -72,11 +72,10 @@ class ManufacturersController extends Controller
$manufacturer->support_email = $request->input('support_email');
$manufacturer = $request->handleImages($manufacturer);
if ($manufacturer->save()) {
return redirect()->route('manufacturers.index')->with('success', trans('admin/manufacturers/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($manufacturer->getErrors());
}
@ -104,7 +103,6 @@ class ManufacturersController extends Controller
return view('manufacturers/edit', compact('item'));
}
/**
* Validates and stores the updated manufacturer data.
*
@ -139,10 +137,10 @@ class ManufacturersController extends Controller
$manufacturer = $request->handleImages($manufacturer);
if ($manufacturer->save()) {
return redirect()->route('manufacturers.index')->with('success', trans('admin/manufacturers/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($manufacturer->getErrors());
}
@ -175,7 +173,7 @@ class ManufacturersController extends Controller
}
// Soft delete the manufacturer if active, permanent delete if is already deleted
if($manufacturer->deleted_at === NULL) {
if ($manufacturer->deleted_at === null) {
$manufacturer->delete();
} else {
$manufacturer->forceDelete();
@ -230,9 +228,10 @@ class ManufacturersController extends Controller
if ($manufacturer->restore()) {
return redirect()->route('manufacturers.index')->with('success', trans('admin/manufacturers/message.restore.success'));
}
return redirect()->back()->with('error', 'Could not restore.');
}
return redirect()->back()->with('error', trans('admin/manufacturers/message.does_not_exist'));
return redirect()->back()->with('error', trans('admin/manufacturers/message.does_not_exist'));
}
}

Some files were not shown because too many files have changed in this diff Show more