80 lines
2.2 KiB
PHP
80 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use CodeIgniter\HTTP\ResponseInterface;
|
|
|
|
class FileUpload extends BaseController
|
|
{
|
|
private string $storagename = '';
|
|
|
|
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
|
|
{
|
|
parent::initController($request, $response, $logger);
|
|
|
|
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
|
|
die('NO ACCESS');
|
|
}
|
|
}
|
|
|
|
public function upload(int $foreignID): ResponseInterface
|
|
{
|
|
$validationRule = [
|
|
'userfile' => [
|
|
'label' => 'File',
|
|
'rules' => 'uploaded[userfile]'
|
|
]
|
|
];
|
|
|
|
if (!$this->validate($validationRule)) {
|
|
return $this->json(['error' => $this->validator->getErrors()]);
|
|
}
|
|
|
|
$file = $this->request->getFile('userfile');
|
|
|
|
if (!$file->isValid()) {
|
|
return $this->json(['error' => $file->getErrorString()]);
|
|
}
|
|
|
|
// Move to temp directory first
|
|
$tempPath = ROOTPATH . 'documents/temp';
|
|
$originalName = $file->getName();
|
|
$file->move($tempPath, $originalName);
|
|
|
|
$this->setStoragename();
|
|
|
|
$uploadData = [
|
|
'file_name' => $originalName,
|
|
'full_path' => $tempPath . '/' . $originalName
|
|
];
|
|
|
|
$this->persistDocument($uploadData, $foreignID);
|
|
$this->renameDocument($uploadData['full_path']);
|
|
|
|
return $this->json(['success' => true, 'storagename' => $this->storagename]);
|
|
}
|
|
|
|
private function setStoragename(): void
|
|
{
|
|
$this->storagename = sha1(bin2hex(random_bytes(16)));
|
|
}
|
|
|
|
private function persistDocument(array $data, int $foreignID): void
|
|
{
|
|
$file = [
|
|
'storagename' => $this->storagename,
|
|
'originalname' => $data['file_name'],
|
|
'user_id' => USERID,
|
|
'uploaddate' => date('Y-m-d H:i:s'),
|
|
'foreign_id' => $foreignID
|
|
];
|
|
|
|
\Document::create($file);
|
|
}
|
|
|
|
private function renameDocument(string $original): void
|
|
{
|
|
rename($original, ROOTPATH . 'documents/' . $this->storagename);
|
|
}
|
|
}
|