Webbserverprogrammering 1

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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
<?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_msgFILE_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"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_entryFILE_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_entryFILE_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_chCURLOPT_POSTtrue);
  
curl_setopt($video_chCURLOPT_RETURNTRANSFERtrue);
  
curl_setopt($video_chCURLOPT_POSTFIELDS$params);
  
$response curl_exec($video_ch);

  
$output json_decode($responsetrue);
  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_chCURLOPT_POSTtrue);
  
curl_setopt($callback_chCURLOPT_POSTFIELDSjson_encode($callback_input));
  
curl_setopt($callback_chCURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  
curl_setopt($callback_chCURLOPT_TIMEOUT_MS1000);
  
curl_setopt($callback_chCURLOPT_CONNECTTIMEOUT_MS1000);
  
curl_setopt($callback_chCURLOPT_NOSIGNAL1);
  
curl_exec($callback_ch);

  
$output json_decode($responsetrue);
  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_strtrue);
}

function 
get_chunk_upload_dir(): string {
  if (!
is_dir(CHUNK_UPLOAD_DIR)) {
    @
mkdir(CHUNK_UPLOAD_DIR0755true);
  }
  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 $videostring $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 10242) . "MB, Max: " round(MAX_VIDEO_SIZE 1024 10242) . "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 10242) . "MB, Max: " round(MAX_IMAGE_SIZE 1024 10242) . "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>