Articles: finish admin refactor, uploads hardening, and attachment sorting (0.262)

This commit is contained in:
2026-02-13 09:00:24 +01:00
parent e984548516
commit 3e1f417ef3
31 changed files with 1951 additions and 1512 deletions

View File

@@ -12,10 +12,21 @@ session_start();
/* połączenie z bazą ustawić wg własnych preferencji */
require_once dirname( __FILE__ ) . '/../../config.php';
require_once dirname( __FILE__ ) . '/../../autoload/class.S.php';
require_once dirname( __FILE__ ) . '/../../autoload/admin/factory/class.Articles.php';
require_once dirname( __FILE__ ) . '/../../autoload/admin/factory/class.Pages.php';
require_once dirname( __FILE__ ) . '/../../autoload/admin/factory/class.ShopCategory.php';
require_once dirname( __FILE__ ) . '/../../autoload/admin/factory/class.ShopProduct.php';
$legacyFactoryFiles = [
'/../../autoload/admin/factory/class.Articles.php',
'/../../autoload/admin/factory/class.Pages.php',
'/../../autoload/admin/factory/class.ShopCategory.php',
'/../../autoload/admin/factory/class.ShopProduct.php',
];
foreach ( $legacyFactoryFiles as $legacyFactoryFile )
{
$legacyFactoryPath = dirname( __FILE__ ) . $legacyFactoryFile;
if ( file_exists( $legacyFactoryPath ) )
require_once $legacyFactoryPath;
}
require_once dirname( __FILE__ ) . '/../../autoload/shop/class.Product.php';
require_once dirname( __FILE__ ) . '/../../libraries/medoo/medoo.php';
@@ -35,4 +46,4 @@ $mdb = new medoo( [
'username' => $database['user'],
'password' => $database['password'],
'charset' => 'utf8'
] );
] );

View File

