1
0
mirror of https://github.com/nokonoko/Uguu.git synced 2024-01-06 13:35:15 +00:00
This commit is contained in:
Go Johansson (neku) 2023-02-18 15:22:37 +01:00
parent 4246dedebe
commit 5205351911
16 changed files with 689 additions and 767 deletions

View File

@ -30,7 +30,7 @@ See the real world site at [uguu.se](https://uguu.se).
## Requirements ## Requirements
Tested and working with Nginx + PHP-8.1 + SQLite/MySQL. Tested and working with Nginx + PHP-8.1 + SQLite/MySQL/PostgreSQL.
Node is used to compile Uguu, after that it runs on PHP. Node is used to compile Uguu, after that it runs on PHP.
@ -57,7 +57,6 @@ tests.
## Upcoming Features ## Upcoming Features
* PostgreSQL Support
* S3 Bucket Support * S3 Bucket Support
* Azure File Storage Support * Azure File Storage Support
* Temporal/RR Support * Temporal/RR Support

View File

@ -12,7 +12,7 @@ RUN chmod a+x nodejssetup.sh
RUN ./nodejssetup.sh RUN ./nodejssetup.sh
RUN apt-get install -y nodejs gcc g++ make RUN apt-get install -y nodejs gcc g++ make
RUN apt-get install -y build-essential nginx-full php8.1-fpm php8.1 sqlite3 php8.1-sqlite3 \ RUN apt-get install -y build-essential nginx-full php8.1-fpm php8.1 sqlite3 php8.1-sqlite3 \
php8.1-curl php8.1-cli php8.1-lz4 \ php8.1-curl php8.1-cli php8.1-lz4 php8.1-pgsql \
php8.1-mcrypt php8.1-mysql php8.1-xdebug php8.1-zip \ php8.1-mcrypt php8.1-mysql php8.1-xdebug php8.1-zip \
php8.1-common php8.1-readline php8.1-bcmath php8.1-common php8.1-xml php8.1-common php8.1-readline php8.1-bcmath php8.1-common php8.1-xml

View File

@ -4,7 +4,7 @@ pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf; include /etc/nginx/modules-enabled/*.conf;
events { events {
worker_connections 1024; worker_connections 4096;
multi_accept on; multi_accept on;
} }

View File

@ -3,8 +3,8 @@ server {
server_name XMAINDOMAINX; server_name XMAINDOMAINX;
ssl on; ssl on;
ssl_certificate /root/.acme.sh/XMAINDOMAINX/fullchain.cer; ssl_certificate /root/.acme.sh/XMAINDOMAINX_ecc/fullchain.cer;
ssl_certificate_key /root/.acme.sh/XMAINDOMAINX/XMAINDOMAINX.key; ssl_certificate_key /root/.acme.sh/XMAINDOMAINX_ecc/XMAINDOMAINX.key;
ssl_protocols TLSv1.2 TLSv1.3; ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
ssl_ecdh_curve secp384r1; ssl_ecdh_curve secp384r1;
@ -39,8 +39,8 @@ server {
server_name XFILESDOMAINX; server_name XFILESDOMAINX;
ssl on; ssl on;
ssl_certificate /root/.acme.sh/XMAINDOMAINX/fullchain.cer; ssl_certificate /root/.acme.sh/XMAINDOMAINX_ecc/fullchain.cer;
ssl_certificate_key /root/.acme.sh/XMAINDOMAINX/XMAINDOMAINX.key; ssl_certificate_key /root/.acme.sh/XMAINDOMAINX_ecc/XMAINDOMAINX.key;
ssl_protocols TLSv1.2 TLSv1.3; ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
ssl_ecdh_curve secp384r1; ssl_ecdh_curve secp384r1;

View File

@ -427,7 +427,7 @@ max_input_time = 60
; Maximum amount of memory a script may consume ; Maximum amount of memory a script may consume
; http://php.net/memory-limit ; http://php.net/memory-limit
memory_limit = 128M memory_limit = 256M
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ; ; Error handling and logging ;
@ -700,7 +700,7 @@ auto_globals_jit = On
; Its value may be 0 to disable the limit. It is ignored if POST data reading ; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading. ; is disabled through enable_post_data_reading.
; http://php.net/post-max-size ; http://php.net/post-max-size
post_max_size = 128M post_max_size = 256M
; Automatically add files before PHP document. ; Automatically add files before PHP document.
; http://php.net/auto-prepend-file ; http://php.net/auto-prepend-file
@ -852,10 +852,10 @@ file_uploads = On
; Maximum allowed size for uploaded files. ; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize ; http://php.net/upload-max-filesize
upload_max_filesize = 128M upload_max_filesize = 256M
; Maximum number of files that can be uploaded via a single request ; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20 max_file_uploads = 100
;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;
; Fopen wrappers ; ; Fopen wrappers ;

View File

@ -1,6 +1,6 @@
{ {
"name": "uguu", "name": "uguu",
"version": "1.6.7", "version": "1.7.0",
"description": "Uguu is a simple lightweight temporary file host with support for drop, paste, click and API uploading.", "description": "Uguu is a simple lightweight temporary file host with support for drop, paste, click and API uploading.",
"homepage": "https://uguu.se", "homepage": "https://uguu.se",
"repository": { "repository": {

View File

@ -2,7 +2,7 @@
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -20,52 +20,58 @@
namespace Pomf\Uguu\Classes; namespace Pomf\Uguu\Classes;
use Exception;
use PDO; use PDO;
class Connector extends Database class Connector extends Database
{ {
public PDO $DB; public PDO $DB;
public string $dbType;
public array $CONFIG; public array $CONFIG;
public Response $response;
public function errorHandler(int $errno, string $errstr):void
{
if ($this->CONFIG['DEBUG']) {
$this->response->error(500, 'Server error: ' . $errstr);
} else {
$this->response->error(500, 'Server error.');
}
}
public function fatalErrorHandler():void
{
if (!is_null($e = error_get_last())) {
if ($this->CONFIG['DEBUG']) {
$this->response->error(500, 'FATAL Server error: ' . print_r($e, true));
} else {
$this->response->error(500, 'Server error.');
}
}
}
/** /**
* Reads the config.json file and populates the CONFIG property with the settings * Reads the config.json file and populates the CONFIG property with the settings
* Also assembles the PDO DB connection and registers error handlers.
* *
* @throws \Exception
*/ */
public function __construct() public function __construct()
{ {
$this->response = new Response('json');
if (!file_exists(__DIR__ . '/../config.json')) { if (!file_exists(__DIR__ . '/../config.json')) {
throw new Exception('Cant read settings file.', 500); $this->response->error(500, 'Cant read settings file.');
} }
try {
$this->CONFIG = json_decode( $this->CONFIG = json_decode(
file_get_contents(__DIR__ . '/../config.json'), file_get_contents(__DIR__ . '/../config.json'),
true, true,
); );
$this->assemble(); ini_set('display_errors', 0);
} set_error_handler([$this, "errorHandler"]);
catch (Exception $e) { register_shutdown_function([$this, "fatalErrorHandler"]);
throw new Exception($e->getMessage(), 500); $this->dbType = $this->CONFIG['DB_MODE'];
}
}
/**
* > Tries to connect to the database
*
* @throws \Exception
*/
public function assemble()
{
try {
$this->DB = new PDO( $this->DB = new PDO(
$this->CONFIG['DB_MODE'] . ':' . $this->CONFIG['DB_PATH'], $this->CONFIG['DB_MODE'] . ':' . $this->CONFIG['DB_PATH'],
$this->CONFIG['DB_USER'], $this->CONFIG['DB_USER'],
$this->CONFIG['DB_PASS'] $this->CONFIG['DB_PASS']
); );
} }
catch (Exception) {
throw new Exception('Cant connect to DB.', 500);
}
}
} }

