bug fixes

This commit is contained in:
Go Johansson 2022-12-25 05:50:55 +01:00
parent 2021c02a02
commit f0b5e51c8b
8 changed files with 514 additions and 471 deletions

1
.php-cs-fixer.cache Normal file
View File

@ -0,0 +1 @@
{"php":"8.1.13","version":"3.13.1","indent":" ","lineEnding":"\n","rules":{"blank_line_after_opening_tag":true,"blank_line_between_import_groups":true,"braces":{"allow_single_line_anonymous_class_with_empty_body":true},"class_definition":{"inline_constructor_arguments":false,"space_before_parenthesis":true},"compact_nullable_typehint":true,"declare_equal_normalize":true,"lowercase_cast":true,"lowercase_static_reference":true,"new_with_braces":true,"no_blank_lines_after_class_opening":true,"no_leading_import_slash":true,"no_whitespace_in_blank_line":true,"ordered_class_elements":{"order":["use_trait"]},"ordered_imports":{"imports_order":["class","function","const"],"sort_algorithm":"none"},"return_type_declaration":true,"short_scalar_cast":true,"single_blank_line_before_namespace":true,"single_import_per_statement":{"group_to_single_imports":false},"single_trait_insert_per_statement":true,"ternary_operator_spaces":true,"visibility_required":true,"blank_line_after_namespace":true,"constant_case":true,"elseif":true,"function_declaration":true,"indentation_type":true,"line_ending":true,"lowercase_keywords":true,"method_argument_space":{"on_multiline":"ensure_fully_multiline"},"no_break_comment":true,"no_closing_tag":true,"no_space_around_double_colon":true,"no_spaces_after_function_name":true,"no_spaces_inside_parenthesis":true,"no_trailing_whitespace":true,"no_trailing_whitespace_in_comment":true,"single_blank_line_at_eof":true,"single_class_element_per_statement":{"elements":["property"]},"single_line_after_imports":true,"switch_case_semicolon_to_colon":true,"switch_case_space":true,"encoding":true,"full_opening_tag":true},"hashes":{"\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder3788\/src\/static\/php\/upload.php":"b626750d2d9ac4f2b2f98a8ec8219533","src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder1142\/src\/static\/php\/upload.php":"b626750d2d9ac4f2b2f98a8ec8219533","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder24\/src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder1007\/src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder3242\/src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder681\/src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder1535\/src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder1163\/src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder4666\/src\/static\/php\/upload.php":"2aa4d70e18ce7445ddd4ba0f76fa0621","\/private\/var\/folders\/5_\/px3cvvbs4rd5bjzl8py2mjnc0000gq\/T\/PHP CS Fixertemp_folder5333\/src\/static\/php\/upload.php":"dc38feb300c1c8ab4614639d5a7af4f7"}}

View File

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

View File

@ -1,15 +0,0 @@
<?xml version="1.0"?>
<psalm
errorLevel="3"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="." />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
</psalm>

View File