@@ -1,154 +1,53 @@
<?php
require_once '../../config.php';
require_once '../medoo/medoo.php';
date_default_timezone_set( 'Europe/Warsaw' );
session_start();
require_once 'upload-common.php';
$upload_token = $_REQUEST['upload_token'] ?? '';
if ( !isset( $_SESSION['upload_tokens'][$upload_token] ) ) {
http_response_code(403);
echo json_encode( ['error' => 'Brak tokenu uploadu'] );
exit;
plupload_bootstrap();
plupload_require_post();
$userId = plupload_require_admin_user();
plupload_validate_token($userId);
$fileDir = '/upload/article_files/tmp';
$targetDir = '../..' . $fileDir;
plupload_ensure_target_dir($targetDir);
list($chunk, $chunks) = plupload_get_chunks();
list($fileName, $extension, $filePath, $partPath) = plupload_build_target_paths(
$targetDir,
$_REQUEST['name'] ?? '',
null,
[
'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phar',
'cgi', 'pl', 'py', 'rb',
'asp', 'aspx', 'jsp',
'js', 'mjs', 'vbs', 'wsf', 'hta',
'sh', 'bash', 'zsh', 'ps1', 'bat', 'cmd', 'com',
'exe', 'msi', 'scr', 'dll', 'jar',
]
);
plupload_cleanup_stale_parts($targetDir, $partPath, 5 * 3600);
plupload_write_chunk_to_part($partPath, $chunk);
plupload_assert_size_limit($partPath, 50 * 1024 * 1024, 'Plik przekracza dozwolony rozmiar (50 MB).');
$fileId = null;
$responseFileName = $fileName;
if (plupload_is_last_chunk($chunk, $chunks)) {
plupload_finalize_part($partPath, $filePath);
$mdb = plupload_create_medoo($database);
$mdb->insert('pp_articles_files', [
'article_id' => null,
'src' => substr($filePath, 5),
]);
$fileId = (int)$mdb->id();
$responseFileName = basename($filePath);
}
$tokenData = $_SESSION['upload_tokens'][$upload_token];
if ( $tokenData['expires'] < time() ) {
unset( $_SESSION['upload_tokens'][$upload_token] );
http_response_code(403);
echo json_encode( ['error' => 'Token wygasł'] );
exit;
}
plupload_send_success([
'file_name' => $responseFileName,
'file_id' => $fileId,
]);
$mdb = new medoo( [
'database_type' => 'mysql',
'database_name' => $database['name'],
'server' => $database['host'],
'username' => $database['user'],
'password' => $database['password'],
'charset' => 'utf8'
] );
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header( "Cache-Control: no-store, no-cache, must-revalidate" );
header( "Cache-Control: post-check=0, pre-check=0", false );
header( "Pragma: no-cache" );
$fileDir = '/upload/article_files/tmp';
$targetDir = '../..' . $fileDir;
if ( !is_dir( $targetDir ) )
mkdir( $targetDir, 0755, true );
$cleanupTargetDir = true;
$maxFileAge = 5 * 3600;
$chunk = isset( $_REQUEST["chunk"] ) ? intval( $_REQUEST["chunk"] ) : 0;
$chunks = isset( $_REQUEST["chunks"] ) ? intval( $_REQUEST["chunks"] ) : 0;
$fileName = isset( $_REQUEST["name"] ) ? $_REQUEST["name"] : '';
$fileName = preg_replace( '/[^\w\._]+/', '-', $fileName );
if ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName ) )
{
$ext = strrpos( $fileName, '.' );
$fileName_a = substr( $fileName, 0, $ext );
$fileName_b = substr( $fileName, $ext );
$count = 1;
while ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b ) )
$count++;
$fileName = $fileName_a . '_' . $count . $fileName_b;
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
if ( $cleanupTargetDir && is_dir( $targetDir ) && ( $dir = opendir( $targetDir ) ) )
{
while ( ( $file = readdir( $dir ) ) !== false )
{
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
if ( preg_match( '/\.part$/', $file ) && ( filemtime( $tmpfilePath ) < time() - $maxFileAge ) && ( $tmpfilePath != "{$filePath}.part" ) ) {
@unlink( $tmpfilePath );
}
}
closedir($dir);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}' );
if ( isset( $_SERVER["HTTP_CONTENT_TYPE"] ) )
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
if ( isset( $_SERVER["CONTENT_TYPE"] ) )
$contentType = $_SERVER["CONTENT_TYPE"];
if ( strpos( $contentType, "multipart" ) !== false )
{
if ( isset( $_FILES['file']['tmp_name'] ) && is_uploaded_file( $_FILES['file']['tmp_name'] ) )
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( $_FILES['file']['tmp_name'], "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite($out, $buff);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
@unlink( $_FILES['file']['tmp_name'] );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}' );
}
else
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( "php://input", "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite( $out, $buff );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
if ( !$chunks || $chunk == $chunks - 1 )
{
rename( "{$filePath}.part", $filePath );
$mdb -> insert( 'pp_articles_files', [
'article_id' => null,
'src' => substr( $filePath, 5, strlen( $filePath ) )
] );
$file_id = $mdb -> id();
$file_name = explode( '/', $filePath );
$file_name = $file_name[ count( $file_name ) - 1 ];
}
die( '{"jsonrpc" : "2.0", "result" : null, "id" : "id", "file_name" : "' . $file_name . '", "file_id" : "' . $file_id . '"}' );
?>

View File

@@ -1,153 +1,61 @@
<?php
require_once '../../config.php';
require_once '../medoo/medoo.php';
date_default_timezone_set( 'Europe/Warsaw' );
session_start();
require_once 'upload-common.php';
$upload_token = $_REQUEST['upload_token'] ?? '';
if ( !isset( $_SESSION['upload_tokens'][$upload_token] ) ) {
http_response_code(403);
echo json_encode( ['error' => 'Brak tokenu uploadu'] );
exit;
plupload_bootstrap();
plupload_require_post();
$userId = plupload_require_admin_user();
plupload_validate_token($userId);
$fileDir = '/upload/article_images/tmp';
$targetDir = '../..' . $fileDir;
plupload_ensure_target_dir($targetDir);
list($chunk, $chunks) = plupload_get_chunks();
list($fileName, $extension, $filePath, $partPath) = plupload_build_target_paths(
$targetDir,
$_REQUEST['name'] ?? '',
['jpg', 'jpeg', 'png', 'gif', 'webp'],
null
);
plupload_cleanup_stale_parts($targetDir, $partPath, 5 * 3600);
plupload_write_chunk_to_part($partPath, $chunk);
plupload_assert_size_limit($partPath, 20 * 1024 * 1024, 'Plik przekracza dozwolony rozmiar (20 MB).');
$imageId = null;
if (plupload_is_last_chunk($chunk, $chunks)) {
plupload_finalize_part($partPath, $filePath);
$mime = mime_content_type($filePath) ?: '';
$imageMeta = @getimagesize($filePath);
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$isValidImage = in_array($mime, $allowedMimeTypes, true)
&& is_array($imageMeta)
&& (int)($imageMeta[0] ?? 0) > 0
&& (int)($imageMeta[1] ?? 0) > 0;
if (!$isValidImage) {
@unlink($filePath);
plupload_send_error(400, 601, 'Plik nie jest prawidlowym obrazem.');
}
$mdb = plupload_create_medoo($database);
$order = (int)$mdb->max('pp_articles_images', 'o');
$articleId = (int)($_POST['article_id'] ?? 0);
$mdb->insert('pp_articles_images', [
'article_id' => $articleId > 0 ? $articleId : null,
'src' => substr($filePath, 5),
'o' => $order + 1,
]);
$imageId = (int)$mdb->id();
}
$tokenData = $_SESSION['upload_tokens'][$upload_token];
if ( $tokenData['expires'] < time() ) {
unset( $_SESSION['upload_tokens'][$upload_token] );
http_response_code(403);
echo json_encode( ['error' => 'Token wygasł'] );
exit;
}
plupload_send_success([
'data_link' => str_replace('../../', '', $filePath),
'image_id' => $imageId,
]);
$mdb = new medoo( [
'database_type' => 'mysql',
'database_name' => $database['name'],
'server' => $database['host'],
'username' => $database['user'],
'password' => $database['password'],
'charset' => 'utf8'
] );
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header( "Cache-Control: no-store, no-cache, must-revalidate" );
header( "Cache-Control: post-check=0, pre-check=0", false );
header( "Pragma: no-cache" );
$fileDir = '/upload/article_images/tmp';
$targetDir = '../..' . $fileDir;
if ( !is_dir( $targetDir ) )
mkdir( $targetDir, 0755, true );
$cleanupTargetDir = true;
$maxFileAge = 5 * 3600;
$chunk = isset( $_REQUEST["chunk"] ) ? intval( $_REQUEST["chunk"] ) : 0;
$chunks = isset( $_REQUEST["chunks"] ) ? intval( $_REQUEST["chunks"] ) : 0;
$fileName = isset( $_REQUEST["name"] ) ? $_REQUEST["name"] : '';
$fileName = preg_replace( '/[^\w\._]+/', '-', $fileName );
if ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName ) )
{
$ext = strrpos( $fileName, '.' );
$fileName_a = substr( $fileName, 0, $ext );
$fileName_b = substr( $fileName, $ext );
$count = 1;
while ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b ) )
$count++;
$fileName = $fileName_a . '_' . $count . $fileName_b;
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
if ( $cleanupTargetDir && is_dir( $targetDir ) && ( $dir = opendir( $targetDir ) ) )
{
while ( ( $file = readdir( $dir ) ) !== false )
{
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
if ( preg_match( '/\.part$/', $file ) && ( filemtime( $tmpfilePath ) < time() - $maxFileAge ) && ( $tmpfilePath != "{$filePath}.part" ) ) {
@unlink( $tmpfilePath );
}
}
closedir($dir);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}' );
if ( isset( $_SERVER["HTTP_CONTENT_TYPE"] ) )
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
if ( isset( $_SERVER["CONTENT_TYPE"] ) )
$contentType = $_SERVER["CONTENT_TYPE"];
if ( strpos( $contentType, "multipart" ) !== false )
{
if ( isset( $_FILES['file']['tmp_name'] ) && is_uploaded_file( $_FILES['file']['tmp_name'] ) )
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( $_FILES['file']['tmp_name'], "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite($out, $buff);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
@unlink( $_FILES['file']['tmp_name'] );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}' );
}
else
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( "php://input", "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite( $out, $buff );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
if ( !$chunks || $chunk == $chunks - 1 )
{
rename( "{$filePath}.part", $filePath );
$o = $mdb -> max( 'pp_articles_images', 'o' );
$mdb -> insert( 'pp_articles_images', [
'article_id' => $_POST['article_id'] ? $_POST['article_id'] : null,
'src' => substr( $filePath, 5, strlen( $filePath ) ),
'o' => ++$o
] );
$image_id = $mdb -> id();
}
die( '{"jsonrpc" : "2.0", "result" : null, "id" : "id", "data_link" : "' . str_replace( '../../', '', $filePath ) . '", "image_id" : "' . $image_id . '"}' );
?>

View File

@@ -0,0 +1,307 @@
<?php
if (!function_exists('plupload_send_error')) {
function plupload_send_error($httpCode, $code, $message)
{
http_response_code((int)$httpCode);
echo json_encode([
'jsonrpc' => '2.0',
'error' => [
'code' => (int)$code,
'message' => (string)$message,
],
'id' => 'id',
]);
exit;
}
}
if (!function_exists('plupload_bootstrap')) {
function plupload_bootstrap()
{
date_default_timezone_set('Europe/Warsaw');
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
header('Content-Type: application/json; charset=utf-8');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
}
}
if (!function_exists('plupload_require_post')) {
function plupload_require_post()
{
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
plupload_send_error(405, 405, 'Method not allowed.');
}
}
}
if (!function_exists('plupload_require_admin_user')) {
function plupload_require_admin_user()
{
$adminSession = isset($_SESSION['admin']) && $_SESSION['admin'] === true;
$userId = (int)($_SESSION['user']['id'] ?? 0);
if (!$adminSession || $userId <= 0) {
plupload_send_error(403, 403, 'Brak autoryzacji.');
}
$sessionOk = isset($_SESSION['check'], $_SESSION['ip'])
&& $_SESSION['check'] === true
&& $_SESSION['ip'] === ($_SERVER['REMOTE_ADDR'] ?? '');
if (!$sessionOk) {
plupload_send_error(403, 403, 'Nieprawidlowa sesja.');
}
return $userId;
}
}
if (!function_exists('plupload_validate_token')) {
function plupload_validate_token($userId)
{
$uploadToken = (string)($_REQUEST['upload_token'] ?? '');
if ($uploadToken === '' || !isset($_SESSION['upload_tokens'][$uploadToken])) {
plupload_send_error(403, 403, 'Brak tokenu uploadu.');
}
$tokenData = $_SESSION['upload_tokens'][$uploadToken];
$tokenUserId = (int)($tokenData['user_id'] ?? 0);
$tokenExpires = (int)($tokenData['expires'] ?? 0);
if ($tokenUserId <= 0 || $tokenUserId !== (int)$userId) {
plupload_send_error(403, 403, 'Token nie nalezy do aktualnego uzytkownika.');
}
if ($tokenExpires < time()) {
unset($_SESSION['upload_tokens'][$uploadToken]);
plupload_send_error(403, 403, 'Token wygasl.');
}
return [$uploadToken, $tokenData];
}
}
if (!function_exists('plupload_normalize_filename')) {
function plupload_normalize_filename($fileName)
{
$fileName = basename((string)$fileName);
$fileName = preg_replace('/[^\w\.-]+/', '-', $fileName);
$fileName = trim((string)$fileName, '.-');
if ($fileName === '') {
$fileName = 'file-' . bin2hex(random_bytes(8));
}
return strtolower($fileName);
}
}
if (!function_exists('plupload_ensure_target_dir')) {
function plupload_ensure_target_dir($targetDir)
{
if (!is_dir($targetDir) && !mkdir($targetDir, 0755, true)) {
plupload_send_error(500, 100, 'Failed to open temp directory.');
}
}
}
if (!function_exists('plupload_build_target_paths')) {
function plupload_build_target_paths($targetDir, $requestName, $allowedExtensions = null, $blockedExtensions = null, $maxNameLength = 180)
{
$fileName = plupload_normalize_filename((string)$requestName);
$extension = strtolower((string)pathinfo($fileName, PATHINFO_EXTENSION));
if (is_array($allowedExtensions)) {
if ($extension === '' || !in_array($extension, $allowedExtensions, true)) {
plupload_send_error(400, 601, 'Nieobslugiwane rozszerzenie pliku.');
}
}
if (is_array($blockedExtensions)) {
if ($extension !== '' && in_array($extension, $blockedExtensions, true)) {
plupload_send_error(400, 601, 'Rozszerzenie pliku jest zablokowane.');
}
}
if (strlen($fileName) > (int)$maxNameLength) {
$base = substr((string)pathinfo($fileName, PATHINFO_FILENAME), 0, 140);
$suffix = '-' . bin2hex(random_bytes(4));
$fileName = $base . $suffix . ($extension !== '' ? '.' . $extension : '');
}
if (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
$nameWithoutExt = (string)pathinfo($fileName, PATHINFO_FILENAME);
$extWithDot = $extension !== '' ? '.' . $extension : '';
$count = 1;
while (file_exists($targetDir . DIRECTORY_SEPARATOR . $nameWithoutExt . '_' . $count . $extWithDot)) {
$count++;
}
$fileName = $nameWithoutExt . '_' . $count . $extWithDot;
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
$partPath = $filePath . '.part';
return [$fileName, $extension, $filePath, $partPath];
}
}
if (!function_exists('plupload_get_chunks')) {
function plupload_get_chunks()
{
$chunk = max(0, (int)($_REQUEST['chunk'] ?? 0));
$chunks = max(0, (int)($_REQUEST['chunks'] ?? 0));
return [$chunk, $chunks];
}
}
if (!function_exists('plupload_cleanup_stale_parts')) {
function plupload_cleanup_stale_parts($targetDir, $currentPartPath, $maxFileAge = 18000)
{
$dir = @opendir($targetDir);
if (!$dir) {
return;
}
while (($file = readdir($dir)) !== false) {
$tmpFilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
if (!preg_match('/\.part$/', $file)) {
continue;
}
if ($tmpFilePath === $currentPartPath) {
continue;
}
if (@filemtime($tmpFilePath) < (time() - (int)$maxFileAge)) {
@unlink($tmpFilePath);
}
}
closedir($dir);
}
}
if (!function_exists('plupload_write_chunk_to_part')) {
function plupload_write_chunk_to_part($partPath, $chunk)
{
$contentType = (string)($_SERVER['HTTP_CONTENT_TYPE'] ?? $_SERVER['CONTENT_TYPE'] ?? '');
$isMultipart = strpos($contentType, 'multipart') !== false;
if ($isMultipart) {
$fileInfo = $_FILES['file'] ?? null;
if (!is_array($fileInfo) || !isset($fileInfo['tmp_name']) || !is_uploaded_file($fileInfo['tmp_name'])) {
plupload_send_error(400, 103, 'Failed to move uploaded file.');
}
if ((int)($fileInfo['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
plupload_send_error(400, 104, 'Upload error.');
}
$in = fopen($fileInfo['tmp_name'], 'rb');
$out = fopen($partPath, ((int)$chunk === 0) ? 'wb' : 'ab');
if (!$in) {
plupload_send_error(500, 101, 'Failed to open input stream.');
}
if (!$out) {
fclose($in);
plupload_send_error(500, 102, 'Failed to open output stream.');
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
fclose($in);
fclose($out);
@unlink($fileInfo['tmp_name']);
return;
}
$in = fopen('php://input', 'rb');
$out = fopen($partPath, ((int)$chunk === 0) ? 'wb' : 'ab');
if (!$in) {
plupload_send_error(500, 101, 'Failed to open input stream.');
}
if (!$out) {
fclose($in);
plupload_send_error(500, 102, 'Failed to open output stream.');
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
fclose($in);
fclose($out);
}
}
if (!function_exists('plupload_assert_size_limit')) {
function plupload_assert_size_limit($partPath, $maxBytes, $message)
{
if (@filesize($partPath) > (int)$maxBytes) {
@unlink($partPath);
plupload_send_error(413, 413, (string)$message);
}
}
}
if (!function_exists('plupload_is_last_chunk')) {
function plupload_is_last_chunk($chunk, $chunks)
{
return ((int)$chunks === 0) || ((int)$chunk === ((int)$chunks - 1));
}
}
if (!function_exists('plupload_finalize_part')) {
function plupload_finalize_part($partPath, $filePath)
{
if (!@rename($partPath, $filePath)) {
@unlink($partPath);
plupload_send_error(500, 105, 'Failed to finalize uploaded file.');
}
}
}
if (!function_exists('plupload_create_medoo')) {
function plupload_create_medoo($database)
{
return new medoo([
'database_type' => 'mysql',
'database_name' => $database['name'],
'server' => $database['host'],
'username' => $database['user'],
'password' => $database['password'],
'charset' => 'utf8',
]);
}
}
if (!function_exists('plupload_send_success')) {
function plupload_send_success(array $payload)
{
echo json_encode(array_merge([
'jsonrpc' => '2.0',
'result' => null,
'id' => 'id',
], $payload));
exit;
}
}

View File

@@ -1,154 +1,53 @@
<?php
require_once '../../config.php';
require_once '../medoo/medoo.php';
date_default_timezone_set( 'Europe/Warsaw' );
session_start();
require_once 'upload-common.php';
$upload_token = $_REQUEST['upload_token'] ?? '';
if ( !isset( $_SESSION['upload_tokens'][$upload_token] ) ) {
http_response_code(403);
echo json_encode( ['error' => 'Brak tokenu uploadu'] );
exit;
plupload_bootstrap();
plupload_require_post();
$userId = plupload_require_admin_user();
plupload_validate_token($userId);
$fileDir = '/upload/product_files/tmp';
$targetDir = '../..' . $fileDir;
plupload_ensure_target_dir($targetDir);
list($chunk, $chunks) = plupload_get_chunks();
list($fileName, $extension, $filePath, $partPath) = plupload_build_target_paths(
$targetDir,
$_REQUEST['name'] ?? '',
null,
[
'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phar',
'cgi', 'pl', 'py', 'rb',
'asp', 'aspx', 'jsp',
'js', 'mjs', 'vbs', 'wsf', 'hta',
'sh', 'bash', 'zsh', 'ps1', 'bat', 'cmd', 'com',
'exe', 'msi', 'scr', 'dll', 'jar',
]
);
plupload_cleanup_stale_parts($targetDir, $partPath, 5 * 3600);
plupload_write_chunk_to_part($partPath, $chunk);
plupload_assert_size_limit($partPath, 50 * 1024 * 1024, 'Plik przekracza dozwolony rozmiar (50 MB).');
$fileId = null;
$responseFileName = $fileName;
if (plupload_is_last_chunk($chunk, $chunks)) {
plupload_finalize_part($partPath, $filePath);
$mdb = plupload_create_medoo($database);
$mdb->insert('pp_shop_products_files', [
'product_id' => null,
'src' => substr($filePath, 5),
]);
$fileId = (int)$mdb->id();
$responseFileName = basename($filePath);
}
$tokenData = $_SESSION['upload_tokens'][$upload_token];
if ( $tokenData['expires'] < time() ) {
unset( $_SESSION['upload_tokens'][$upload_token] );
http_response_code(403);
echo json_encode( ['error' => 'Token wygasł'] );
exit;
}
plupload_send_success([
'file_name' => $responseFileName,
'file_id' => $fileId,
]);
$mdb = new medoo( [
'database_type' => 'mysql',
'database_name' => $database['name'],
'server' => $database['host'],
'username' => $database['user'],
'password' => $database['password'],
'charset' => 'utf8'
] );
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header( "Cache-Control: no-store, no-cache, must-revalidate" );
header( "Cache-Control: post-check=0, pre-check=0", false );
header( "Pragma: no-cache" );
$fileDir = '/upload/product_files/tmp';
$targetDir = '../..' . $fileDir;
if ( !is_dir( $targetDir ) )
mkdir( $targetDir, 0755, true );
$cleanupTargetDir = true;
$maxFileAge = 5 * 3600;
$chunk = isset( $_REQUEST["chunk"] ) ? intval( $_REQUEST["chunk"] ) : 0;
$chunks = isset( $_REQUEST["chunks"] ) ? intval( $_REQUEST["chunks"] ) : 0;
$fileName = isset( $_REQUEST["name"] ) ? $_REQUEST["name"] : '';
$fileName = preg_replace( '/[^\w\._]+/', '-', $fileName );
if ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName ) )
{
$ext = strrpos( $fileName, '.' );
$fileName_a = substr( $fileName, 0, $ext );
$fileName_b = substr( $fileName, $ext );
$count = 1;
while ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b ) )
$count++;
$fileName = $fileName_a . '_' . $count . $fileName_b;
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
if ( $cleanupTargetDir && is_dir( $targetDir ) && ( $dir = opendir( $targetDir ) ) )
{
while ( ( $file = readdir( $dir ) ) !== false )
{
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
if ( preg_match( '/\.part$/', $file ) && ( filemtime( $tmpfilePath ) < time() - $maxFileAge ) && ( $tmpfilePath != "{$filePath}.part" ) ) {
@unlink( $tmpfilePath );
}
}
closedir($dir);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}' );
if ( isset( $_SERVER["HTTP_CONTENT_TYPE"] ) )
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
if ( isset( $_SERVER["CONTENT_TYPE"] ) )
$contentType = $_SERVER["CONTENT_TYPE"];
if ( strpos( $contentType, "multipart" ) !== false )
{
if ( isset( $_FILES['file']['tmp_name'] ) && is_uploaded_file( $_FILES['file']['tmp_name'] ) )
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( $_FILES['file']['tmp_name'], "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite($out, $buff);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
@unlink( $_FILES['file']['tmp_name'] );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}' );
}
else
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( "php://input", "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite( $out, $buff );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
if ( !$chunks || $chunk == $chunks - 1 )
{
rename( "{$filePath}.part", $filePath );
$mdb -> insert( 'pp_shop_products_files', [
'product_id' => null,
'src' => substr( $filePath, 5, strlen( $filePath ) )
] );
$file_id = $mdb -> id();
$file_name = explode( '/', $filePath );
$file_name = $file_name[ count( $file_name ) - 1 ];
}
die( '{"jsonrpc" : "2.0", "result" : null, "id" : "id", "file_name" : "' . $file_name . '", "file_id" : "' . $file_id . '"}' );
?>

View File

@@ -1,154 +1,61 @@
<?php
require_once '../../config.php';
require_once '../medoo/medoo.php';
date_default_timezone_set( 'Europe/Warsaw' );
session_start();
require_once 'upload-common.php';
$upload_token = $_REQUEST['upload_token'] ?? '';
if ( !isset( $_SESSION['upload_tokens'][$upload_token] ) ) {
http_response_code(403);
echo json_encode( ['error' => 'Brak tokenu uploadu'] );
exit;
plupload_bootstrap();
plupload_require_post();
$userId = plupload_require_admin_user();
plupload_validate_token($userId);
$fileDir = '/upload/product_images/tmp';
$targetDir = '../..' . $fileDir;
plupload_ensure_target_dir($targetDir);
list($chunk, $chunks) = plupload_get_chunks();
list($fileName, $extension, $filePath, $partPath) = plupload_build_target_paths(
$targetDir,
$_REQUEST['name'] ?? '',
['jpg', 'jpeg', 'png', 'gif', 'webp'],
null
);
plupload_cleanup_stale_parts($targetDir, $partPath, 5 * 3600);
plupload_write_chunk_to_part($partPath, $chunk);
plupload_assert_size_limit($partPath, 20 * 1024 * 1024, 'Plik przekracza dozwolony rozmiar (20 MB).');
$imageId = null;
if (plupload_is_last_chunk($chunk, $chunks)) {
plupload_finalize_part($partPath, $filePath);
$mime = mime_content_type($filePath) ?: '';
$imageMeta = @getimagesize($filePath);
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$isValidImage = in_array($mime, $allowedMimeTypes, true)
&& is_array($imageMeta)
&& (int)($imageMeta[0] ?? 0) > 0
&& (int)($imageMeta[1] ?? 0) > 0;
if (!$isValidImage) {
@unlink($filePath);
plupload_send_error(400, 601, 'Plik nie jest prawidlowym obrazem.');
}
$mdb = plupload_create_medoo($database);
$order = (int)$mdb->max('pp_shop_products_images', 'o');
$productId = (int)($_POST['product_id'] ?? 0);
$mdb->insert('pp_shop_products_images', [
'product_id' => $productId > 0 ? $productId : null,
'src' => substr($filePath, 5),
'o' => $order + 1,
]);
$imageId = (int)$mdb->id();
}
$tokenData = $_SESSION['upload_tokens'][$upload_token];
if ( $tokenData['expires'] < time() ) {
unset( $_SESSION['upload_tokens'][$upload_token] );
http_response_code(403);
echo json_encode( ['error' => 'Token wygasł'] );
exit;
}
plupload_send_success([
'data_link' => str_replace('../../', '', $filePath),
'image_id' => $imageId,
]);
$mdb = new medoo( [
'database_type' => 'mysql',
'database_name' => $database['name'],
'server' => $database['host'],
'username' => $database['user'],
'password' => $database['password'],
'charset' => 'utf8'
] );
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
header( "Cache-Control: no-store, no-cache, must-revalidate" );
header( "Cache-Control: post-check=0, pre-check=0", false );
header( "Pragma: no-cache" );
$fileDir = '/upload/product_images/tmp';
$targetDir = '../..' . $fileDir;
if ( !is_dir( $targetDir ) )
mkdir( $targetDir, 0755, true );
$cleanupTargetDir = true;
$maxFileAge = 5 * 3600;
$chunk = isset( $_REQUEST["chunk"] ) ? intval( $_REQUEST["chunk"] ) : 0;
$chunks = isset( $_REQUEST["chunks"] ) ? intval( $_REQUEST["chunks"] ) : 0;
$fileName = isset( $_REQUEST["name"] ) ? $_REQUEST["name"] : '';
$fileName = preg_replace( '/[^\w\._]+/', '-', $fileName );
if ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName ) )
{
$ext = strrpos( $fileName, '.' );
$fileName_a = substr( $fileName, 0, $ext );
$fileName_b = substr( $fileName, $ext );
$count = 1;
while ( file_exists( $targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b ) )
$count++;
$fileName = $fileName_a . '_' . $count . $fileName_b;
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
if ( $cleanupTargetDir && is_dir( $targetDir ) && ( $dir = opendir( $targetDir ) ) )
{
while ( ( $file = readdir( $dir ) ) !== false )
{
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
if ( preg_match( '/\.part$/', $file ) && ( filemtime( $tmpfilePath ) < time() - $maxFileAge ) && ( $tmpfilePath != "{$filePath}.part" ) ) {
@unlink( $tmpfilePath );
}
}
closedir($dir);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}' );
if ( isset( $_SERVER["HTTP_CONTENT_TYPE"] ) )
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
if ( isset( $_SERVER["CONTENT_TYPE"] ) )
$contentType = $_SERVER["CONTENT_TYPE"];
if ( strpos( $contentType, "multipart" ) !== false )
{
if ( isset( $_FILES['file']['tmp_name'] ) && is_uploaded_file( $_FILES['file']['tmp_name'] ) )
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( $_FILES['file']['tmp_name'], "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite($out, $buff);
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
@unlink( $_FILES['file']['tmp_name'] );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}' );
}
else
{
$out = fopen( "{$filePath}.part", $chunk == 0 ? "wb" : "ab" );
if ( $out )
{
$in = fopen( "php://input", "rb" );
if ( $in )
{
while ( $buff = fread( $in, 4096 ) )
fwrite( $out, $buff );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
fclose( $in );
fclose( $out );
}
else
die( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
}
if ( !$chunks || $chunk == $chunks - 1 )
{
rename( "{$filePath}.part", $filePath );
$o = $mdb -> max( 'pp_shop_products_images', 'o' );
$mdb -> insert( 'pp_shop_products_images', [
'product_id' => isset( $_POST['product_id'] ) ? $_POST['product_id'] : null,
'src' => substr( $filePath, 5, strlen( $filePath ) ),
'o' => ++$o
] );
$image_id = $mdb -> id();
}
die( '{"jsonrpc" : "2.0", "result" : null, "id" : "id", "data_link" : "' . str_replace( '../../', '', $filePath ) . '", "image_id" : "' . $image_id . '"}' );
?>