View File

@ -2,7 +2,7 @@
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View File

@ -1,9 +1,8 @@
<?php <?php
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,142 +20,88 @@
namespace Pomf\Uguu\Classes; namespace Pomf\Uguu\Classes;
use DateTimeZone;
use Exception;
use PDO; use PDO;
use DateTime;
class Database class Database
{ {
private PDO $DB;
/**
* Sets the value of the DB variable.
*
* @param $DB PDO The database connection.
*/
public function setDB(PDO $DB): void
{
$this->DB = $DB;
}
/**
* Checks if a file name exists in the database
*
* @param $name string The name of the file.
*
* @return bool The number of rows that match the query.
* @throws \Exception
*/
public function dbCheckNameExists(string $name):bool public function dbCheckNameExists(string $name):bool
{ {
try { $query = match ($this->dbType) {
$q = $this->DB->prepare('SELECT * FROM files WHERE EXISTS 'pgsql' => 'SELECT EXISTS(SELECT id FROM files WHERE filename = (:name)), filename FROM files WHERE filename = (:name) LIMIT 1',
(SELECT filename FROM files WHERE filename = (:name)) LIMIT 1'); default => 'SELECT filename FROM files WHERE filename = (:name) AND EXISTS (SELECT id FROM files WHERE filename = (:name)) LIMIT 1'
};
$q = $this->DB->prepare($query);
$q->bindValue(':name', $name); $q->bindValue(':name', $name);
$q->execute(); $q->execute();
$result = $q->fetch(); $result = $q->fetch();
if ($result) { $q->closeCursor();
if (isset($result['exists']) and $result['exists']) {
return true;
} elseif ($result) {
return true; return true;
} }
return false; return false;
} catch (Exception) {
throw new Exception('Cant check if name exists in DB.', 500);
}
} }
/** public function checkFileBlacklist(string $hash):void
* Checks if the file is blacklisted
*
* @param $FILE_INFO array An array containing the following:
*
* @throws \Exception
*/
public function checkFileBlacklist(array $FILE_INFO): void
{ {
try { $query = match ($this->dbType) {
$q = $this->DB->prepare('SELECT * FROM blacklist WHERE EXISTS 'pgsql' => 'SELECT EXISTS(SELECT id FROM blacklist WHERE hash = (:hash)), hash FROM blacklist WHERE hash = (:hash) LIMIT 1',
(SELECT hash FROM blacklist WHERE hash = (:hash)) LIMIT 1'); default => 'SELECT id FROM blacklist WHERE EXISTS(SELECT id FROM blacklist WHERE hash = (:hash)) LIMIT 1'
$q->bindValue(':hash', $FILE_INFO['SHA1']); };
$q->execute(); $q = $this->DB->prepare($query);
$result = $q->fetch();
if ($result) {
throw new Exception('File blacklisted!', 415);
}
} catch (Exception) {
throw new Exception('Cant check blacklist DB.', 500);
}
}
/**
* Checks if the file already exists in the database
*
* @param $hash string The hash of the file you want to check for.
*
* @throws \Exception
*/
public function antiDupe(string $hash): array
{
try {
$q = $this->DB->prepare(
'SELECT * FROM files WHERE EXISTS
(SELECT filename FROM files WHERE hash = (:hash)) LIMIT 1',
);
$q->bindValue(':hash', $hash); $q->bindValue(':hash', $hash);
$q->execute(); $q->execute();
$result = $q->fetch(); $result = $q->fetch();
if ($result) { $q->closeCursor();
if (isset($result['exists']) and $result['exists']) {
$this->response->error(415, 'File blacklisted.');
} elseif ($result) {
$this->response->error(415, 'File blacklisted.');
}
}
public function antiDupe(string $hash):array
{
$query = match ($this->dbType) {
'pgsql' => 'SELECT EXISTS(SELECT id FROM files WHERE hash = (:hash)), filename FROM files WHERE hash = (:hash) LIMIT 1',
default => 'SELECT filename FROM files WHERE hash = (:hash) AND EXISTS (SELECT id FROM files WHERE hash = (:hash)) LIMIT 1'
};
$q = $this->DB->prepare($query);
$q->bindValue(':hash', $hash);
$q->execute();
$result = $q->fetch();
$q->closeCursor();
if (!$result) {
return [
'result' => false,
];
} else {
return [ return [
'result' => true, 'result' => true,
'name' => $result['filename'], 'name' => $result['filename'],
]; ];
} else {
return [
'result' => false
];
}
} catch (Exception) {
throw new Exception('Cant check for dupes in DB.', 500);
} }
} }
/**
* Inserts a new file into the database
*
* @param $FILE_INFO array
* @param $fingerPrintInfo array
*
* @throws \Exception
*/
public function newIntoDB(array $FILE_INFO, array $fingerPrintInfo):void public function newIntoDB(array $FILE_INFO, array $fingerPrintInfo):void
{ {
try {
$q = $this->DB->prepare( $q = $this->DB->prepare(
'INSERT INTO files (hash, originalname, filename, size, date, ip)' . 'INSERT INTO files (hash, originalname, filename, size, date, ip)' .
'VALUES (:hash, :orig, :name, :size, :date, :ip)', 'VALUES (:hash, :orig, :name, :size, :date, :ip)',
); );
$q->bindValue(':hash', $FILE_INFO['SHA1']); $q->bindValue(':hash', $FILE_INFO['SHA1']);
$q->bindValue(':orig', $FILE_INFO['NAME']); $q->bindValue(':orig', $FILE_INFO['NAME']);
$q->bindValue(':name', $FILE_INFO['NEW_NAME']); $q->bindValue(':name', $FILE_INFO['FILENAME']);
$q->bindValue(':size', $FILE_INFO['SIZE'], PDO::PARAM_INT); $q->bindValue(':size', $FILE_INFO['SIZE'], PDO::PARAM_INT);
$q->bindValue(':date', $fingerPrintInfo['timestamp']); $q->bindValue(':date', $fingerPrintInfo['timestamp']);
$q->bindValue(':ip', $fingerPrintInfo['ip']); $q->bindValue(':ip', $fingerPrintInfo['ip']);
$q->execute(); $q->execute();
} catch (Exception) { $q->closeCursor();
throw new Exception('Cant insert into DB.', 500);
}
} }
/**
* Creates a new row in the database with the information provided
*
* @param $fingerPrintInfo array
*
* @throws \Exception
*/
public function createRateLimit(array $fingerPrintInfo):void public function createRateLimit(array $fingerPrintInfo):void
{ {
try {
$q = $this->DB->prepare( $q = $this->DB->prepare(
'INSERT INTO ratelimit (iphash, files, time)' . 'INSERT INTO ratelimit (iphash, files, time)' .
'VALUES (:iphash, :files, :time)', 'VALUES (:iphash, :files, :time)',
@ -165,23 +110,11 @@ class Database
$q->bindValue(':files', $fingerPrintInfo['files_amount']); $q->bindValue(':files', $fingerPrintInfo['files_amount']);
$q->bindValue(':time', $fingerPrintInfo['timestamp']); $q->bindValue(':time', $fingerPrintInfo['timestamp']);
$q->execute(); $q->execute();
} catch (Exception $e) { $q->closeCursor();
throw new Exception(500, $e->getMessage());
}
} }
/**
* Update the rate limit table with the new file count and timestamp
*
* @param $fCount int The number of files uploaded by the user.
* @param $iStamp bool A boolean value that determines whether or not to update the timestamp.
* @param $fingerPrintInfo array An array containing the following keys:
*
* @throws \Exception
*/
public function updateRateLimit(int $fCount, bool $iStamp, array $fingerPrintInfo):void public function updateRateLimit(int $fCount, bool $iStamp, array $fingerPrintInfo):void
{ {
try {
if ($iStamp) { if ($iStamp) {
$q = $this->DB->prepare( $q = $this->DB->prepare(
'UPDATE ratelimit SET files = (:files), time = (:time) WHERE iphash = (:iphash)', 'UPDATE ratelimit SET files = (:files), time = (:time) WHERE iphash = (:iphash)',
@ -195,68 +128,48 @@ class Database
$q->bindValue(':files', $fCount); $q->bindValue(':files', $fCount);
$q->bindValue(':iphash', $fingerPrintInfo['ip_hash']); $q->bindValue(':iphash', $fingerPrintInfo['ip_hash']);
$q->execute(); $q->execute();
} catch (Exception $e) { $q->closeCursor();
throw new Exception(500, $e->getMessage());
}
} }
/**
* @throws \Exception
*/
public function compareTime(int $timestamp, int $seconds_d):bool public function compareTime(int $timestamp, int $seconds_d):bool
{ {
$dateTime_end = new DateTime('now', new DateTimeZone('Europe/Stockholm')); $diff = time() - $timestamp;
$dateTime_start = new DateTime();
$dateTime_start->setTimestamp($timestamp);
$diff = strtotime($dateTime_end->format('Y-m-d H:i:s')) - strtotime($dateTime_start->format('Y-m-d H:i:s'));
if ($diff > $seconds_d) { if ($diff > $seconds_d) {
return true; return true;
} }
return false; return false;
} }
/**
* Checks if the user has uploaded more than 100 files in the last minute, if so it returns true,
* if not it updates the database with the new file
* count and timestamp
*
* @param $fingerPrintInfo array An array containing the following:
*
* @return bool A boolean value.
* @throws \Exception
*/
public function checkRateLimit(array $fingerPrintInfo, int $rateTimeout, int $fileLimit):bool public function checkRateLimit(array $fingerPrintInfo, int $rateTimeout, int $fileLimit):bool
{ {
$q = $this->DB->prepare( $query = match ($this->dbType) {
'SELECT files, time, iphash, COUNT(*) AS count FROM ratelimit WHERE iphash = (:iphash)', 'pgsql' => 'SELECT EXISTS(SELECT id FROM ratelimit WHERE iphash = (:iphash)), id, iphash, files, time FROM ratelimit WHERE iphash = (:iphash) LIMIT 1',
); default => 'SELECT * FROM ratelimit WHERE iphash = (:iphash) AND EXISTS (SELECT id FROM ratelimit WHERE iphash = (:iphash)) LIMIT 1'
};
$q = $this->DB->prepare($query);
$q->bindValue(':iphash', $fingerPrintInfo['ip_hash']); $q->bindValue(':iphash', $fingerPrintInfo['ip_hash']);
$q->execute(); $q->execute();
$result = $q->fetch(); $result = $q->fetch();
$q->closeCursor();
//If there is no other match a record does not exist, create one. //If there is no other match a record does not exist, create one.
if (!$result['count'] > 0) { if (!$result) {
$this->createRateLimit($fingerPrintInfo); $this->createRateLimit($fingerPrintInfo);
return false; return false;
} }
// Apply rate-limit when file count reached and timeout not reached. // Apply rate-limit when file count reached and timeout not reached.
if ($result['files'] === $fileLimit and !$this->compareTime($result['time'], $rateTimeout)) { if ($result['files'] === $fileLimit and !$this->compareTime($result['time'], $rateTimeout)) {
return true; return true;
} }
// Update timestamp if timeout reached, reset file count and add the incoming file count.
// Update timestamp if timeout reached.
if ($this->compareTime($result['time'], $rateTimeout)) { if ($this->compareTime($result['time'], $rateTimeout)) {
$this->updateRateLimit($fingerPrintInfo['files_amount'], true, $fingerPrintInfo); $this->updateRateLimit($fingerPrintInfo['files_amount'], true, $fingerPrintInfo);
return false; return false;
} }
// Add filecount, timeout not reached. // Add filecount, timeout not reached.
if ($result['files'] < $fileLimit and !$this->compareTime($result['time'], $rateTimeout)) { if ($result['files'] < $fileLimit and !$this->compareTime($result['time'], $rateTimeout)) {
$this->updateRateLimit($result['files'] + $fingerPrintInfo['files_amount'], false, $fingerPrintInfo); $this->updateRateLimit($result['files'] + $fingerPrintInfo['files_amount'], false, $fingerPrintInfo);
return false; return false;
} }
return false; return false;
} }
} }

View File

@ -2,7 +2,7 @@
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View File

@ -1,9 +1,8 @@
<?php <?php
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -67,7 +66,7 @@ class Response
* @param $code mixed The HTTP status code to return. * @param $code mixed The HTTP status code to return.
* @param $desc string The description of the error. * @param $desc string The description of the error.
*/ */
public function error(int $code, string $desc): void public function error(int $code, string $desc):string
{ {
$response = match ($this->type) { $response = match ($this->type) {
'csv' => $this->csvError($desc), 'csv' => $this->csvError($desc),
@ -77,6 +76,7 @@ class Response
}; };
http_response_code($code); http_response_code($code);
echo $response; echo $response;
exit(1);
} }
/* Returning a string that contains the error message. */ /* Returning a string that contains the error message. */

View File

@ -1,9 +1,8 @@
<?php <?php
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -21,8 +20,6 @@
namespace Pomf\Uguu\Classes; namespace Pomf\Uguu\Classes;
use Exception;
class Upload extends Response class Upload extends Response
{ {
public array $FILE_INFO; public array $FILE_INFO;
@ -36,36 +33,36 @@ class Upload extends Response
* @param $files array The files array from the $_FILES superglobal. * @param $files array The files array from the $_FILES superglobal.
* *
* @return array An array of arrays. * @return array An array of arrays.
* @throws \Exception
*/ */
public function reFiles(array $files):array public function reFiles(array $files):array
{ {
$this->Connector = new Connector(); $this->Connector = new Connector();
$this->Connector->setDB($this->Connector->DB);
$result = []; $result = [];
$files = $this->diverseArray($files); $files = $this->diverseArray($files);
foreach ($files as $file) { foreach ($files as $file) {
$hash = sha1_file($file['tmp_name']);
$this->FILE_INFO = [ $this->FILE_INFO = [
'TEMP_NAME' => $file['tmp_name'], 'TEMP_NAME' => $file['tmp_name'],
'NAME' => strip_tags($this->checkNameLength($file['name'])), 'NAME' => strip_tags($this->checkNameLength($file['name'])),
'SIZE' => $file['size'], 'SIZE' => $file['size'],
'SHA1' => $hash, 'SHA1' => sha1_file($file['tmp_name']),
'EXTENSION' => $this->fileExtension($file), 'EXTENSION' => $this->fileExtension($file),
'MIME' => $this->fileMIME($file), 'MIME' => $this->fileMIME($file),
'DUPE' => false,
'FILENAME' => null,
]; ];
// Check if anti dupe is enabled
if ($this->Connector->CONFIG['ANTI_DUPE']) { if ($this->Connector->CONFIG['ANTI_DUPE']) {
$dupeResult = $this->Connector->antiDupe($hash); // Check if hash exists in DB, if it does return the name of the file
$dupeResult = $this->Connector->antiDupe($this->FILE_INFO['SHA1']);
if ($dupeResult['result']) { if ($dupeResult['result']) {
$this->FILE_INFO['NEW_NAME'] = $dupeResult['name']; $this->FILE_INFO['FILENAME'] = $dupeResult['name'];
$this->FILE_INFO['DUPE'] = true;
} }
} }
// If its not a dupe then generate a new name
if (!isset($this->FILE_INFO['NEW_NAME'])) { if (!$this->FILE_INFO['DUPE']) {
$this->FILE_INFO['NEW_NAME'] = $this->generateName($this->FILE_INFO['EXTENSION']); $this->FILE_INFO['FILENAME'] = $this->generateName($this->FILE_INFO['EXTENSION']);
} }
$result[] = [ $result[] = [
$this->FILE_INFO['TEMP_NAME'], $this->FILE_INFO['TEMP_NAME'],
$this->FILE_INFO['NAME'], $this->FILE_INFO['NAME'],
@ -73,6 +70,8 @@ class Upload extends Response
$this->FILE_INFO['SHA1'], $this->FILE_INFO['SHA1'],
$this->FILE_INFO['EXTENSION'], $this->FILE_INFO['EXTENSION'],
$this->FILE_INFO['MIME'], $this->FILE_INFO['MIME'],
$this->FILE_INFO['DUPE'],
$this->FILE_INFO['FILENAME'],
]; ];
} }
return $result; return $result;
@ -120,7 +119,6 @@ class Upload extends Response
* Takes a file, checks if it's blacklisted, moves it to the file storage, and then logs it to the database * Takes a file, checks if it's blacklisted, moves it to the file storage, and then logs it to the database
* *
* @return array An array containing the hash, name, url, and size of the file. * @return array An array containing the hash, name, url, and size of the file.
* @throws \Exception
*/ */
public function uploadFile():array public function uploadFile():array
{ {
@ -129,16 +127,19 @@ class Upload extends Response
if ( if (
$this->Connector->checkRateLimit( $this->Connector->checkRateLimit(
$this->fingerPrintInfo, $this->fingerPrintInfo,
(int) $this->Connector->CONFIG['RATE_LIMIT_TIMEOUT'], $this->Connector->CONFIG['RATE_LIMIT_TIMEOUT'],
(int) $this->Connector->CONFIG['RATE_LIMIT_FILES'] $this->Connector->CONFIG['RATE_LIMIT_FILES'],
) )
) { ) {
throw new Exception('Rate limit, please wait ' . $this->Connector->CONFIG['RATE_LIMIT_TIMEOUT'] . $this->Connector->response->error(
' seconds before uploading again.', 500); 500,
'Rate limit, please wait ' . $this->Connector->CONFIG['RATE_LIMIT_TIMEOUT'] .
' seconds before uploading again.',
);
} }
// Continue // Continue
case $this->Connector->CONFIG['BLACKLIST_DB']: case $this->Connector->CONFIG['BLACKLIST_DB']:
$this->Connector->checkFileBlacklist($this->FILE_INFO); $this->Connector->checkFileBlacklist($this->FILE_INFO['SHA1']);
// Continue // Continue
case $this->Connector->CONFIG['FILTER_MODE'] && empty($this->FILE_INFO['EXTENSION']): case $this->Connector->CONFIG['FILTER_MODE'] && empty($this->FILE_INFO['EXTENSION']):
$this->checkMimeBlacklist(); $this->checkMimeBlacklist();
@ -148,30 +149,33 @@ class Upload extends Response
$this->checkExtensionBlacklist(); $this->checkExtensionBlacklist();
// Continue // Continue
} }
// If its not a dupe then skip checking if file can be written and
// skip inserting it into the DB.
if (!$this->FILE_INFO['DUPE']) {
if (!is_dir($this->Connector->CONFIG['FILES_ROOT'])) { if (!is_dir($this->Connector->CONFIG['FILES_ROOT'])) {
throw new Exception('File storage path not accessible.', 500); $this->Connector->response->error(500, 'File storage path not accessible.');
} }
if ( if (
!move_uploaded_file( !move_uploaded_file(
$this->FILE_INFO['TEMP_NAME'], $this->FILE_INFO['TEMP_NAME'],
$this->Connector->CONFIG['FILES_ROOT'] . $this->Connector->CONFIG['FILES_ROOT'] .
$this->FILE_INFO['NEW_NAME'], $this->FILE_INFO['FILENAME'],
) )
) { ) {
throw new Exception('Failed to move file to destination', 500); $this->Connector->response->error(500, 'Failed to move file to destination.');
} }
if (!chmod($this->Connector->CONFIG['FILES_ROOT'] . $this->FILE_INFO['NEW_NAME'], 0644)) { if (!chmod($this->Connector->CONFIG['FILES_ROOT'] . $this->FILE_INFO['FILENAME'], 0644)) {
throw new Exception('Failed to change file permissions', 500); $this->Connector->response->error(500, 'Failed to change file permissions.');
} }
$this->Connector->newIntoDB($this->FILE_INFO, $this->fingerPrintInfo); $this->Connector->newIntoDB($this->FILE_INFO, $this->fingerPrintInfo);
}
return [ return [
'hash' => $this->FILE_INFO['SHA1'], 'hash' => $this->FILE_INFO['SHA1'],
'name' => $this->FILE_INFO['NAME'], 'name' => $this->FILE_INFO['NAME'],
'url' => 'https://' . $this->Connector->CONFIG['FILE_DOMAIN'] . '/' . $this->FILE_INFO['NEW_NAME'], 'filename' => $this->FILE_INFO['FILENAME'],
'url' => 'https://' . $this->Connector->CONFIG['FILE_DOMAIN'] . '/' . $this->FILE_INFO['FILENAME'],
'size' => $this->FILE_INFO['SIZE'], 'size' => $this->FILE_INFO['SIZE'],
'dupe' => $this->FILE_INFO['DUPE'],
]; ];
} }
@ -182,7 +186,6 @@ class Upload extends Response
* *
* @param $files_amount int The amount of files that are being uploaded. * @param $files_amount int The amount of files that are being uploaded.
* *
* @throws \Exception
*/ */
public function fingerPrint(int $files_amount):void public function fingerPrint(int $files_amount):void
{ {
@ -200,7 +203,7 @@ class Upload extends Response
'files_amount' => $files_amount, 'files_amount' => $files_amount,
]; ];
} else { } else {
throw new Exception('Invalid user agent.', 500); $this->Connector->response->error(500, 'Invalid user agent.');
} }
} }
@ -259,28 +262,27 @@ class Upload extends Response
/** /**
* > Check if the file's MIME type is in the blacklist * > Check if the file's MIME type is in the blacklist
* *
* @throws \Exception
*/ */
public function checkMimeBlacklist():void public function checkMimeBlacklist():void
{ {
if (in_array($this->FILE_INFO['MIME'], $this->Connector->CONFIG['BLOCKED_MIME'])) { if (in_array($this->FILE_INFO['MIME'], $this->Connector->CONFIG['BLOCKED_MIME'])) {
throw new Exception('Filetype not allowed.', 415); $this->Connector->response->error(415, 'Filetype not allowed');
} }
} }
/** /**
* > Check if the file extension is in the blacklist * > Check if the file extension is in the blacklist
* *
* @throws \Exception
*/ */
public function checkExtensionBlacklist():void public function checkExtensionBlacklist():void
{ {
if (in_array($this->FILE_INFO['EXTENSION'], $this->Connector->CONFIG['BLOCKED_EXTENSIONS'])) { if (in_array($this->FILE_INFO['EXTENSION'], $this->Connector->CONFIG['BLOCKED_EXTENSIONS'])) {
throw new Exception('Filetype not allowed.', 415); $this->Connector->response->error(415, 'Filetype not allowed');
} }
} }
public function checkNameLength(string $fileName): string { public function checkNameLength(string $fileName):string
{
if (strlen($fileName) > 250) { if (strlen($fileName) > 250) {
return substr($fileName, 0, 250); return substr($fileName, 0, 250);
} else { } else {
@ -295,18 +297,17 @@ class Upload extends Response
* @param $extension string The file extension. * @param $extension string The file extension.
* *
* @return string A string * @return string A string
* @throws \Exception
*/ */
public function generateName(string $extension):string public function generateName(string $extension):string
{ {
do { do {
if ($this->Connector->CONFIG['FILES_RETRIES'] === 0) { if ($this->Connector->CONFIG['FILES_RETRIES'] === 0) {
throw new Exception('Gave up trying to find an unused name!', 500); $this->Connector->response->error(500, 'Gave up trying to find an unused name!');
} }
$NEW_NAME = ''; $NEW_NAME = '';
$count = strlen($this->Connector->CONFIG['ID_CHARSET']); for ($i = 0; $i < $this->Connector->CONFIG['NAME_LENGTH']; $i++) {
while ($this->Connector->CONFIG['NAME_LENGTH']--) { $index = rand(0, strlen($this->Connector->CONFIG['ID_CHARSET']) - 1);
$NEW_NAME .= $this->Connector->CONFIG['ID_CHARSET'][mt_rand(0, $count - 1)]; $NEW_NAME .= $this->Connector->CONFIG['ID_CHARSET'][$index];
} }
if (!empty($extension)) { if (!empty($extension)) {
$NEW_NAME .= '.' . $extension; $NEW_NAME .= '.' . $extension;

View File

@ -3,12 +3,13 @@
"allowErrors": false "allowErrors": false
}, },
"dest": "dist", "dest": "dist",
"pkgVersion": "1.6.7", "pkgVersion": "1.7.0",
"pages": [ "pages": [
"index.ejs", "index.ejs",
"faq.ejs", "faq.ejs",
"tools.ejs" "tools.ejs"
], ],
"DEBUG": false,
"max_upload_size": 128, "max_upload_size": 128,
"expireTime": "48", "expireTime": "48",
"siteName": "Uguu", "siteName": "Uguu",

View File

@ -0,0 +1,27 @@
CREATE TABLE files
(
id serial PRIMARY KEY,
hash text NOT NULL,
originalname text NOT NULL,
filename text NOT NULL,
size integer not null,
date integer not null,
ip text null
);
CREATE TABLE blacklist
(
id serial PRIMARY KEY,
hash text NOT NULL,
originalname text NOT NULL,
time integer not null,
ip text null
);
CREATE TABLE ratelimit
(
id serial PRIMARY KEY,
iphash text NOT NULL,
files integer not null,
time integer not null
);

View File

@ -3,7 +3,7 @@
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by

View File

@ -3,7 +3,7 @@
/** /**
* Uguu * Uguu
* *
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se> * @copyright Copyright (c) 2022-2023 Go Johansson (nokonoko) <neku@pomf.se>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -18,56 +18,31 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../vendor/autoload.php';
use Pomf\Uguu\Classes\Upload; use Pomf\Uguu\Classes\Upload;
use Pomf\Uguu\Classes\Response; use Pomf\Uguu\Classes\Response;
/** function handleFiles(string $outputFormat, array $files):void
* It takes a string and an array as arguments, creates a new Upload object,
* calls the reFiles method on the Upload object, calls the fingerPrint method on
* the Upload object, calls the uploadFile method on the Upload object,
* calls the send method on the Upload object, and calls the error method on the
* Upload object
*
* @param $outputFormat string The format of the output, json or xml
* @param $files array The file to be uploaded, which is an array.
*
* @throws \Exception
*/
function handleFile(string $outputFormat, array $files): void
{ {
$fCount = count($files['size']);
$upload = new Upload($outputFormat); $upload = new Upload($outputFormat);
$files = $upload->reFiles($files); $files = $upload->reFiles($files);
try { $fCount = count($files);
$upload->fingerPrint($fCount); $upload->fingerPrint($fCount);
$res = []; $res = [];
foreach ($files as $ignored) { $i = 0;
while ($i < $fCount) {
$res[] = $upload->uploadFile(); $res[] = $upload->uploadFile();
$i++;
} }
if (!empty($res)) { if (!empty($res)) {
$upload->send($res); $upload->send($res);
} }
} catch (Exception $e) {
$upload->error(500, $e->getMessage());
}
} }
$response = new Response('json'); $response = new Response('json');
$resType = (isset($_GET['output']) and !empty($_GET['output'])) ? strtolower(preg_replace('/[^a-zA-Z]/', '', $_GET['output'])) : 'json';
if (!isset($_FILES['files']) or empty($_FILES['files'])) { if (!isset($_FILES['files']) or empty($_FILES['files'])) {
$response->error(400, 'No input file(s)'); $response->error(400, 'No input file(s)');
} }
if (isset($_GET['output']) and !empty($_GET['output'])) { handleFiles($resType, $_FILES['files']);
$resType = strtolower(preg_replace('/[^a-zA-Z]/', '', $_GET['output']));
} else {
$resType = 'json';
}
try {
handleFile($resType, $_FILES['files']);
} catch (Exception $e) {
$response->error($e->getCode(), $e->getMessage());
}