@ -1,4 +1,5 @@
<?php
/**
* Uguu
*
@ -23,8 +24,8 @@
use Exception;
use PDO;
class Database
{
class Database
{
private PDO $DB;
/**
@ -32,7 +33,7 @@
*
* @param $DB PDO The database connection.
*/
public function setDB(PDO $DB):void
public function setDB(PDO $DB): void
{
$this->DB = $DB;
}
@ -45,15 +46,14 @@
* @return int The number of rows that match the query.
* @throws \Exception
*/
public function dbCheckNameExists(string $name):int
public function dbCheckNameExists(string $name): int
{
try {
$q = $this->DB->prepare('SELECT COUNT(filename) FROM files WHERE filename = (:name)');
$q->bindValue(':name', $name);
$q->execute();
return $q->fetchColumn();
}
catch (Exception) {
} catch (Exception) {
throw new Exception('Cant check if name exists in DB.', 500);
}
}
@ -65,7 +65,7 @@
*
* @throws \Exception
*/
public function checkFileBlacklist(array $FILE_INFO):void
public function checkFileBlacklist(array $FILE_INFO): void
{
try {
$q = $this->DB->prepare('SELECT hash, COUNT(*) AS count FROM blacklist WHERE hash = (:hash)');
@ -75,8 +75,7 @@
if ($result['count'] > 0) {
throw new Exception('File blacklisted!', 415);
}
}
catch (Exception) {
} catch (Exception) {
throw new Exception('Cant check blacklist DB.', 500);
}
}
@ -88,11 +87,8 @@
*
* @throws \Exception
*/
public function antiDupe(string $hash):bool|array|string
public function antiDupe(string $hash): array
{
if (!$this->CONFIG['ANTI_DUPE']) {
return true;
}
try {
$q = $this->DB->prepare(
'SELECT filename, COUNT(*) AS count FROM files WHERE hash = (:hash)',
@ -101,12 +97,16 @@
$q->execute();
$result = $q->fetch();
if ($result['count'] > 0) {
return $result['filename'];
return [
'result' => true,
'name' => $result['filename'],
];
} else {
return true;
return [
'result' => false
];
}
}
catch (Exception) {
} catch (Exception) {
throw new Exception('Cant check for dupes in DB.', 500);
}
}
@ -119,7 +119,7 @@
*
* @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(
@ -133,8 +133,7 @@
$q->bindValue(':date', $fingerPrintInfo['timestamp']);
$q->bindValue(':ip', $fingerPrintInfo['ip']);
$q->execute();
}
catch (Exception) {
} catch (Exception) {
throw new Exception('Cant insert into DB.', 500);
}
}
@ -144,7 +143,7 @@
*
* @param $fingerPrintInfo array
*/
public function createRateLimit(array $fingerPrintInfo):void
public function createRateLimit(array $fingerPrintInfo): void
{
$q = $this->DB->prepare(
'INSERT INTO timestamp (iphash, files, time)' .
@ -163,7 +162,7 @@
* @param $iStamp boolean A boolean value that determines whether or not to update the timestamp.
* @param $fingerPrintInfo array An array containing the following keys:
*/
public function updateRateLimit(int $fCount, bool $iStamp, array $fingerPrintInfo):void
public function updateRateLimit(int $fCount, bool $iStamp, array $fingerPrintInfo): void
{
if ($iStamp) {
$q = $this->DB->prepare(
@ -188,7 +187,7 @@
*
* @return bool A boolean value.
*/
public function checkRateLimit(array $fingerPrintInfo):bool
public function checkRateLimit(array $fingerPrintInfo): bool
{
$q = $this->DB->prepare(
'SELECT files, time, iphash, COUNT(*) AS count FROM ratelimit WHERE iphash = (:iphash)',
@ -216,4 +215,4 @@
}
return false;
}
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* Uguu
*
@ -22,21 +23,22 @@
use Exception;
class Upload extends Response
{
class Upload extends Response
{
public array $FILE_INFO;
public array $fingerPrintInfo;
private mixed $Connector;
/**
* Takes an array of files, and returns an array of arrays containing the file's temporary name, name, size, SHA1 hash, extension, and MIME type
* Takes an array of files, and returns an array of arrays containing the file's temporary name,
* name, size, SHA1 hash, extension, and MIME type
*
* @param $files array The files array from the $_FILES superglobal.
*
* @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->setDB($this->Connector->DB);
@ -51,8 +53,19 @@
'SHA1' => $hash,
'EXTENSION' => $this->fileExtension($file),
'MIME' => $this->fileMIME($file),
'NEW_NAME' => $this->generateName($this->fileExtension($file), $hash),
];
if ($this->Connector->CONFIG['ANTI_DUPE']) {
$dupeResult = $this->Connector->antiDupe($hash);
if ($dupeResult['result']) {
$this->FILE_INFO['NEW_NAME'] = $dupeResult['name'];
}
}
if (!isset($this->FILE_INFO['NEW_NAME'])) {
$this->FILE_INFO['NEW_NAME'] = $this->generateName($this->FILE_INFO['EXTENSION']);
}
$result[] = [
$this->FILE_INFO['TEMP_NAME'],
$this->FILE_INFO['NAME'],
@ -92,7 +105,7 @@
* ]
* ```
*/
public function diverseArray(array $files):array
public function diverseArray(array $files): array
{
$result = [];
foreach ($files as $key1 => $value1) {
@ -109,20 +122,25 @@
* @return array An array containing the hash, name, url, and size of the file.
* @throws \Exception
*/
public function uploadFile():array
public function uploadFile(): array
{
if ($this->Connector->CONFIG['RATE_LIMIT']) {
switch (true) {
case $this->Connector->CONFIG['RATE_LIMIT']:
$this->Connector->checkRateLimit($this->fingerPrintInfo);
}
if ($this->Connector->CONFIG['BLACKLIST_DB']) {
// Continue
case $this->Connector->CONFIG['BLACKLIST_DB']:
$this->Connector->checkFileBlacklist($this->FILE_INFO);
}
if ($this->Connector->CONFIG['FILTER_MODE'] && empty($this->FILE_INFO['EXTENSION'])) {
// Continue
case $this->Connector->CONFIG['FILTER_MODE'] && empty($this->FILE_INFO['EXTENSION']):
$this->checkMimeBlacklist();
}
if ($this->Connector->CONFIG['FILTER_MODE'] && !empty($this->FILE_INFO['EXTENSION'])) {
// Continue
case $this->Connector->CONFIG['FILTER_MODE'] && !empty($this->FILE_INFO['EXTENSION']):
$this->checkMimeBlacklist();
$this->checkExtensionBlacklist();
// Continue
case !$this->Connector->CONFIG['LOG_IP']:
$this->fingerPrintInfo['ip'] = null;
// Continue
}
if (!is_dir($this->Connector->CONFIG['FILES_ROOT'])) {
throw new Exception('File storage path not accessible.', 500);
@ -139,9 +157,9 @@
if (!chmod($this->Connector->CONFIG['FILES_ROOT'] . $this->FILE_INFO['NEW_NAME'], 0644)) {
throw new Exception('Failed to change file permissions', 500);
}
if (!$this->Connector->CONFIG['LOG_IP']) {
$this->fingerPrintInfo['ip'] = null;
}
$this->Connector->newIntoDB($this->FILE_INFO, $this->fingerPrintInfo);
return [
'hash' => $this->FILE_INFO['SHA1'],
@ -152,14 +170,15 @@
}
/**
* Takes the amount of files that are being uploaded, and creates a fingerprint of the user's IP address, user agent, and the amount of files being
* Takes the amount of files that are being uploaded, and creates a fingerprint of the user's IP address,
* user agent, and the amount of files 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
{
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
$USER_AGENT = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_ENCODED);
@ -182,27 +201,48 @@
*
* @return string The MIME type of the file.
*/
public function fileMIME(array $file):string
public function fileMIME(array $file): string
{
$FILE_INFO = finfo_open(FILEINFO_MIME_TYPE);
return finfo_file($FILE_INFO, $file['tmp_name']);
}
/**
* It takes an array of strings, and returns the last two strings joined by a dot,
* unless the last two strings are in the array of strings in the
* `DOUBLE_DOTS_EXTENSIONS` config variable, in which case it returns the last string
*
* @param $extension array The extension of the file.
*
* @return string The last two elements of the array are joined together and returned.
*/
public function doubleDotExtension(array $extension): string
{
$doubleDotArray = array_slice($extension, -2, 2);
$doubleDot = strtolower(preg_replace('/[^a-zA-Z.]/', '', join('.', $doubleDotArray)));
if (in_array($doubleDot, $this->Connector->CONFIG['DOUBLE_DOTS_EXTENSIONS'])) {
return $doubleDot;
} else {
return end($extension);
}
}
/**
* Takes a file and returns the file extension
*
* @param $file array The file you want to get the extension from.
*
* @return ?string The file extension of the file.
* @return string The file extension of the file.
*/
public function fileExtension(array $file):?string
public function fileExtension(array $file): string
{
$extension = explode('.', $file['name']);
if (substr_count($file['name'], '.') > 0) {
return end($extension);
} else {
return null;
}
$dotCount = substr_count($file['name'], '.');
return match ($dotCount) {
0 => null,
1 => end($extension),
2 => $this->doubleDotExtension($extension)
};
}
/**
@ -210,7 +250,7 @@
*
* @throws \Exception
*/
public function checkMimeBlacklist():void
public function checkMimeBlacklist(): void
{
if (in_array($this->FILE_INFO['MIME'], $this->Connector->CONFIG['BLOCKED_MIME'])) {
throw new Exception('Filetype not allowed.', 415);
@ -222,7 +262,7 @@
*
* @throws \Exception
*/
public function checkExtensionBlacklist():void
public function checkExtensionBlacklist(): void
{
if (in_array($this->FILE_INFO['EXTENSION'], $this->Connector->CONFIG['BLOCKED_EXTENSIONS'])) {
throw new Exception('Filetype not allowed.', 415);
@ -230,7 +270,8 @@
}
/**
* Generates a random string of characters, checks if it exists in the database, and if it does, it generates another one
* Generates a random string of characters, checks if it exists in the database,
* and if it does, it generates another one
*
* @param $extension string The file extension.
* @param $hash string The hash of the file.
@ -238,9 +279,8 @@
* @return string A string
* @throws \Exception
*/
public function generateName(string $extension, string $hash):string
public function generateName(string $extension): string
{
if ($this->Connector->antiDupe($hash)) {
do {
if ($this->Connector->CONFIG['FILES_RETRIES'] === 0) {
throw new Exception('Gave up trying to find an unused name!', 500);
@ -255,8 +295,5 @@
}
} while ($this->Connector->dbCheckNameExists($NEW_NAME) > 0);
return $NEW_NAME;
} else {
return $this->Connector->antiDupe($hash);
}
}
}
}

View File

@ -20,13 +20,6 @@
"ext-fileinfo": "*",
"ext-pdo": "*"
},
"require-dev": {
"phpunit/phpunit": "^9.5.27",
"squizlabs/php_codesniffer": "^3.7.1",
"phpmd/phpmd": "^2.13.0",
"phpstan/phpstan": "^1.9.3",
"vimeo/psalm": "^5.2.0"
},
"config": {
"optimize-autoloader": true,
"classmap-authoritative": true

View File

@ -3,7 +3,7 @@
"allowErrors": false
},
"dest": "dist",
"pkgVersion": "1.6.3",
"pkgVersion": "1.6.4",
"pages": [
"index.ejs",
"faq.ejs",
@ -39,6 +39,13 @@
"FILES_URL": "https://files.domain.com",
"NAME_LENGTH": 8,
"ID_CHARSET": "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ",
"DOUBLE_DOTS_EXTENSIONS": [
"tar.bz2",
"tar.gz",
"min.css",
"min.js",
"conf.bak"
],
"BLOCKED_EXTENSIONS": [
"exe",
"scr",

View File

@ -1,4 +1,8 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/**
* Uguu
*
@ -17,14 +21,25 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
require_once __DIR__ . '/../vendor/autoload.php';
use Pomf\Uguu\Classes\Upload;
use Pomf\Uguu\Classes\Response;
function handleFile(string $outputFormat, array $files)
{
/**
* 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
{
$upload = new Upload($outputFormat);
$files = $upload->reFiles($files);
try {
@ -39,15 +54,21 @@
} catch (Exception $e) {
$upload->error($e->getCode(), $e->getMessage());
}
}
}
if (!isset($_FILES['files']) or empty($_FILES['files'])) {
$response = new Response('json');
if (!isset($_FILES['files']) or empty($_FILES['files'])) {
$response->error(400, 'No input file(s)');
}
if (isset($_GET['output']) and !empty($_GET['output'])) {
}
if (isset($_GET['output']) and !empty($_GET['output'])) {
$resType = strtolower(preg_replace('/[^a-zA-Z]/', '', $_GET['output']));
} else {
} else {
$resType = 'json';
}
}
try {
handleFile($resType, $_FILES['files']);
} catch (Exception $e) {
$response->error($e->getCode(), $e->getMessage());
}