1
0
mirror of https://github.com/nokonoko/Uguu.git synced 2024-01-06 13:35:15 +00:00

minor changes + documentation

This commit is contained in:
Go Johansson 2022-12-16 20:44:43 +01:00
parent 2a85717f5b
commit 8f7f88401b
10 changed files with 782 additions and 562 deletions

2
.gitignore vendored
View File

@ -8,3 +8,5 @@ uguu.sq3
.idea
.phpdoc
.vscode
composer.phar
composer.lock

View File

@ -43,19 +43,25 @@ copy-img:
copy-php:
cp -v $(CURDIR)/src/static/php/*.php $(CURDIR)/build/php/
cp -v $(CURDIR)/src/Classes/*.php $(CURDIR)/build/php/classes/
install: installdirs
cp -rv $(CURDIR)/build/* $(DESTDIR)/
mv $(DESTDIR)/html/min/* $(DESTDIR)/
mv $(DESTDIR)/js/* $(DESTDIR)/
mv $(DESTDIR)/css/* $(DESTDIR)/
cp -rv $(CURDIR)/vendor $(DESTDIR)/
cp $(CURDIR)/src/config.json $(DESTDIR)/
mv $(DESTDIR)/html/min/* $(DESTDIR)/public/
mv $(DESTDIR)/js/* $(DESTDIR)/public/
mv $(DESTDIR)/css/* $(DESTDIR)/public/
mv $(DESTDIR)/php/* $(DESTDIR)/
rm -rf $(DESTDIR)/html
rm -rf $(DESTDIR)/css
rm -rf $(DESTDIR)/js
rm -rf $(DESTDIR)/php
mv $(DESTDIR)/uguu.css $(DESTDIR)/uguu.min.css
mv $(DESTDIR)/uguu.js $(DESTDIR)/uguu.min.js
mv $(DESTDIR)/public/uguu.css $(DESTDIR)/public/uguu.min.css
mv $(DESTDIR)/public/uguu.js $(DESTDIR)/public/uguu.min.js
mv $(DESTDIR)/img $(DESTDIR)/public/
mv $(DESTDIR)/grill.php $(DESTDIR)/public/
mv $(DESTDIR)/upload.php $(DESTDIR)/public/
dist:
DESTDIR=$(TMPDIR)/uguu-$(PKGVERSION)
@ -98,5 +104,5 @@ purge-container:
fi;
builddirs:
mkdir -p $(CURDIR)/build $(CURDIR)/build/img $(CURDIR)/build/html $(CURDIR)/build/html/min $(CURDIR)/build/html/unmin $(CURDIR)/build/js $(CURDIR)/build/css $(CURDIR)/build/php
mkdir -p $(CURDIR)/build $(CURDIR)/build/img $(CURDIR)/build/html $(CURDIR)/build/html/min $(CURDIR)/build/html/unmin $(CURDIR)/build/js $(CURDIR)/build/css $(CURDIR)/build/php $(CURDIR)/build/php/classes $(CURDIR)/build/public

899
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -28,18 +28,20 @@ class Connector extends Database
{
public PDO $DB;
public array $CONFIG;
/**
* @throws Exception
* Reads the config.json file and populates the CONFIG property with the settings
*
* @throws \Exception
*/
public function __construct()
{
if (!file_exists(__DIR__ . '/../config.json')) {
if (!file_exists(__DIR__ . '../config.json')) {
throw new Exception('Cant read settings file.', 500);
}
try {
$this->CONFIG = json_decode(
file_get_contents(__DIR__ . '/../config.json'),
file_get_contents(__DIR__ . '../config.json'),
true
);
$this->assemble();
@ -47,9 +49,11 @@ class Connector extends Database
throw new Exception('Cant populate settings.', 500);
}
}
/**
* @throws Exception
* > Tries to connect to the database
*
* @throws \Exception
*/
public function assemble()
{

View File

@ -25,6 +25,9 @@ class CuteGrills
{
public array $GRILLS;
/**
* Loads the list of grills, then redirects to a random grill
*/
public function showGrills(): void
{
$this->loadGrills();
@ -38,6 +41,9 @@ class CuteGrills
}
}
/**
* Loads the images from the `img/grills/` directory into the `GRILLS` array
*/
public function loadGrills(): void
{
$this->GRILLS = array_slice(scandir('img/grills/'), 2);

View File

@ -28,16 +28,25 @@ class Database
{
private PDO $DB;
public function setDB($DB): void
/**
* Sets the value of the DB variable.
*
* @param $DB PDO The database connection.
*/
public function setDB(PDO $DB): void
{
$this->DB = $DB;
}
/**
* @throws Exception
* Checks if a file name exists in the database
*
* @param $name string The name of the file.
*
* @return int The number of rows that match the query.
* @throws \Exception
*/
public function dbCheckNameExists($name): string
public function dbCheckNameExists(string $name): int
{
try {
$q = $this->DB->prepare('SELECT COUNT(filename) FROM files WHERE filename = (:name)');
@ -48,11 +57,15 @@ class Database
throw new Exception('Cant check if name exists in DB.', 500);
}
}
/**
* @throws Exception
* Checks if the file is blacklisted
*
* @param $FILE_INFO array An array containing the following:
*
* @throws \Exception
*/
public function checkFileBlacklist($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)');
@ -66,11 +79,15 @@ class Database
throw new Exception('Cant check blacklist DB.', 500);
}
}
/**
* @throws Exception
* 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($hash): bool | array | string
public function antiDupe(string $hash): bool | array | string
{
if (!$this->CONFIG['ANTI_DUPE']) {
return true;
@ -92,11 +109,16 @@ class Database
throw new Exception('Cant check for dupes in DB.', 500);
}
}
/**
* @throws Exception
* Inserts a new file into the database
*
* @param $FILE_INFO array
* @param $fingerPrintInfo array
*
* @throws \Exception
*/
public function newIntoDB($FILE_INFO, $fingerPrintInfo): void
public function newIntoDB(array $FILE_INFO, array $fingerPrintInfo): void
{
try {
$q = $this->DB->prepare(
@ -116,7 +138,12 @@ class Database
}
public function createRateLimit($fingerPrintInfo): void
/**
* Creates a new row in the database with the information provided
*
* @param $fingerPrintInfo array
*/
public function createRateLimit(array $fingerPrintInfo): void
{
$q = $this->DB->prepare(
'INSERT INTO timestamp (iphash, files, time)' .
@ -129,7 +156,14 @@ class Database
$q->execute();
}
public function updateRateLimit($fCount, $iStamp, $fingerPrintInfo): void
/**
* 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 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
{
if ($iStamp) {
$q = $this->DB->prepare(
@ -149,7 +183,15 @@ class Database
public function checkRateLimit($fingerPrintInfo): bool
/**
* 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.
*/
public function checkRateLimit(array $fingerPrintInfo): bool
{
$q = $this->DB->prepare(
'SELECT files, time, iphash, COUNT(*) AS count FROM ratelimit WHERE iphash = (:iphash)'

View File

@ -25,7 +25,12 @@ class Response
{
public mixed $type;
public function __construct($response_type = "json")
/**
* Takes a string as an argument and sets the header to the appropriate content type
*
* @param $response_type string The type of response you want to return. Valid options are: csv, html, json, text.
*/
public function __construct(string $response_type = "json")
{
switch ($response_type) {
case 'csv':
@ -56,7 +61,13 @@ class Response
}
}
public function error($code, $desc): void
/**
* Returns a string based on the type of response requested
*
* @param $code mixed The HTTP status code to return.
* @param $desc string The description of the error.
*/
public function error(mixed $code, string $desc): void
{
$response = match ($this->type) {
'csv' => $this->csvError($desc),
@ -68,17 +79,34 @@ class Response
echo $response;
}
private static function csvError($description): string
/* Returning a string that contains the error message. */
private static function csvError(string $description): string
{
return '"error"' . "\r\n" . "\"$description\"" . "\r\n";
}
private static function htmlError($code, $description): string
/**
* Returns a string containing an HTML paragraph element with the error code and description
*
* @param $code int|string The error code.
* @param $description string The description of the error.
*
* @return string A string.
*/
private static function htmlError(int|string $code, string $description): string
{
return '<p>ERROR: (' . $code . ') ' . $description . '</p>';
}
private static function jsonError($code, $description): bool|string
/**
* Returns a JSON string with the error code and description
*
* @param $code int|string The error code.
* @param $description string The description of the error.
*
* @return bool|string A JSON string
*/
private static function jsonError(int|string $code, string $description): bool|string
{
return json_encode([
'success' => false,
@ -88,12 +116,27 @@ class Response
}
private static function textError($code, $description): string
/**
* Returns a string that contains the error code and description
*
* @param $code int|string The error code.
* @param $description string The description of the error.
*
* @return string A string with the error code and description.
*/
private static function textError(int|string $code, string $description): string
{
return 'ERROR: (' . $code . ') ' . $description;
}
public function send($files): void
/**
* "If the type is csv, then call the csvSuccess function, if the type is html, then call the htmlSuccess function, etc."
*
* The `match` keyword is a new feature in PHP 8. It's a lot like a switch statement, but it's more powerful
*
* @param $files array An array of file objects.
*/
public function send(array $files): void
{
$response = match ($this->type) {
'csv' => $this->csvSuccess($files),
@ -106,7 +149,14 @@ class Response
echo $response;
}
private static function csvSuccess($files): string
/**
* Takes an array of files and returns a CSV string
*
* @param $files array An array of files that have been uploaded.
*
* @return string A string of the files in the array.
*/
private static function csvSuccess(array $files): string
{
$result = '"name","url","hash","size"' . "\r\n";
foreach ($files as $file) {
@ -119,7 +169,14 @@ class Response
return $result;
}
private static function htmlSuccess($files): string
/**
* Takes an array of files and returns a string of HTML links
*
* @param $files array An array of files to be uploaded.
*
* @return string the result of the foreach loop.
*/
private static function htmlSuccess(array $files): string
{
$result = '';
@ -130,7 +187,14 @@ class Response
return $result;
}
private static function jsonSuccess($files): bool|string
/**
* Returns a JSON string that contains a success message and the files that were uploaded
*
* @param $files array The files to be uploaded.
*
* @return bool|string A JSON string
*/
private static function jsonSuccess(array $files): bool|string
{
return json_encode([
'success' => true,
@ -138,7 +202,14 @@ class Response
], JSON_PRETTY_PRINT);
}
private static function textSuccess($files): string
/**
* Takes an array of files and returns a string of URLs
*
* @param $files array The files to be uploaded.
*
* @return string the url of the file.
*/
private static function textSuccess(array $files): string
{
$result = '';

View File

@ -28,12 +28,16 @@ class Upload extends Response
public array $FILE_INFO;
public array $fingerPrintInfo;
private mixed $Connector;
/**
* @throws Exception
* 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($files): array
public function reFiles(array $files): array
{
$this->Connector = new Connector();
$this->Connector->setDB($this->Connector->DB);
@ -61,7 +65,34 @@ class Upload extends Response
}
return $result;
}
public function diverseArray($files): array
/**
* Takes an array of arrays and returns an array of arrays with the keys and values swapped
*
* @param $files array an array of arrays
*
* @return array ```
* array:2 [
* 0 => array:2 [
* 'TEMP_NAME' => 'example'
* 'NAME' => 'example'
* 'SIZE' => 'example'
* 'SHA1' => 'example'
* 'EXTENSION' => 'example'
* 'MIME' => 'example'
*
* ]
* 1 => array:2 [
* 'TEMP_NAME' => 'example'
* 'NAME' => 'example'
* 'SIZE' => 'example'
* 'SHA1' => 'example'
* 'EXTENSION' => 'example'
* 'MIME' => 'example'
* ]
* ]
* ```
*/
public function diverseArray(array $files): array
{
$result = [];
foreach ($files as $key1 => $value1) {
@ -71,9 +102,12 @@ class Upload extends Response
}
return $result;
}
/**
* @throws Exception
* 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.
* @throws \Exception
*/
public function uploadFile(): array
{
@ -123,26 +157,52 @@ class Upload extends Response
'size' => $this->FILE_INFO['SIZE']
];
}
public function fingerPrint($files_amount): void
/**
* 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
{
$this->fingerPrintInfo = [
'timestamp' => time(),
'useragent' => $_SERVER['HTTP_USER_AGENT'],
'ip' => $_SERVER['REMOTE_ADDR'],
'ip_hash' => hash('sha1', $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']),
'files_amount' => $files_amount
];
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
$USER_AGENT = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_ENCODED);
$this->fingerPrintInfo = [
'timestamp' => time(),
'useragent' => $USER_AGENT,
'ip' => $_SERVER['REMOTE_ADDR'],
'ip_hash' => hash('sha1', $_SERVER['REMOTE_ADDR'] . $USER_AGENT),
'files_amount' => $files_amount
];
} else {
throw new Exception('Invalid user agent.', 500);
}
}
public function fileMIME($file): string
/**
* Returns the MIME type of a file
*
* @param $file array The file to be checked.
*
* @return string The MIME type of the file.
*/
public function fileMIME(array $file): string
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
return finfo_file($finfo, $file['tmp_name']);
$FILE_INFO = finfo_open(FILEINFO_MIME_TYPE);
return finfo_file($FILE_INFO, $file['tmp_name']);
}
public function fileExtension($file): ?string
/**
* 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.
*/
public function fileExtension(array $file): ?string
{
$extension = explode('.', $file['name']);
if (substr_count($file['name'], '.') > 0) {
@ -151,10 +211,11 @@ class Upload extends Response
return null;
}
}
/**
* @throws Exception
* > Check if the file's MIME type is in the blacklist
*
* @throws \Exception
*/
public function checkMimeBlacklist(): void
{
@ -162,12 +223,11 @@ class Upload extends Response
throw new Exception('Filetype not allowed.', 415);
}
}
/**
* Check if file extension is blacklisted
* if it does throw an exception.
* > Check if the file extension is in the blacklist
*
* @throws Exception
* @throws \Exception
*/
public function checkExtensionBlacklist(): void
{
@ -175,14 +235,19 @@ class Upload extends Response
throw new Exception('Filetype not allowed.', 415);
}
}
/**
* @throws Exception
* 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.
*
* @return string A string
* @throws \Exception
*/
public function generateName($extension, $hash): string
public function generateName(string $extension, string $hash): string
{
$a = $this->Connector->antiDupe($hash);
if ($a === true) {
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);
@ -194,13 +259,13 @@ class Upload extends Response
[mt_rand(0, strlen($this->Connector->CONFIG['ID_CHARSET']))];
}
if (!is_null($extension)) {
if (!empty($extension)) {
$NEW_NAME .= '.' . $extension;
}
} while ($this->Connector->dbCheckNameExists($NEW_NAME) > 0);
return $NEW_NAME;
} else {
return $a;
return $this->Connector->antiDupe($hash);
}
}
}

View File

@ -1,53 +1,61 @@
<?php
/**
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Pomf\Uguu;
use Exception;
use Pomf\Uguu\Classes\Response;
class UploadGateway extends Classes\Upload
{
/**
* @throws Exception
* Uguu
*
* @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
*
* 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
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
public function handleFile($output, $files)
namespace Pomf\Uguu;
use Exception;
use Pomf\Uguu\Classes\Response;
class UploadGateway extends Classes\Upload
{
$type = $output ?? 'json';
$response = (new Response($type));
if (isset($_FILES['files'])) {
$files = $this->reFiles($files);
try {
$this->fingerPrint(count($files));
foreach ($files as $ignored) {
$res[] = $this->uploadFile();
/**
* It handles the file uploads.
*
* @param $output mixed The output format of the response.
* @param $files mixed The name of the file input field.
*
* @throws \Exception
*/
public function handleFile(mixed $output, mixed $files)
{
$type = 'json' ?? $output;
$response = (new Response($type));
if (!empty($_FILES['files'])) {
$files = $this->reFiles($files);
try {
$this->fingerPrint(count($files));
$res = [];
foreach ($files as $ignored) {
$res[] = $this->uploadFile();
}
if (!empty($res)) {
$response->send($res);
}
}
if (isset($res)) {
$response->send($res);
catch (Exception $e) {
$response->error($e->getCode(), $e->getMessage());
}
} catch (Exception $e) {
$response->error($e->getCode(), $e->getMessage());
} else {
$response->error(400, 'No input file(s)');
}
} else {
$response->error(400, 'No input file(s)');
}
}
}
}

View File

@ -25,9 +25,8 @@ require_once __DIR__ . '/../vendor/autoload.php';
use Pomf\Uguu\UploadGateway;
$Upload = new UploadGateway();
try {
$Upload->handleFile($_GET['output'], $_FILES['files']);
(new UploadGateway())->handleFile($_GET['output'], $_FILES['files']);
} catch (Exception $e) {
throw new Exception($e->getMessage(), 500);
}