- Slim::storeCroppedImage() vertraute dem vom Client gemeldeten Typ und uebernahm die Endung aus dem Dateinamen; "shell.php" mit Typ image/png landete als .php im public-Disk. Jetzt entscheidet getimagesizefromstring() ueber die Bytes, die Endung kommt aus dem geprueften Typ. - Foto loeschen war ein GET-Link und liess sich per fremdem <img src> ausloesen (CSRF); jetzt POST-Formular mit Token. - Ohne Konto (users.account_id) bricht Upload/Loeschen mit 404 ab statt mit einem Fatal. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
345 lines
11 KiB
PHP
345 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
abstract class SlimStatus
|
|
{
|
|
const FAILURE = 'failure';
|
|
|
|
const SUCCESS = 'success';
|
|
}
|
|
|
|
class Slim
|
|
{
|
|
/** Maximale Länge des bereinigten Dateinamens inklusive Endung. */
|
|
private const MAX_FILENAME_LENGTH = 33;
|
|
|
|
/**
|
|
* Speichert ein Slim-Cropper-Upload (Base64-Payload aus getImages()) im
|
|
* public-Disk und liefert Dateiname + Metadaten — gemeinsame Logik für
|
|
* Shop- und Profilfoto-Upload. Null, wenn der Inhalt kein JPEG/PNG ist.
|
|
*
|
|
* Zwei Dinge sind hier sicherheitsrelevant und dürfen nicht vereinfacht
|
|
* werden:
|
|
*
|
|
* 1. `output.type` ist eine ANGABE DES CLIENTS aus dem geposteten JSON, kein
|
|
* geprüfter Inhaltstyp. Massgeblich ist deshalb, was
|
|
* getimagesizefromstring() in den Bytes findet.
|
|
* 2. Die Endung kommt IMMER aus dem geprüften Typ, nie aus dem übermittelten
|
|
* Dateinamen: {@see sanitizeFileName()} lässt jede Endung stehen, ein
|
|
* "foto.php" landete sonst als ausführbarer Dateiname im public-Disk.
|
|
*
|
|
* @param array $image Ein Eintrag aus {@see getImages()}
|
|
* @return array{filename: string, originalname: string, ext: string, mime: string, size: mixed}|null
|
|
*/
|
|
public static function storeCroppedImage(array $image, string $directory): ?array
|
|
{
|
|
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png'];
|
|
|
|
$declaredType = $image['output']['type'] ?? null;
|
|
$data = $image['output']['data'] ?? null;
|
|
|
|
if (! is_string($declaredType) || ! isset($allowed[$declaredType]) || ! is_string($data) || $data === '') {
|
|
return null;
|
|
}
|
|
|
|
$info = @getimagesizefromstring($data);
|
|
$mime = is_array($info) ? ($info['mime'] ?? null) : null;
|
|
|
|
if (! is_string($mime) || ! isset($allowed[$mime])) {
|
|
return null;
|
|
}
|
|
|
|
$ext = $allowed[$mime];
|
|
$base = Slim::sanitizeFileName(pathinfo((string) ($image['output']['name'] ?? ''), PATHINFO_FILENAME));
|
|
$name = uniqid().'_'.$base.'.'.$ext;
|
|
|
|
\Storage::disk('public')->put(rtrim($directory, '/').'/'.$name, $data);
|
|
|
|
return [
|
|
'filename' => $name,
|
|
'originalname' => $image['output']['name'] ?? '',
|
|
'ext' => $ext,
|
|
'mime' => $mime,
|
|
'size' => $image['input']['size'] ?? null,
|
|
];
|
|
}
|
|
|
|
public static function getImages($inputName = 'slim')
|
|
{
|
|
|
|
$values = Slim::getPostData($inputName);
|
|
|
|
// test for errors
|
|
if ($values === false) {
|
|
return false;
|
|
}
|
|
|
|
// determine if contains multiple input values, if is singular, put in array
|
|
$data = [];
|
|
if (! is_array($values)) {
|
|
$values = [$values];
|
|
}
|
|
|
|
// handle all posted fields
|
|
foreach ($values as $value) {
|
|
$inputValue = Slim::parseInput($value);
|
|
if ($inputValue) {
|
|
array_push($data, $inputValue);
|
|
}
|
|
}
|
|
|
|
// return the data collected from the fields
|
|
return $data;
|
|
|
|
}
|
|
|
|
// $value should be in JSON format
|
|
private static function parseInput($value)
|
|
{
|
|
|
|
// if no json received, exit, don't handle empty input values.
|
|
if (empty($value)) {
|
|
return null;
|
|
}
|
|
|
|
// If magic quotes enabled
|
|
// Magic quotes were removed in PHP 5.4, no need to check in PHP 8.2
|
|
|
|
// The data is posted as a JSON String so to be used it needs to be deserialized first
|
|
$data = json_decode($value);
|
|
|
|
// shortcut
|
|
$input = null;
|
|
$actions = null;
|
|
$output = null;
|
|
$meta = null;
|
|
|
|
if (isset($data->input)) {
|
|
|
|
$inputData = null;
|
|
if (isset($data->input->image)) {
|
|
$inputData = Slim::getBase64Data($data->input->image);
|
|
} elseif (isset($data->input->field)) {
|
|
$filename = $_FILES[$data->input->field]['tmp_name'];
|
|
if ($filename) {
|
|
$inputData = file_get_contents($filename);
|
|
}
|
|
}
|
|
|
|
$input = [
|
|
'data' => $inputData,
|
|
'name' => $data->input->name,
|
|
'type' => $data->input->type,
|
|
'size' => $data->input->size,
|
|
'width' => $data->input->width,
|
|
'height' => $data->input->height,
|
|
];
|
|
|
|
}
|
|
|
|
if (isset($data->output)) {
|
|
|
|
$outputData = null;
|
|
if (isset($data->output->image)) {
|
|
$outputData = Slim::getBase64Data($data->output->image);
|
|
} elseif (isset($data->output->field)) {
|
|
$filename = $_FILES[$data->output->field]['tmp_name'];
|
|
if ($filename) {
|
|
$outputData = file_get_contents($filename);
|
|
}
|
|
}
|
|
|
|
$output = [
|
|
'data' => $outputData,
|
|
'name' => $data->output->name,
|
|
'type' => $data->output->type,
|
|
'width' => $data->output->width,
|
|
'height' => $data->output->height,
|
|
];
|
|
}
|
|
|
|
if (isset($data->actions)) {
|
|
$actions = [
|
|
'crop' => $data->actions->crop ? [
|
|
'x' => $data->actions->crop->x,
|
|
'y' => $data->actions->crop->y,
|
|
'width' => $data->actions->crop->width,
|
|
'height' => $data->actions->crop->height,
|
|
'type' => $data->actions->crop->type,
|
|
] : null,
|
|
'size' => $data->actions->size ? [
|
|
'width' => $data->actions->size->width,
|
|
'height' => $data->actions->size->height,
|
|
] : null,
|
|
'rotation' => $data->actions->rotation,
|
|
'filters' => $data->actions->filters ? [
|
|
'sharpen' => $data->actions->filters->sharpen,
|
|
] : null,
|
|
];
|
|
}
|
|
|
|
if (isset($data->meta)) {
|
|
$meta = $data->meta;
|
|
}
|
|
|
|
// We've sanitized the base64data and will now return the clean file object
|
|
return [
|
|
'input' => $input,
|
|
'output' => $output,
|
|
'actions' => $actions,
|
|
'meta' => $meta,
|
|
];
|
|
}
|
|
|
|
// $path should have trailing slash
|
|
public static function saveFile($data, $name, $path = 'tmp/', $uid = true)
|
|
{
|
|
|
|
// Add trailing slash if omitted
|
|
if (substr($path, -1) !== '/') {
|
|
$path .= '/';
|
|
}
|
|
|
|
// Test if directory already exists
|
|
if (! is_dir($path)) {
|
|
mkdir($path, 0755, true);
|
|
}
|
|
|
|
// Sanitize characters in file name
|
|
$name = Slim::sanitizeFileName($name);
|
|
|
|
// Let's put a unique id in front of the filename so we don't accidentally overwrite other files
|
|
if ($uid) {
|
|
$name = uniqid().'_'.$name;
|
|
}
|
|
|
|
// Add name to path, we need the full path including the name to save the file
|
|
$path = $path.$name;
|
|
|
|
// store the file
|
|
Slim::save($data, $path);
|
|
|
|
// return the files new name and location
|
|
return [
|
|
'name' => $name,
|
|
'path' => $path,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Get data from remote URL
|
|
*
|
|
* @return string
|
|
*/
|
|
public static function fetchURL($url, $maxFileSize)
|
|
{
|
|
if (! ini_get('allow_url_fopen')) {
|
|
return null;
|
|
}
|
|
$content = null;
|
|
try {
|
|
$content = @file_get_contents($url, false, null, 0, $maxFileSize);
|
|
} catch (Exception $e) {
|
|
return false;
|
|
}
|
|
|
|
return $content;
|
|
}
|
|
|
|
public static function outputJSON($data)
|
|
{
|
|
header('Content-Type: application/json');
|
|
echo json_encode($data);
|
|
}
|
|
|
|
/**
|
|
* http://stackoverflow.com/a/2021729
|
|
* Remove anything which isn't a word, whitespace, number
|
|
* or any of the following characters -_~,;[]().
|
|
* If you don't need to handle multi-byte characters
|
|
* you can use preg_replace rather than mb_ereg_replace
|
|
*
|
|
* @return string
|
|
*/
|
|
/**
|
|
* Bereinigt einen hochgeladenen Dateinamen für die Ablage im public-Disk.
|
|
*
|
|
* Kürzt bei Bedarf am ENDE des Namens und behält die Endung — die frühere
|
|
* Fassung schnitt mit substr($str, -33) vorne ab, wodurch aus
|
|
* "Bildschirmfoto ....png" ein "ldschirmfoto ....png" wurde. Leerzeichen
|
|
* werden zu "-", damit die Datei ohne Encoding in einer URL stehen kann.
|
|
*/
|
|
public static function sanitizeFileName($str)
|
|
{
|
|
// Unicode-Trennzeichen (z. B. geschütztes Leerzeichen in macOS-Screenshot-
|
|
// Namen) zuerst zu einem normalen Leerzeichen machen. Der ASCII-Filter
|
|
// darunter arbeitet byteweise und würde sie sonst spurlos entfernen,
|
|
// sodass Wörter zusammenkleben. Bei ungültigem UTF-8 liefert preg_replace
|
|
// null — dann bleibt der Originalwert stehen.
|
|
$str = preg_replace('/[\p{Z}\s]+/u', ' ', (string) $str) ?? $str;
|
|
|
|
// Basic clean up
|
|
$str = preg_replace('([^\w\s\d\-_~,;\[\]\(\).])', '', $str);
|
|
// Remove any runs of periods
|
|
$str = preg_replace('([\.]{2,})', '', $str);
|
|
// Whitespace (auch geschützte Leerzeichen aus macOS-Screenshots) zu "-"
|
|
$str = preg_replace('(\s+)', '-', $str);
|
|
$str = trim($str, '-');
|
|
|
|
$extension = pathinfo($str, PATHINFO_EXTENSION);
|
|
$suffix = $extension !== '' ? '.'.$extension : '';
|
|
$base = $suffix !== '' ? substr($str, 0, -strlen($suffix)) : $str;
|
|
|
|
$maxBase = max(1, self::MAX_FILENAME_LENGTH - strlen($suffix));
|
|
if (strlen($base) > $maxBase) {
|
|
$base = rtrim(substr($base, 0, $maxBase), '-.');
|
|
}
|
|
|
|
return ($base === '' ? 'datei' : $base).$suffix;
|
|
}
|
|
|
|
/**
|
|
* Gets the posted data from the POST or FILES object. If was using Slim to upload it will be in POST (as posted with hidden field) if not enhanced with Slim it'll be in FILES.
|
|
*
|
|
* @return array|bool
|
|
*/
|
|
private static function getPostData($inputName)
|
|
{
|
|
|
|
$values = [];
|
|
|
|
if (isset($_POST[$inputName])) {
|
|
$values = $_POST[$inputName];
|
|
} elseif (isset($_FILES[$inputName])) {
|
|
// Slim was not used to upload this file
|
|
return false;
|
|
}
|
|
|
|
return $values;
|
|
}
|
|
|
|
/**
|
|
* Saves the data to a given location
|
|
*
|
|
* @return bool
|
|
*/
|
|
private static function save($data, $path)
|
|
{
|
|
if (! file_put_contents($path, $data)) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Strips the "data:image..." part of the base64 data string so PHP can save the string as a file
|
|
*
|
|
* @return string
|
|
*/
|
|
private static function getBase64Data($data)
|
|
{
|
|
return base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
|
|
}
|
|
}
|