opensupports/server/libs/FileUploader.php

96 lines
2.8 KiB
PHP
Raw Normal View History

<?php
class FileUploader extends FileManager {
2018-11-19 14:27:42 +01:00
use SingletonTrait;
2018-09-20 20:52:27 +02:00
private $maxSize = 1;
private $fileName;
private $permission;
2018-10-06 03:23:19 +02:00
private $storage;
2018-11-19 14:27:42 +01:00
private function __construct() {
2018-10-06 03:23:19 +02:00
$this->storage = new \Upload\Storage\FileSystem($this->getLocalPath());
}
2018-09-20 20:52:27 +02:00
public function isSizeValid($file) {
return $file['size'] <= (1048576 * $this->maxSize);
}
2018-10-06 03:23:19 +02:00
public function upload($fileKey) {
$file = new \Upload\File($fileKey, $this->storage);
$file->setName($this->generateFileName($_FILES[$fileKey]['name']));
$file->addValidations(array(
new \Upload\Validation\Mimetype([
'image/png',
'image/gif',
2018-10-06 03:23:19 +02:00
'image/jpeg',
'image/bmp',
'image/tiff',
'application/gzip',
'application/x-gzip',
'application/zip',
'application/x-rar-compressed',
'application/x-7z-compressed',
'application/x-tar',
'application/x-bzip',
'application/x-bzip2',
'text/csv',
'text/rtf',
'application/msword',
'application/vnd.ms-excel',
'text/plain',
'application/pdf'
]),
new \Upload\Validation\Size($this->maxSize.'M')
));
try {
$file->upload();
$this->setFileName($file->getNameWithExtension());
return true;
} catch (\Exception $e) {
return false;
}
}
2018-10-06 03:23:19 +02:00
private function generateFileName($fileName) {
$newName = $this->removeFileExtension($fileName);
$newName = strtolower($newName);
2017-06-20 21:47:27 +02:00
$newName = preg_replace('/[^a-zA-Z0-9\d\.\-]/', '_', $newName);
2018-10-06 03:23:19 +02:00
$result = "";
2018-11-16 19:12:15 +01:00
if($this->permission) $result = $this->permission . '_';
else $result = '';
2018-11-16 19:12:15 +01:00
$result .= substr(Hashing::generateRandomToken(), 0, 6) . '_' . $newName;
2018-10-06 03:23:19 +02:00
return $result;
}
public function removeFileExtension($fileName) {
return substr($fileName, 0, strrpos($fileName, "."));
}
public function setPermission($type = '', $extra = '') {
if($type === FileManager::PERMISSION_ARTICLE) $this->permission = 'a';
else if($type === FileManager::PERMISSION_TICKET) $this->permission = 't' . $extra;
else if($type === FileManager::PERMISSION_PROFILE) $this->permission = 'p';
else $this->permission = '';
}
public function setMaxSize($maxSize) {
$this->maxSize = $maxSize;
}
2018-10-06 03:23:19 +02:00
public function setFileName($fileName) {
$this->fileName = $fileName;
}
public function getFileName() {
return $this->fileName;
}
}