Files
cimacrestyle/public/uploadphotofile.php
2026-08-02 13:53:56 +02:00

239 lines
6.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
include('include/headscript.php');
ini_set('display_errors', 0);
error_reporting(E_ALL);
// =======================
// Language messages
// =======================
$lang = $_SESSION['langselect'] ?? 'it';
$messages = [
'it' => [
'missing_trf' => 'ID TRF mancante.',
'no_image' => 'Nessuna immagine selezionata.',
'upload_error' => 'Errore durante il caricamento.',
'too_large' => 'Immagine troppo grande. Dimensione massima consentita: 8 MB.',
'invalid_extension' => 'Estensione non valida. Sono consentiti solo JPG, JPEG e PNG.',
'invalid_type' => 'Tipo immagine non valido. Sono consentiti solo JPG, JPEG e PNG.',
'invalid_image' => 'File immagine non valido.',
'unsupported_type' => 'Tipo immagine non supportato.',
'process_error' => 'Impossibile elaborare limmagine.',
'save_error' => 'Impossibile salvare limmagine ridimensionata.'
],
'en' => [
'missing_trf' => 'Missing TRF ID.',
'no_image' => 'No image selected.',
'upload_error' => 'Upload error.',
'too_large' => 'Image too large. Maximum allowed size is 8 MB.',
'invalid_extension' => 'Invalid file extension. Only JPG, JPEG and PNG are allowed.',
'invalid_type' => 'Invalid image type. Only JPG, JPEG and PNG are allowed.',
'invalid_image' => 'Invalid image file.',
'unsupported_type' => 'Unsupported image type.',
'process_error' => 'Unable to process image.',
'save_error' => 'Unable to save resized image.'
]
];
$msg = $messages[$lang] ?? $messages['it'];
// =======================
// Upload settings
// =======================
$targetDir = "uploaddocuments/";
$targetDirPath = __DIR__ . "/uploaddocuments/";
$maxUploadSize = 8 * 1024 * 1024; // 8 MB
$maxWidth = 1600;
$maxHeight = 1600;
$jpgQuality = 82;
$allowedExtensions = ['jpg', 'jpeg', 'png'];
$allowedMimeTypes = ['image/jpeg', 'image/png'];
// =======================
// Basic checks
// =======================
if (empty($_POST["idtrf"])) {
http_response_code(400);
echo $msg['missing_trf'];
exit;
}
$idtrf = intval($_POST["idtrf"]);
if (empty($_FILES['docphotoone']) || empty($_FILES['docphotoone']['name'][0])) {
http_response_code(400);
echo $msg['no_image'];
exit;
}
if (!is_dir($targetDirPath)) {
mkdir($targetDirPath, 0755, true);
}
// This upload manages only photo one
$key = 0;
$imageName = $_FILES['docphotoone']['name'][$key];
$tmpName = $_FILES['docphotoone']['tmp_name'][$key];
$size = $_FILES['docphotoone']['size'][$key];
$error = $_FILES['docphotoone']['error'][$key];
if ($error !== UPLOAD_ERR_OK) {
http_response_code(400);
echo $msg['upload_error'];
exit;
}
if ($size > $maxUploadSize) {
http_response_code(400);
echo $msg['too_large'];
exit;
}
// =======================
// Extension check
// =======================
$extension = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));
if (!in_array($extension, $allowedExtensions)) {
http_response_code(400);
echo $msg['invalid_extension'];
exit;
}
// =======================
// Real MIME check
// =======================
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $tmpName);
finfo_close($finfo);
if (!in_array($mimeType, $allowedMimeTypes)) {
http_response_code(400);
echo $msg['invalid_type'];
exit;
}
// =======================
// Image validation
// =======================
$imageInfo = getimagesize($tmpName);
if ($imageInfo === false) {
http_response_code(400);
echo $msg['invalid_image'];
exit;
}
$originalWidth = $imageInfo[0];
$originalHeight = $imageInfo[1];
// =======================
// Create source image
// =======================
if ($mimeType === 'image/jpeg') {
$sourceImage = imagecreatefromjpeg($tmpName);
} elseif ($mimeType === 'image/png') {
$sourceImage = imagecreatefrompng($tmpName);
} else {
http_response_code(400);
echo $msg['unsupported_type'];
exit;
}
if (!$sourceImage) {
http_response_code(400);
echo $msg['process_error'];
exit;
}
// =======================
// Resize calculation
// =======================
$ratio = min($maxWidth / $originalWidth, $maxHeight / $originalHeight, 1);
$newWidth = (int)($originalWidth * $ratio);
$newHeight = (int)($originalHeight * $ratio);
// =======================
// Create resized image
// =======================
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
// White background for PNG transparency
$white = imagecolorallocate($resizedImage, 255, 255, 255);
imagefill($resizedImage, 0, 0, $white);
imagecopyresampled(
$resizedImage,
$sourceImage,
0,
0,
0,
0,
$newWidth,
$newHeight,
$originalWidth,
$originalHeight
);
// =======================
// New filename
// =======================
$code = time();
$fileName = $idtrf . '-' . $code . '-photoone.jpg';
$targetFilePath = $targetDirPath . $fileName;
// =======================
// Save as JPG
// =======================
$saved = imagejpeg($resizedImage, $targetFilePath, $jpgQuality);
imagedestroy($sourceImage);
imagedestroy($resizedImage);
if (!$saved || !file_exists($targetFilePath)) {
http_response_code(500);
echo $msg['save_error'];
exit;
}
// =======================
// Delete previous photo one if exists
// =======================
$oldPhoto = "";
$oldPhotoQuery = new WA_MySQLi_RS("oldPhotoOneQuery", $cmctrfdb, 1);
$oldPhotoQuery->setQuery("SELECT photoone FROM `trf-details` WHERE idtrfdetails = $idtrf");
$oldPhotoQuery->execute();
$oldPhoto = $oldPhotoQuery->getColumnVal("photoone");
if (!empty($oldPhoto)) {
$oldPhotoPath = $targetDirPath . basename($oldPhoto);
if (file_exists($oldPhotoPath) && $oldPhoto !== $fileName) {
unlink($oldPhotoPath);
}
}
// =======================
// Update database
// =======================
$UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
$UpdateQuery->Action = "update";
$UpdateQuery->Table = "`trf-details`";
$UpdateQuery->bindColumn("photoone", "s", "$fileName", "WA_DEFAULT");
$UpdateQuery->addFilter("idtrfdetails", "=", "i", "" . ($idtrf) . "");
$UpdateQuery->execute();
// Important: no redirect because this file is called by AJAX
// =======================
// Return image HTML
// =======================
?>
<img src="<?php echo $targetDir . htmlspecialchars($fileName); ?>" alt="" width="200">