Show sourcecode
The following files exists in this folder. Click to view.
Webserver1/Ovningar/Slutprojekt/
.env
DEBUG/
Media/
account.js
account.php
callback_log.txt
change_account_details.php
composer.json
composer.lock
forgot_pass.php
forgot_pass_new_pass.php
header.php
index.php
login.php
mediaplayer.php
node_modules/
package-lock.json
package.json
signup.php
style.css
upload.js
upload_callback.php
upload_callback_simulated.php
upload_chunk.php
upload_errors.log
upload_form.php
upload_handler.php
upload_success.log
vendor/
verify_file.php
verifypage.php
upload_handler.php
760 lines UTF-8 Windows (CRLF)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
<?php
session_start();
// VERY EARLY LOGGING - before anything else
$local = isset($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'labb.vgy.se') === false;
// Directory constants
define("LOCAL_UPLOAD_DIR", "../../../filhantering/");
define("SERVER_UPLOAD_DIR", "/home/antasp23/public_html/filhantering/");
define("UPLOAD_DIR", $local ? LOCAL_UPLOAD_DIR : SERVER_UPLOAD_DIR);
$early_log = UPLOAD_DIR . "upload_early.log";
$timestamp = date('Y-m-d H:i:s');
$early_msg = "[$timestamp] Script started - Method: " . $_SERVER['REQUEST_METHOD'] . ", User: " . ($_SESSION['userId'] ?? 'none') . ", Files: " . count($_FILES) . "\n";
@file_put_contents($early_log, $early_msg, FILE_APPEND);
// echo "<pre>";
// print_r($_SESSION);
// echo "</pre>";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('../../incl/dbconnection.php');
/**
* @var PDO $dbconn
* @var bool $local
* @var class DBManager
*/
require_once __DIR__ . '/vendor/autoload.php';
$DEBUG = true;
define("MAX_VIDEO_SIZE", 200 * 1024 * 1024); // 200 Mb
define("MAX_IMAGE_SIZE", 2 * 1024 * 1024); // 2 Mb
define("CHUNK_UPLOAD_DIR", UPLOAD_DIR); // Same as chunk endpoint
// Error logging function
function log_upload_error($message, $context = [])
{
$log_file = UPLOAD_DIR . "upload_errors.log";
$timestamp = date('Y-m-d H:i:s');
$log_entry = "[$timestamp] $message";
if (!empty($context)) {
$log_entry .= " | Context: " . json_encode($context);
}
$log_entry .= "\n";
// Try to write to log, but don't fail if we can't
@file_put_contents($log_file, $log_entry, FILE_APPEND);
}
// Success logging function
function log_upload_success($message, $context = [])
{
$log_file = UPLOAD_DIR . "upload_success.log";
$timestamp = date('Y-m-d H:i:s');
$log_entry = "[$timestamp] $message";
if (!empty($context)) {
$log_entry .= " | Context: " . json_encode($context);
}
$log_entry .= "\n";
// Try to write to log, but don't fail if we can't
@file_put_contents($log_file, $log_entry, FILE_APPEND);
}
/**
* Cleans up temporary chunk files if they exist
*/
function cleanup_chunk_files(?array $video): void
{
if ($video && !empty($video['is_chunked'])) {
if (isset($video['tmp_name']) && file_exists($video['tmp_name'])) {
@unlink($video['tmp_name']);
}
if (!empty($video['meta_path']) && file_exists($video['meta_path'])) {
@unlink($video['meta_path']);
}
}
}
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
// Only load .env if it exists (for production environments)
if (file_exists(__DIR__ . '/.env')) {
$dotenv->load();
}
$api_user = $_ENV['sightengine_user'] ?? null;
$api_secret = $_ENV['sightengine_secret'] ?? null;
$user_id = $_SESSION['userId'] ?? null;
if (!$user_id) {
log_upload_error("No user session", ["session" => session_id(), "session_data" => $_SESSION]);
http_response_code(401);
exit("Du måste vara inloggad för att ladda upp filer!");
}
log_upload_success("Upload handler accessed", ["user_id" => $user_id, "method" => $_SERVER['REQUEST_METHOD']]);
$callback_url = $local ?
'https://swindlingly-lockable-leonel.ngrok-free.dev/Webserver1/Ovningar/Slutprojekt/upload_callback_simulated.php' :
'https://labb.vgy.se/~antasp23/Webserver1/Ovningar/Slutprojekt/upload_callback_simulated.php';
$dbmanager = new DBManager();
// API keys are only required when not in debug mode
if (!$DEBUG && (!$api_user || !$api_secret)) {
log_upload_error("Missing API credentials in production mode");
throw new Exception("SightEngine API credentials required when DEBUG=false");
}
if (!$user_id) {
throw new Exception("No userId in session!");
}
function send_video_to_moderation(&$videofile): array
{
global $callback_url, $api_user, $api_secret;
$params = array(
'media' => new CurlFile($videofile["tmp_name"], $videofile["type"], $videofile["name"]),
'models' => 'nudity,gore',
'callback_url' => $callback_url,
'api_user' => $api_user,
'api_secret' => $api_secret,
);
$video_ch = curl_init('https://api.sightengine.com/1.0/video/check.json');
curl_setopt($video_ch, CURLOPT_POST, true);
curl_setopt($video_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($video_ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($video_ch);
$output = json_decode($response, true);
return $output;
}
function simulate_video_moderation(&$videofile): array
{
global $callback_url, $api_user, $api_secret;
$params = array(
'media' => new CurlFile($videofile["tmp_name"], $videofile["type"], $videofile["name"]),
'models' => 'nudity,gore',
'callback_url' => $callback_url,
'api_user' => $api_user,
'api_secret' => $api_secret,
);
$req_id = uniqid();
$med_id = uniqid();
$response = '{
"status": "success",
"request": {
"id": "req_' . $req_id . '",
"timestamp": "' . time() . '"
},
"media": {
"id": "med_' . $med_id . '",
"uri": "' . $videofile["name"] . '"
},
"callback": "' . $callback_url . '"
}';
// $video_ch = curl_init("http://localhost/Webserver1/Ovningar/Slutprojekt/DEBUG/test_callback_recieve.php");
// curl_setopt($video_ch, CURLOPT_POST, true);
// curl_setopt($video_ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($video_ch, CURLOPT_POSTFIELDS, $params);
// $response = curl_exec($video_ch);
// Exempelrespons till callback
$callback_input = [
'media' => [
'id' => 'med_' . $med_id
],
'request' => 'req_' . $req_id,
'data' => [
'status' => "finished",
"progress" => 1.0,
"operations" => 6,
"frames" => [
[
"info" => [
"id" => "med_9urgHE38fdLs0R85qa7MX_1",
"position" => 0
],
"nudity" => [
"sexual_activity" => 0.01,
"sexual_display" => 0.01,
"erotica" => 0.01,
"sextoy" => 0.01,
"suggestive" => 0.01,
"suggestive_classes" => [
"bikini" => 0.01,
"cleavage" => 0.01,
"cleavage_categories" => [
"very_revealing" => 0.01,
"revealing" => 0.01,
"none" => 0.99
],
"male_chest" => 0.01,
"male_chest_categories" => [
"very_revealing" => 0.01,
"revealing" => 0.01,
"slightly_revealing" => 0.01,
"none" => 0.99
],
"male_underwear" => 0.01,
"lingerie" => 0.01,
"miniskirt" => 0.01,
"other" => 0.01
],
"none" => 0.99,
"context" => [
"sea_lake_pool" => 0.01,
"outdoor_other" => 0.99,
"indoor_other" => 0.01
]
]
],
[
"info" => [
"id" => "med_9urgHE38fdLs0R85qa7MX_2",
"position" => 1000
],
"nudity" => [
"sexual_activity" => 0.01,
"sexual_display" => 0.01,
"erotica" => 0.01,
"sextoy" => 0.01,
"suggestive" => 0.01,
"suggestive_classes" => [
"bikini" => 0.01,
"cleavage" => 0.01,
"cleavage_categories" => [
"very_revealing" => 0.01,
"revealing" => 0.01,
"none" => 0.99
],
"male_chest" => 0.01,
"male_chest_categories" => [
"very_revealing" => 0.01,
"revealing" => 0.01,
"slightly_revealing" => 0.01,
"none" => 0.99
],
"male_underwear" => 0.01,
"lingerie" => 0.01,
"miniskirt" => 0.01,
"other" => 0.01
],
"none" => 0.99,
"context" => [
"sea_lake_pool" => 0.01,
"outdoor_other" => 0.99,
"indoor_other" => 0.01
]
]
],
]
]
];
$callback_ch = curl_init($callback_url);
curl_setopt($callback_ch, CURLOPT_POST, true);
curl_setopt($callback_ch, CURLOPT_POSTFIELDS, json_encode($callback_input));
curl_setopt($callback_ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($callback_ch, CURLOPT_TIMEOUT_MS, 1000);
curl_setopt($callback_ch, CURLOPT_CONNECTTIMEOUT_MS, 1000);
curl_setopt($callback_ch, CURLOPT_NOSIGNAL, 1);
curl_exec($callback_ch);
$output = json_decode($response, true);
if (!$output) {
echo "problem!!!!";
}
return $output;
}
function simulate_image_moderation(&$imagefile): array
{
global $callback_url;
$json_str = '{
"status": "success",
"request": {
"id": "req_' . uniqid() . '",
"timestamp": "' . time() . '"
},
"media": {
"id": "med_' . uniqid() . '",
"uri": "' . $imagefile["name"] . '"
},
"callback": "' . $callback_url . '"
}';
return json_decode($json_str, true);
}
function get_chunk_upload_dir(): string {
if (!is_dir(CHUNK_UPLOAD_DIR)) {
@mkdir(CHUNK_UPLOAD_DIR, 0755, true);
}
return CHUNK_UPLOAD_DIR;
}
function resolve_video_upload(): ?array
{
if (!empty($_POST['video_temp_id'])) {
$uploadId = preg_replace('/[^A-Za-z0-9_-]/', '', $_POST['video_temp_id']);
$chunkDir = get_chunk_upload_dir();
$tmpPath = $chunkDir . $uploadId . '.tmp';
$metaPath = $chunkDir . $uploadId . '.meta.json';
log_upload_success("Resolving chunked upload", [
'upload_id' => $uploadId,
'chunk_dir' => $chunkDir,
'tmp_path' => $tmpPath,
'meta_path' => $metaPath,
'tmp_exists' => file_exists($tmpPath),
'meta_exists' => file_exists($metaPath),
'tmp_size' => file_exists($tmpPath) ? filesize($tmpPath) : 'N/A'
]);
if (!file_exists($tmpPath) || !file_exists($metaPath)) {
log_upload_error("Chunked upload files missing", [
'upload_id' => $uploadId,
'chunk_dir' => $chunkDir,
'tmp_path' => $tmpPath,
'meta_path' => $metaPath
]);
return null;
}
$meta = json_decode(file_get_contents($metaPath), true);
return [
'name' => $meta['fileName'] ?? 'video.mp4',
'type' => $meta['fileType'] ?? 'video/mp4',
'tmp_name' => $tmpPath,
'size' => filesize($tmpPath),
'error' => UPLOAD_ERR_OK,
'is_chunked' => true,
'upload_id' => $uploadId,
'meta_path' => $metaPath,
];
}
return $_FILES['video-input'] ?? null;
}
function persist_video_file(array $video, string $target_path): bool
{
log_upload_success("Attempting to persist video file", [
'target_path' => $target_path,
'is_chunked' => !empty($video['is_chunked']),
'source_path' => $video['tmp_name'],
'source_exists' => file_exists($video['tmp_name']),
'source_size' => file_exists($video['tmp_name']) ? filesize($video['tmp_name']) : 'N/A',
'target_dir' => dirname($target_path),
'target_dir_writable' => is_writable(dirname($target_path))
]);
if (!empty($video['is_chunked'])) {
if (@rename($video['tmp_name'], $target_path)) {
log_upload_success("Chunked file renamed successfully", ['target_path' => $target_path]);
return true;
}
if (@copy($video['tmp_name'], $target_path)) {
@unlink($video['tmp_name']);
log_upload_success("Chunked file copied successfully", ['target_path' => $target_path]);
return true;
}
log_upload_error("Chunked file persistence failed", [
'source' => $video['tmp_name'],
'target' => $target_path,
'rename_error' => error_get_last()
]);
return false;
}
if (move_uploaded_file($video['tmp_name'], $target_path)) {
log_upload_success("Regular file moved successfully", ['target_path' => $target_path]);
return true;
}
if (@copy($video['tmp_name'], $target_path)) {
@unlink($video['tmp_name']);
log_upload_success("Regular file copied successfully", ['target_path' => $target_path]);
return true;
}
log_upload_error("Regular file persistence failed", [
'source' => $video['tmp_name'],
'target' => $target_path,
'error' => error_get_last()
]);
return false;
}
if ((isset($_FILES["video-input"]) || !empty($_POST["video_temp_id"])) && isset($_FILES["thumb-input"])) {
@file_put_contents($early_log, "[$timestamp] Files detected - processing upload\n", FILE_APPEND);
log_upload_success("Upload started", [
"user_id" => $user_id,
"files" => array_keys($_FILES),
"video_temp_id" => $_POST["video_temp_id"] ?? null,
"php_limits" => [
"upload_max_filesize" => ini_get('upload_max_filesize'),
"post_max_size" => ini_get('post_max_size'),
"max_file_uploads" => ini_get('max_file_uploads'),
"memory_limit" => ini_get('memory_limit')
]
]);
$VIDEO = resolve_video_upload();
$THUMB = $_FILES["thumb-input"];
if (!$VIDEO) {
log_upload_error("Missing video upload", ["post" => $_POST]);
http_response_code(400);
exit("Ingen videofil hittades. Prova att ladda upp igen.");
}
$title = $_POST['video-title'] ?? '';
$description = $_POST['video-description'] ?? '';
// Validate required fields
if (empty($title)) {
log_upload_error("Missing video title");
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Video titel är obligatorisk!");
}
// Check for duplicate title
try {
$existing = $dbmanager->fetch_from_table(["title"], "bay_media", ["uploaded_by_user_id" => $user_id, "title" => $title]);
if (!empty($existing)) {
log_upload_error("Duplicate title", ["title" => $title, "user_id" => $user_id]);
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Du har redan laddat upp en video med denna titel!");
}
} catch (Exception $e) {
log_upload_error("Database error checking duplicate title", ["error" => $e->getMessage()]);
cleanup_chunk_files($VIDEO);
http_response_code(500);
exit("Databasfel vid kontroll av titel!");
}
// Validate file types
if (!str_starts_with($VIDEO['type'], "video")) {
log_upload_error("Invalid video file type", ["type" => $VIDEO['type']]);
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Video input har inte video format! Typ: " . $VIDEO['type']);
}
if (!str_starts_with($THUMB['type'], "image")) {
log_upload_error("Invalid image file type", ["type" => $THUMB['type']]);
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Bild input har inte bild format! Typ: " . $THUMB['type']);
}
// Validate file sizes
if ($VIDEO["size"] > MAX_VIDEO_SIZE) {
log_upload_error("Video file too large", ["size" => $VIDEO["size"], "max" => MAX_VIDEO_SIZE]);
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Video filstorlek för stor! Storlek: " . round($VIDEO["size"] / 1024 / 1024, 2) . "MB, Max: " . round(MAX_VIDEO_SIZE / 1024 / 1024, 2) . "MB");
}
if ($VIDEO["size"] < 64) {
log_upload_error("Video file too small or missing", ["size" => $VIDEO["size"]]);
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Video fil verkar vara för liten eller saknas!");
}
if ($THUMB["size"] > MAX_IMAGE_SIZE) {
log_upload_error("Thumbnail file too large", ["size" => $THUMB["size"], "max" => MAX_IMAGE_SIZE]);
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Thumbnail filstorlek för stor! Storlek: " . round($THUMB["size"] / 1024 / 1024, 2) . "MB, Max: " . round(MAX_IMAGE_SIZE / 1024 / 1024, 2) . "MB");
}
log_upload_success("File validation passed", ["video_size" => $VIDEO["size"], "thumb_size" => $THUMB["size"]]);
// Run moderation
try {
if ($DEBUG) {
$videoResponse = simulate_video_moderation($VIDEO);
$imageResponse = simulate_image_moderation($THUMB);
log_upload_success("Simulated moderation completed");
} else {
$videoResponse = send_video_to_moderation($VIDEO);
$imageResponse = simulate_image_moderation($THUMB);
log_upload_success("Real moderation completed");
}
} catch (Exception $e) {
log_upload_error("Moderation failed", ["error" => $e->getMessage()]);
cleanup_chunk_files($VIDEO);
http_response_code(500);
exit("Moderation misslyckades: " . $e->getMessage());
}
$videoStatus = $videoResponse["status"] ?? null;
$imageStatus = $imageResponse["status"] ?? null;
if ($videoStatus != "success" || $imageStatus != "success") {
log_upload_error("Moderation status failed", ["video_status" => $videoStatus, "image_status" => $imageStatus]);
cleanup_chunk_files($VIDEO);
http_response_code(400);
exit("Filuppladdningen misslyckades - moderation nekades. Video status: $videoStatus, Bild status: $imageStatus");
}
log_upload_success("Moderation passed", ["video_id" => $videoResponse['media']['id'] ?? 'unknown', "image_id" => $imageResponse['media']['id'] ?? 'unknown']);
// Försök lägga in videojobb i db
try {
// // Video job
// $dbmanager->insert_into_table(
// [
// "user_id" => $user_id,
// "req_id" => $videoResponse["request"]["id"],
// "status" => "ongoing",
// "type" => "video",
// "debug" => $DEBUG ? "1" : "0"
// ],
// "bay_moderation_jobs"
// );
// echo "video insert successful\n";
// // Image job
// $dbmanager->insert_into_table(
// [
// "user_id" => $user_id,
// "req_id" => $imageResponse["request"]["id"],
// "status" => "ongoing",
// "type" => "image",
// "debug" => $DEBUG ? "1" : "0"
// ],
// "bay_moderation_jobs"
// );
// echo "image insert successful\n";
} catch (RuntimeException $e) {
// Insert gick åt pipan
cleanup_chunk_files($VIDEO);
exit("Ett problem uppstod och fin fil har inte laddats upp :(\n Error: " . $e->getMessage());
}
// Setup upload directory
$target_dir = UPLOAD_DIR;
// Ensure directory exists and is writable
if (!is_dir($target_dir)) {
log_upload_error("Upload directory does not exist", ["path" => $target_dir, "realpath" => realpath($target_dir)]);
cleanup_chunk_files($VIDEO);
http_response_code(500);
exit("Målmappen existerar inte: " . realpath($target_dir));
}
if (!is_writable($target_dir)) {
log_upload_error("Upload directory not writable", ["path" => $target_dir, "permissions" => substr(sprintf('%o', fileperms($target_dir)), -4)]);
cleanup_chunk_files($VIDEO);
http_response_code(500);
exit("Målmappen är inte skrivbar: " . realpath($target_dir) . " (rättigheter: " . substr(sprintf('%o', fileperms($target_dir)), -4) . ")");
}
// Generate unique filenames
$video_ext = str_replace("video/", "", $VIDEO['type']);
$image_ext = str_replace("image/", "", $THUMB['type']);
$target_video_path = $target_dir . $videoResponse['media']['id'] . "_" . bin2hex(random_bytes(4)) . "." . $video_ext;
$target_image_path = $target_dir . $imageResponse['media']['id'] . "_" . bin2hex(random_bytes(4)) . "." . $image_ext;
// Convert server paths to web-relative paths for database storage
$web_video_path = "../../../filhantering/" . basename($target_video_path);
$web_image_path = "../../../filhantering/" . basename($target_image_path);
log_upload_success("File paths generated", ["video_path" => $target_video_path, "image_path" => $target_image_path, "web_video_path" => $web_video_path, "web_image_path" => $web_image_path]);
// Insert into database
try {
$dbmanager->insert_into_table(
[
"media_id" => $videoResponse['media']['id'],
"title" => $title,
"description" => $description,
"href_video" => $web_video_path,
"href_thumb" => $web_image_path,
"uploaded_by_user_id" => $user_id
],
"bay_media"
);
log_upload_success("Database insert successful", ["media_id" => $videoResponse['media']['id']]);
} catch (Exception $e) {
log_upload_error("Database insert failed", ["error" => $e->getMessage(), "media_id" => $videoResponse['media']['id']]);
cleanup_chunk_files($VIDEO);
http_response_code(500);
exit("Databasfel vid sparande av media information: " . $e->getMessage());
}
// Move uploaded files
$upload_success = true;
$error_messages = [];
// Try to move video file
if (!persist_video_file($VIDEO, $target_video_path)) {
$error = error_get_last();
$error_msg = "Video kunde inte flyttas: " . ($error['message'] ?? 'Okänt fel');
log_upload_error("Video file move/copy failed", ["error" => $error_msg, "target" => $target_video_path, "temp_file" => $VIDEO['tmp_name'], "temp_exists" => file_exists($VIDEO['tmp_name'])]);
$error_messages[] = $error_msg;
$upload_success = false;
} else {
log_upload_success("Video file moved successfully", ["path" => $target_video_path]);
}
// Try to move thumbnail file
if (!move_uploaded_file($THUMB['tmp_name'], $target_image_path)) {
$error = error_get_last();
$error_msg = "Tumnagel kunde inte flyttas: " . ($error['message'] ?? 'Okänt fel');
// Fallback: try copy() if move_uploaded_file failed
if (copy($THUMB['tmp_name'], $target_image_path)) {
unlink($THUMB['tmp_name']); // Clean up temp file
log_upload_success("Thumbnail file copied successfully (fallback)", ["path" => $target_image_path]);
} else {
log_upload_error("Thumbnail file move/copy failed", ["error" => $error_msg, "target" => $target_image_path, "temp_file" => $THUMB['tmp_name'], "temp_exists" => file_exists($THUMB['tmp_name'])]);
$error_messages[] = $error_msg;
// Clean up video file if thumbnail failed
if (file_exists($target_video_path)) {
unlink($target_video_path);
log_upload_success("Cleaned up video file after thumbnail failure");
}
$upload_success = false;
}
} else {
log_upload_success("Thumbnail file moved successfully", ["path" => $target_image_path]);
}
if (!$upload_success) {
// Remove database entry
try {
$dbmanager->remove_from_table("bay_media", ["href_video" => $target_video_path]);
log_upload_success("Database entry removed after upload failure");
} catch (Exception $e) {
log_upload_error("Failed to remove database entry", ["error" => $e->getMessage()]);
}
cleanup_chunk_files($VIDEO);
http_response_code(500);
exit("Filuppladdningen misslyckades:\n" . implode("\n", $error_messages));
}
log_upload_success("Upload completed successfully", ["media_id" => $videoResponse['media']['id'], "title" => $title]);
// Verify files actually exist before claiming success
if (!file_exists($target_video_path) || !file_exists($target_image_path)) {
log_upload_error("Files missing after upload completion", [
'video_exists' => file_exists($target_video_path),
'video_path' => $target_video_path,
'image_exists' => file_exists($target_image_path),
'image_path' => $target_image_path
]);
// Clean up database entry if files are missing
try {
$dbmanager->remove_from_table("bay_media", ["href_video" => $target_video_path]);
log_upload_success("Database entry removed due to missing files");
} catch (Exception $e) {
log_upload_error("Failed to remove database entry", ["error" => $e->getMessage()]);
}
cleanup_chunk_files($VIDEO);
http_response_code(500);
exit("Uppladdningen misslyckades - filer kunde inte sparas korrekt.");
}
// Clean up temporary chunk files
cleanup_chunk_files($VIDEO);
$_SESSION['flash_msg'] = "Din fil har laddats upp och inväntar moderation. Den kommer att kunna ses när den blir godkänd.";
header("Location: index.php");
exit;
}
// If we reach here, no files were uploaded - show debug info
@file_put_contents($early_log, "[$timestamp] No files uploaded - showing debug page\n", FILE_APPEND);
?>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Debug Info</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php include("header.php") ?>
<main>
<h1>Upload Debug Information</h1>
<p>This page shows debug information when no files are uploaded.</p>
<h2>Environment Info:</h2>
<ul>
<li><strong>Local mode:</strong> <?php echo $local ? 'Yes' : 'No'; ?></li>
<li><strong>Debug mode:</strong> <?php echo $DEBUG ? 'Yes' : 'No'; ?></li>
<li><strong>User ID:</strong> <?php echo $user_id ?: 'Not logged in'; ?></li>
<li><strong>Upload dir:</strong> <?php echo UPLOAD_DIR; ?></li>
<li><strong>Dir exists:</strong> <?php echo is_dir(UPLOAD_DIR) ? 'Yes' : 'No'; ?></li>
<li><strong>Dir writable:</strong> <?php echo is_writable(UPLOAD_DIR) ? 'Yes' : 'No'; ?></li>
<li><strong>Log dir:</strong> <?php echo UPLOAD_DIR; ?></li>
<li><strong>Log dir writable:</strong> <?php echo is_writable(UPLOAD_DIR) ? 'Yes' : 'No'; ?></li>
</ul>
<h2>Recent Upload Logs:</h2>
<?php
$error_log = UPLOAD_DIR . "upload_errors.log";
$success_log = UPLOAD_DIR . "upload_success.log";
$early_log_file = UPLOAD_DIR . "upload_early.log";
if (file_exists($early_log_file)) {
echo "<h3>Early Access Log (last 10 entries):</h3><pre>";
$lines = array_slice(file($early_log_file), -10);
echo implode("", $lines);
echo "</pre>";
} else {
echo "<h3>Early Access Log:</h3><p>No early log found at: $early_log_file</p>";
}
if (file_exists($error_log)) {
echo "<h3>Error Log (last 10 entries):</h3><pre>";
$lines = array_slice(file($error_log), -10);
echo implode("", $lines);
echo "</pre>";
} else {
echo "<h3>Error Log:</h3><p>No error log found at: $error_log</p>";
}
if (file_exists($success_log)) {
echo "<h3>Success Log (last 10 entries):</h3><pre>";
$lines = array_slice(file($success_log), -10);
echo implode("", $lines);
echo "</pre>";
} else {
echo "<h3>Success Log:</h3><p>No success log found at: $success_log</p>";
}
?>
<h2>PHP Upload Settings:</h2>
<ul>
<li><strong>file_uploads:</strong> <?php echo ini_get('file_uploads') ? 'Enabled' : 'Disabled'; ?></li>
<li><strong>upload_max_filesize:</strong> <?php echo ini_get('upload_max_filesize'); ?></li>
<li><strong>post_max_size:</strong> <?php echo ini_get('post_max_size'); ?></li>
<li><strong>max_file_uploads:</strong> <?php echo ini_get('max_file_uploads'); ?></li>
<li><strong>upload_tmp_dir:</strong> <?php echo ini_get('upload_tmp_dir') ?: 'Default'; ?></li>
<li><strong>Temp dir writable:</strong> <?php echo is_writable(ini_get('upload_tmp_dir') ?: sys_get_temp_dir()) ? 'Yes' : 'No'; ?></li>
</ul>
<p><a href="upload_form.php">← Back to Upload Form</a></p>
</main>
</body>
</html>