edms2023/app/SharedFile.php

121 lines
3.1 KiB
PHP

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SharedFile extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
public function saveWithoutEvents(array $options=[])
{
return static::withoutEvents(function() use ($options) {
return $this->save($options);
});
}
protected $table = 'shared_files';
protected $fillable = [
'file_type', 'file_id', 'parent_id', 'user_id', 'department_id', 'permission', 'shared_by', 'path_to_root',
];
public function sharedby()
{
return $this->belongsTo(User::class, 'shared_by', 'id');
}
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function department()
{
return $this->belongsTo(Department::class, 'department_id', 'id');
}
public function getSharedName()
{
if($this->user_id)
return $this->user->getFullName();
else if($this->department_id)
return dataTranslation($this->department->name);
return '';
}
public function file()
{
return $this->belongsTo(MyFile::class, 'file_id', 'id');
}
public function getSharedFileName()
{
if($this->file_type == 1)
return $this->file->name_org;
else
return $this->file->name;
}
public function getPermissionAttribute($attribute)
{
$v = $this->getPermissionOptions()[$attribute];
return $v;
}
public static function validShare($file_id, $id, $usertype, $permission)
{
$auth_user = auth()->user()->id ?? 3;
$dept_user = auth()->user()->department_id ?? 2;
$file = MyFile::find($file_id);
if(($file->user_id != $auth_user) || ($file->is_temp == 1))
return false;
$path_array = preg_split('/;/', $file->path_to_root, -1, PREG_SPLIT_NO_EMPTY);
$path_array = array_merge($path_array, [$file->id]);
if($usertype == 'department')
{
$departments = SharedFile::where('department_id', $id)->whereIn('file_id', $path_array)->where('permission', '>=', $permission)->get();
if(count($departments) == 0)
return true;
}
else if($usertype == 'user')
{
$users = SharedFile::whereIn('file_id', $path_array)
->where('permission', '>=', $permission)
->where(function($q) use($id, $dept_user){
$q->orWhere('user_id', $id)
->orWhere('department_id', $dept_user);
})->get();
if(count($users) == 0)
return true;
}
return false;
}
public static function deleteRelatedShares(MyFile $f)
{
SharedFile::where('path_to_root', 'LIKE', '%;'.$f->id.';%')->delete();
SharedFile::where('file_id', $f->id)->delete();
}
public function getPermissionOptions()
{
return [
1 => 'Read',
2 => 'Write',
// 3 => 'Read And Write',
];
}
}