-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
874 lines (800 loc) · 36.4 KB
/
functions.php
File metadata and controls
874 lines (800 loc) · 36.4 KB
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
<?php
/**
* Fonctions pures réutilisables — extraites de download.php et ctrl.php
*/
// ── Tuning constants ────────────────────────────────────────────────────────
// Adjust these to match your hardware. See CLAUDE.md for rationale.
const PROBE_MAX_CONCURRENT = 5; // max parallel ffprobe processes
const PROBE_TIMEOUT = 10; // ffprobe timeout (seconds)
const SUBTITLE_EXTRACT_TIMEOUT = 120; // ffmpeg subtitle extraction timeout (seconds)
const SUBTITLE_TRACK_MAX = 99; // max subtitle track index (anti-DoS)
const KEYFRAME_LOOKUP_TIMEOUT = 5; // ffprobe keyframe PTS lookup timeout (seconds)
const STREAM_SLOT_TIMEOUT = 15; // max wait for a stream slot (seconds)
const VMTOUCH_SIZE_LIMIT = 2 * 1024 * 1024 * 1024; // page-cache warm only files < 2 GB
const LOG_ROTATION_SIZE = 5 * 1024 * 1024; // rotate stream.log at 5 MB
const LOG_ROTATION_COUNT = 3; // keep 3 rotated log files
const AUTH_MAX_ATTEMPTS = 10; // password attempts before lockout
const AUTH_LOCKOUT_SLEEP = 3; // sleep seconds on lockout
const AUTH_FAIL_SLEEP = 1; // sleep seconds per failed attempt
// FFmpeg encoding defaults (overridable via config.php)
defined('FFMPEG_CRF') || define('FFMPEG_CRF', 22); // x264 quality (lower = better, 18-28 typical)
defined('FFMPEG_PRESET') || define('FFMPEG_PRESET', 'veryfast'); // x264 preset live streaming sur 8 cores
defined('FFMPEG_PRESET_HLS') || define('FFMPEG_PRESET_HLS', 'slow'); // x264 preset HLS (async, pré-généré en arrière-plan)
defined('FFMPEG_THREADS') || define('FFMPEG_THREADS', 4); // 50% des 8 cores, laisse marge pour rtorrent/flood/jellyfin
defined('FFMPEG_AUDIO_BITRATE') || define('FFMPEG_AUDIO_BITRATE', '192k'); // AAC audio bitrate
defined('FFMPEG_AUDIO_CHANNELS') || define('FFMPEG_AUDIO_CHANNELS', 2); // stereo downmix
defined('FFMPEG_GOP_SIZE_DEFAULT') || define('FFMPEG_GOP_SIZE_DEFAULT', 50); // keyframe interval transcode (2s@25fps, seek-friendly)
defined('FFMPEG_TUNE') || define('FFMPEG_TUNE', ''); // '' = désactivé, 'film' = archivage (coût CPU élevé en live)
defined('FFMPEG_BFRAMES') || define('FFMPEG_BFRAMES', 0); // 0 = defaults x264, sinon 2-3 (qualité++ mais encode plus lent)
defined('FFMPEG_REFS') || define('FFMPEG_REFS', 0); // 0 = defaults x264, sinon 3-4 (idem)
// FFmpeg HDR tonemapping — CPU-intensif, nécessite plus de threads (overridable via config.php)
defined('FFMPEG_HDR_THREADS') || define('FFMPEG_HDR_THREADS', 6); // tonemapping float32 gourmand (75% des 8 cores)
defined('FFMPEG_HDR_CRF') || define('FFMPEG_HDR_CRF', 22); // aligné avec SDR (le tonemapping domine le CPU, pas l'encodage)
/**
* Acquire a stream slot using flock — limits concurrent ffmpeg processes.
* Tries non-blocking first, falls back to blocking wait on slot 1.
* @return array{resource, bool} [file pointer, true if had to wait]
*/
function acquireStreamSlot(): array {
$max = defined('STREAM_MAX_CONCURRENT') ? STREAM_MAX_CONCURRENT : 3;
for ($i = 1; $i <= $max; $i++) {
$fp = fopen("/tmp/sharebox_stream_slot_{$i}.lock", 'w');
if (flock($fp, LOCK_EX | LOCK_NB)) {
return [$fp, false];
}
fclose($fp);
}
// Tous les slots occupés — polling round-robin avec détection déconnexion
// ignore_user_abort(false) permet à connection_aborted() de fonctionner
// même sans output envoyé (pas de headers flush à ce stade)
ignore_user_abort(false);
$deadline = microtime(true) + STREAM_SLOT_TIMEOUT;
while (microtime(true) < $deadline) {
for ($i = 1; $i <= $max; $i++) {
$fp = fopen("/tmp/sharebox_stream_slot_{$i}.lock", 'w');
if (flock($fp, LOCK_EX | LOCK_NB)) return [$fp, true];
fclose($fp);
}
if (connection_aborted()) exit;
usleep(100000); // 100ms entre chaque tour
}
http_response_code(503);
exit;
}
function releaseStreamSlot(mixed &$fp): void {
if (!is_resource($fp)) return;
flock($fp, LOCK_UN);
fclose($fp);
$fp = null;
}
/**
* Acquire a probe slot (non-blocking, max 5 concurrent ffprobe processes).
* Returns file pointer or null if all slots busy → caller should return 429.
* @return resource|null
*/
function acquireProbeSlot(): mixed {
for ($i = 1; $i <= PROBE_MAX_CONCURRENT; $i++) {
$fp = fopen("/tmp/sharebox_probe_slot_{$i}.lock", 'w');
if ($fp !== false && flock($fp, LOCK_EX | LOCK_NB)) return $fp;
if ($fp !== false) fclose($fp);
}
return null;
}
function releaseProbeSlot(mixed $fp): void {
if (!is_resource($fp)) return;
flock($fp, LOCK_UN);
fclose($fp);
}
/**
* Formate une taille en octets
*/
function format_taille(int $bytes): string {
if ($bytes < 1024) return $bytes . ' o';
if ($bytes < 1048576) return round($bytes / 1024, 1) . ' Ko';
if ($bytes < 1073741824) return round($bytes / 1048576, 1) . ' Mo';
return round($bytes / 1073741824, 2) . ' Go';
}
/**
* Retourne le type MIME de streaming pour une extension donnée
*/
function get_stream_mime(string $ext): ?string {
return match($ext) {
'mp4', 'm4v', 'mov' => 'video/mp4',
'webm' => 'video/webm',
'mkv' => 'video/x-matroska',
'avi' => 'video/x-msvideo',
'mp3' => 'audio/mpeg',
'aac', 'm4a' => 'audio/mp4',
'ogg', 'oga', 'opus' => 'audio/ogg',
'flac' => 'audio/flac',
'wav' => 'audio/wav',
default => null,
};
}
/**
* Vérifie récursivement si un dossier contient au moins un fichier vidéo.
* S'arrête dès le premier trouvé (early return).
*/
function dir_has_video(string $path): bool {
static $videoExts = ['mp4' => 1, 'm4v' => 1, 'mov' => 1, 'webm' => 1, 'mkv' => 1, 'avi' => 1];
try {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
);
$it->setMaxDepth(3);
foreach ($it as $f) {
try {
if ($f->isFile() && isset($videoExts[strtolower($f->getExtension())])) {
return true;
}
} catch (\UnexpectedValueException $e) { continue; }
}
} catch (\UnexpectedValueException $e) {
return false;
}
return false;
}
/**
* Retourne 'video', 'audio' ou null selon l'extension du fichier
*/
function get_media_type(string $filename): ?string {
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$mime = get_stream_mime($ext);
if (!$mime) return null;
return str_starts_with($mime, 'video/') ? 'video' : 'audio';
}
/**
* Extrait un titre et une année depuis un nom de dossier/fichier média.
* Ex: "Mobile Suit Gundam 0079" → ['title' => 'Mobile Suit Gundam 0079', 'year' => null]
* "Batman.Begins.2005.MULTI.2160p" → ['title' => 'Batman Begins', 'year' => 2005]
*/
function extract_title_year(string $name): array {
// Retirer l'extension si c'est un fichier
$clean = pathinfo($name, PATHINFO_EXTENSION) ? pathinfo($name, PATHINFO_FILENAME) : $name;
// Retirer les tags entre crochets (ex: [Torrent911.com], [1080p], [FR])
$clean = preg_replace('/\[.*?\]/', '', $clean);
// Remplacer les séparateurs courants par des espaces
$clean = preg_replace('/[._()[\]{}:]+/', ' ', $clean);
// Retirer la numérotation en début (ex: "01 - ", "01. ", "95 - ")
$clean = preg_replace('/^\s*\d{1,3}\s*[-–.]\s*/', '', $clean);
// Chercher une année (4 chiffres entre 1950 et 2099)
// Si range d'années proches (ex: "1997-2003" = série), prendre la première (TMDB indexe par début).
// Sinon prendre la dernière (ex: "2001 A Space Odyssey 1968" → 1968 est l'année de sortie).
$year = null;
if (preg_match_all('/\b((?:19|20)\d{2})\b/', $clean, $m)) {
$first = (int)reset($m[1]);
$last = (int)end($m[1]);
$year = (count($m[1]) > 1 && abs($last - $first) <= 10) ? $first : $last;
}
// Remove season/saison markers before cutting to tech tags (they pollute TMDB search)
// Handles: "Saison 3", "Season 2", "34 Saisons", "4 Seasons", "Season 1-4", "S01-S07"
// Also handles ordinal forms: "2nd Season", "3rd Season", "1st Season"
$clean = preg_replace('/\b\d*\s*(saisons?|seasons?)\s*\d*(?:\s*[-–]\s*\d+)?\b/i', ' ', $clean);
$clean = preg_replace('/\b\d+(st|nd|rd|th)\s+seasons?\b/i', ' ', $clean);
$clean = preg_replace('/\bS\d{1,2}\s*[-–]\s*S\d{1,2}\b/i', ' ', $clean);
// Remove common non-title words that confuse TMDB
$clean = preg_replace('/\b(int[eé]grale|collection|custom|restored|remast(?:er)?ed|pack|films?\s+\d+\s+a\s+\d+|oav|mini\s+film)\b/iu', ' ', $clean);
// Remove site tags like "Torrent911.com"
$clean = preg_replace('/\b\w+\.(com|org|net|eu|io)\b/i', '', $clean);
// Remove "HD Remasted" pattern
$clean = preg_replace('/\bHD\s+Remast\w*/i', '', $clean);
// Couper au premier tag technique
$title = preg_replace('/\b(multi|vff|vfq|truefrench|french|english|vostfr|vost|subfrench|dual|bluray|blu-ray|bdrip|brrip|webrip|web-?dl|hdtv|dvdrip|hdrip|x264|x265|h264|h265|hevc|avc|xvid|divx|avi|mpeg|mpg|10bit|remux|2160p|1080p|720p|480p|uhd|4k|hdr|hdr10|dts|truehd|atmos|aac|ac3|flac|ddp?\d|proper\d?|repack|internal|extended|unrated|directors?-?cut|complete|s\d{2}e?\d{0,2}|e\d{2,4})\b.*/i', '', $clean);
// "DC" = Directors Cut — retire seulement en fin de titre (évite de couper "DC Comics" au début)
$title = preg_replace('/\s+dc\s*$/i', '', $title);
// Si on a coupé à l'année, la retirer du titre aussi
if ($year) {
$title = preg_replace('/\b' . $year . '\b/', '', $title);
}
// Clean trailing junk: dashes, numbers, stray words
$title = preg_replace('/\s*-\s*$/', '', $title);
$title = preg_replace('/\s{2,}/', ' ', trim($title));
// Fallback : le nom brut nettoyé
if ($title === '') $title = trim($clean);
// Un code saison/épisode nu (S01, E03...) n'est pas un titre exploitable
if (preg_match('/^[SE]\d{1,2}$/i', $title)) $title = '';
// Nom de dossier générique sans contexte → pas de titre exploitable
if (preg_match('/^(movies?|films?|s[eé]ries?|videos?|specials?|extras?|bonus|ova|oav)$/i', $title)) $title = '';
return ['title' => $title, 'year' => $year];
}
/**
* Génère un slug lisible depuis un nom de fichier/dossier
* Ex: "Batman.Begins.2005.MULTI.2160p.mkv" → "batman-begins-2005-x7k2"
*/
function generate_slug(string $name, PDO $db): string {
// Retirer l'extension
$slug = pathinfo($name, PATHINFO_FILENAME);
// Translittérer les accents (é→e, ü→u, etc.)
$slug = @iconv('UTF-8', 'ASCII//TRANSLIT', $slug);
if (!$slug) $slug = pathinfo($name, PATHINFO_FILENAME);
$slug = strtolower($slug);
// Remplacer séparateurs courants par des tirets
$slug = preg_replace('/[\s._()[\]{}]+/', '-', $slug);
// Couper au premier tag technique (tout ce qui suit est du bruit)
$slug = preg_replace('/-(multi|vff|vfq|truefrench|french|english|vostfr|subfrench|bluray|blu-ray|bdrip|brrip|webrip|web-?dl|hdtv|dvdrip|hdrip|x264|x265|h264|h265|hevc|avc|10bit|remux|2160p|1080p|720p|480p|uhd|4k|hdr|hdr10|dts|truehd|atmos|aac|ac3|flac|ddp?\d|proper|repack|internal|extended|unrated|directors?-?cut|complete|s\d{2}e?\d{0,2}).*/i', '', $slug);
// Ne garder que lettres, chiffres, tirets
$slug = preg_replace('/[^a-z0-9-]/', '', $slug);
// Nettoyer les tirets multiples et aux extrémités
$slug = preg_replace('/-{2,}/', '-', $slug);
$slug = trim($slug, '-');
// Tronquer à 40 chars max
if (strlen($slug) > 40) {
$slug = substr($slug, 0, 40);
$slug = rtrim($slug, '-');
}
// Fallback si slug vide
if ($slug === '') $slug = 'partage';
// Ajouter suffixe random (4 chars alphanum)
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$attempts = 0;
do {
if (++$attempts > 100) {
throw new RuntimeException('Impossible de générer un token unique après 100 tentatives');
}
$suffix = '';
for ($i = 0; $i < 4; $i++) $suffix .= $chars[random_int(0, 35)];
$candidate = $slug . '-' . $suffix;
$check = $db->prepare("SELECT COUNT(*) FROM links WHERE token = :t");
$check->execute([':t' => $candidate]);
} while ($check->fetchColumn() > 0);
return $candidate;
}
/**
* Calcule la taille totale d'un répertoire récursivement
*/
function dir_size(string $path): int {
$size = 0;
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS));
foreach ($it as $file) {
if ($file->isFile()) $size += $file->getSize();
}
return $size;
}
/**
* Vérifie qu'un chemin résolu reste dans le répertoire de base autorisé
*/
/**
* Normalize a path to the filesystem encoding (NFD on Linux).
* Prevents NFC/NFD duplicates in DB by always using realpath() when possible.
*/
function normalize_path(string $path): string {
$real = realpath($path);
return $real !== false ? $real : $path;
}
function is_path_within(string|false $resolvedPath, string $basePath): bool {
if ($resolvedPath === false) return false;
$base = rtrim($basePath, '/');
if ($resolvedPath === $base || str_starts_with($resolvedPath, $base . '/')) {
return true;
}
// $basePath peut etre un symlink : verifier aussi contre sa cible reelle
$realBase = realpath($basePath);
if ($realBase !== false) {
$realBase = rtrim($realBase, '/');
if ($resolvedPath === $realBase || str_starts_with($resolvedPath, $realBase . '/')) {
return true;
}
}
// Chemin NVMe : les symlinks dans BASE_PATH peuvent pointer vers NVME_PATH
if (defined('NVME_PATH')) {
$nvme = rtrim(NVME_PATH, '/');
if ($resolvedPath === $nvme || str_starts_with($resolvedPath, $nvme . '/')) {
return true;
}
}
return false;
}
// ── Logging ─────────────────────────────────────────────────────────────────
/**
* Retourne le chemin vers ffmpeg_errors.log et rotate si nécessaire (5 MB max, 3 fichiers).
* À appeler juste avant chaque invocation ffmpeg pour éviter que stream.log soit pollué.
*/
function ffmpeg_log_path(): string {
if (!defined('STREAM_LOG') || !STREAM_LOG) return '/dev/null';
$logFile = dirname(STREAM_LOG) . '/ffmpeg_errors.log';
if (@filesize($logFile) > LOG_ROTATION_SIZE) {
for ($r = LOG_ROTATION_COUNT; $r > 1; $r--) @rename($logFile . '.' . ($r - 1), $logFile . '.' . $r);
@rename($logFile, $logFile . '.1');
}
return $logFile;
}
/**
* Log avec rotation (5 MB max, 3 fichiers). Channels : stream, poster, app.
*/
function sharebox_log(string $msg, string $channel = 'stream'): void {
if (!defined('STREAM_LOG') || !STREAM_LOG) return;
$logFile = $channel === 'stream' ? STREAM_LOG : dirname(STREAM_LOG) . '/' . $channel . '.log';
if (@filesize($logFile) > LOG_ROTATION_SIZE) {
for ($r = LOG_ROTATION_COUNT; $r > 1; $r--) @rename($logFile . '.' . ($r - 1), $logFile . '.' . $r);
@rename($logFile, $logFile . '.1');
}
$caller = php_sapi_name() === 'cli' ? 'CLI' : ($_SERVER['REMOTE_ADDR'] ?? '-');
$line = '[' . date('Y-m-d H:i:s') . '] [' . $caller . '] ' . $msg . "\n";
@file_put_contents($logFile, $line, FILE_APPEND | LOCK_EX);
}
// Aliases pour compatibilité et lisibilité
function stream_log(string $msg): void { sharebox_log($msg, 'stream'); }
function poster_log(string $msg): void { sharebox_log($msg, 'poster'); }
function app_log(string $msg): void { sharebox_log($msg, 'app'); }
// ── TMDB helpers ───────────────────────────────────────────────────────────
/**
* Construit les variantes de recherche pour un titre (du plus précis au plus large).
* @return string[]
*/
function tmdb_build_queries(string $title): array {
$queries = [$title];
$shorter = preg_replace('/\b(hd|remasted|remastered|complete|integrale|intégrale|collection|pack|coffret)\b.*/i', '', $title);
$shorter = trim($shorter);
if ($shorter !== '' && $shorter !== $title) $queries[] = $shorter;
$words = explode(' ', $title);
if (count($words) > 3) {
$half = implode(' ', array_slice($words, 0, (int)ceil(count($words) / 2)));
if ($half !== $title && $half !== $shorter) $queries[] = $half;
}
return $queries;
}
/**
* Fetch a TMDB API URL with retry on 429/5xx and exponential backoff.
* @return array|null Decoded JSON or null on failure
*/
function tmdb_fetch(string $url, $ctx, int $maxRetries = 2): ?array {
for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
$resp = @file_get_contents($url, false, $ctx);
$status = 0;
if (isset($http_response_header[0]) && preg_match('/\s(\d{3})/', $http_response_header[0], $m)) {
$status = (int)$m[1];
}
if ($resp !== false && $status >= 200 && $status < 400) {
return json_decode($resp, true);
}
if ($attempt < $maxRetries) {
if ($status === 429) {
// Rate limited — check Retry-After or wait 2s
$wait = 2;
foreach ($http_response_header as $h) {
if (stripos($h, 'retry-after:') === 0) {
$wait = min(5, max(1, (int)trim(substr($h, 12))));
}
}
usleep($wait * 1000000);
} else {
// Network error or 5xx — exponential backoff
usleep(500000 * ($attempt + 1));
}
}
}
// Log failures for debugging (hide API key)
$safeUrl = preg_replace('/api_key=[^&]+/', 'api_key=***', $url);
if (function_exists('ai_log')) ai_log('TMDB fetch failed after ' . ($maxRetries + 1) . ' attempts: ' . $safeUrl);
return null;
}
/**
* Cherche un titre sur TMDB et retourne TOUS les candidats (pour le pick IA).
* @return array[] Array of {id, title, year, type, overview, poster}
*/
function tmdb_search_candidates(string $title, ?int $year, string $apiKey, $ctx, int $limit = 15): array {
$candidates = [];
$seenIds = [];
$encoded = urlencode($title);
$urls = [
"https://api.themoviedb.org/3/search/multi?api_key={$apiKey}&query={$encoded}&language=fr&page=1",
"https://api.themoviedb.org/3/search/tv?api_key={$apiKey}&query={$encoded}&language=fr&page=1",
"https://api.themoviedb.org/3/search/movie?api_key={$apiKey}&query={$encoded}&language=fr&page=1",
];
if ($year) {
$urls[] = "https://api.themoviedb.org/3/search/multi?api_key={$apiKey}&query=" . urlencode($title . ' ' . $year) . "&language=fr&page=1";
}
foreach ($urls as $searchUrl) {
$data = tmdb_fetch($searchUrl, $ctx);
if (!$data || empty($data['results'])) continue;
foreach ($data['results'] as $r) {
if (empty($r['poster_path']) || isset($seenIds[$r['id']])) continue;
$seenIds[$r['id']] = true;
$candidates[] = [
'id' => $r['id'],
'title' => $r['title'] ?? $r['name'] ?? '?',
'original_title' => $r['original_title'] ?? $r['original_name'] ?? null,
'year' => substr($r['release_date'] ?? $r['first_air_date'] ?? '', 0, 4),
'type' => $r['media_type'] ?? ($r['first_air_date'] ?? false ? 'tv' : 'movie'),
'overview' => substr($r['overview'] ?? '', 0, 150),
'poster' => 'https://image.tmdb.org/t/p/w300' . $r['poster_path'],
'rating' => round((float)($r['vote_average'] ?? 0), 1),
'vote_count' => (int)($r['vote_count'] ?? 0),
];
if (count($candidates) >= $limit) break 2;
}
usleep(300000);
}
return $candidates;
}
/**
* Score a TMDB candidate against an extracted title/year.
* Returns 0-100 reflecting match confidence.
*
* @param array $candidate {id, title, year, type, overview, poster, vote_count?}
* @param bool $preferTv True if folder context suggests TV (has season subfolders)
*/
function tmdb_score_candidate(string $extractedTitle, ?int $extractedYear, array $candidate, bool $preferTv = false): int {
$score = 0;
// ── Title similarity (0-65 points) ──
$norm = function(string $s): string {
$s = mb_strtolower($s);
$trans = @iconv('UTF-8', 'ASCII//TRANSLIT', $s);
$ascii = ($trans !== false) ? trim(preg_replace('/[^a-z0-9 ]/', '', $trans)) : '';
if ($ascii !== '') {
$s = $ascii;
} else {
// Non-latin (kanji, hangul…): keep as-is, just strip punctuation
$s = preg_replace('/[\p{P}\p{S}]/u', '', $s);
}
return trim(preg_replace('/\s+/', ' ', $s));
};
$a = $norm($extractedTitle);
if ($a === '') return 0;
// Tronquer pour éviter O(n³) de similar_text sur des noms de release longs
if (mb_strlen($a) > 80) $a = mb_substr($a, 0, 80);
$lenA = mb_strlen($a);
// Score against localized title
$b = $norm($candidate['title'] ?? '');
$bestPct = 0;
$bestB = $b;
if ($b !== '') {
similar_text($a, $b, $pct);
// Penalize length divergence to avoid short-title false positives ("One" vs "One Piece")
$lenB = mb_strlen($b);
$lenRatio = min($lenA, $lenB) / max($lenA, $lenB);
if ($lenRatio < 0.5) $pct *= $lenRatio * 1.5;
$bestPct = $pct;
}
// Also try original title (handles anime, non-English media)
$bOrig = isset($candidate['original_title']) ? $norm($candidate['original_title']) : '';
if ($bOrig !== '' && $bOrig !== $b) {
similar_text($a, $bOrig, $pctOrig);
// Same length penalty for original title
$lenBO = mb_strlen($bOrig);
$lenRatioO = min($lenA, $lenBO) / max($lenA, $lenBO);
if ($lenRatioO < 0.5) $pctOrig *= $lenRatioO * 1.5;
if ($pctOrig > $bestPct) {
$bestPct = $pctOrig;
$bestB = $bOrig;
}
}
if ($bestB === '') return 0;
$score += (int)round($bestPct * 0.65);
// Substring bonus — additive, proportional to length ratio to avoid false positives
// Skip very short titles (< 4 chars) to prevent "One" matching "One Piece"
if ($a !== $bestB && mb_strlen($a) >= 4 && (str_contains($bestB, $a) || str_contains($a, $bestB))) {
$shorter = min(mb_strlen($a), mb_strlen($bestB));
$longer = max(mb_strlen($a), mb_strlen($bestB));
$ratio = $shorter / $longer;
$score += (int)round(8 * $ratio);
}
// ── Year (0-15 points) ──
$cYear = (int)($candidate['year'] ?? 0);
if ($extractedYear && $cYear) {
if ($cYear === $extractedYear) {
$score += 15;
} elseif (abs($cYear - $extractedYear) <= 1) {
$score += 10;
}
}
// ── Type coherence (0-10 points) ──
$cType = $candidate['type'] ?? '';
if ($preferTv && $cType === 'tv') {
$score += 10;
} elseif (!$preferTv && $cType === 'movie') {
$score += 10;
} elseif ($cType === 'tv' || $cType === 'movie') {
$score += 3; // wrong preference but still valid media
}
// ── Popularity (0-12 points) — finer granularity to break ties ──
$voteCount = (int)($candidate['vote_count'] ?? 0);
if ($voteCount > 3000) {
$score += 12;
} elseif ($voteCount > 1000) {
$score += 10;
} elseif ($voteCount > 500) {
$score += 8;
} elseif ($voteCount > 100) {
$score += 5;
} elseif ($voteCount > 10) {
$score += 2;
}
return min(100, $score);
}
/**
* Convert a tmdb_score_candidate score to a verified level.
*/
function tmdb_score_to_verified(int $score): int {
if ($score >= 80) return 80;
if ($score >= 55) return 60;
if ($score >= 35) return 40;
return 0; // below threshold — no match
}
// ── FFmpeg helpers ──────────────────────────────────────────────────────────
const ALLOWED_QUALITIES = [480, 576, 720, 1080];
const ALLOWED_FILTER_MODES = ['none', 'anime', 'detail', 'night', 'deinterlace', 'hdr'];
function validateQuality(int $quality): int {
return in_array($quality, ALLOWED_QUALITIES, true) ? $quality : 720;
}
function validateFilterMode(string $mode): string {
return in_array($mode, ALLOWED_FILTER_MODES, true) ? $mode : 'none';
}
function validateBurnSub(int $burnSub, ?int $subCount = null): int {
if ($burnSub < 0 || $burnSub >= 50) return -1;
if ($subCount !== null && $burnSub >= $subCount) return -1;
return $burnSub;
}
/**
* Compte les pistes sous-titres d'un fichier via probe_cache.
*/
function getSubtitleCount(PDO $db, string $path): int {
try {
$stmt = $db->prepare("SELECT result FROM probe_cache WHERE path = :p");
$stmt->execute([':p' => $path]);
if ($row = $stmt->fetch()) {
$data = json_decode($row['result'], true);
return count($data['subtitles'] ?? []);
}
} catch (PDOException $e) { /* ignore */ }
return 0;
}
/**
* Détecte automatiquement si un fichier nécessite le filtre HDR→SDR.
* @param PDO $db Database connection
* @param string $path Chemin absolu du fichier
* @return bool True si le fichier est en HDR (smpte2084, arib-std-b67, smpte428)
*/
function isHDRFile(PDO $db, string $path): bool {
try {
$stmt = $db->prepare("SELECT result FROM probe_cache WHERE path = :p");
$stmt->execute([':p' => $path]);
if ($row = $stmt->fetch()) {
$data = json_decode($row['result'], true);
$ct = $data['colorTransfer'] ?? '';
return in_array($ct, ['smpte2084', 'arib-std-b67', 'smpte428'], true);
}
} catch (PDOException $e) { /* ignore */ }
return false;
}
/**
* Construit le filter_complex ffmpeg pour transcode (avec ou sans burn-in sous-titre).
*/
function buildFilterGraph(int $quality, int $audioTrack, int $burnSub = -1, string $filterMode = 'none'): string {
// Construit la chaîne de filtres vidéo selon le mode
$scaleFilter = 'scale=-2:\'min(' . $quality . ',ih)\':flags=lanczos';
// HDR : downscale dans le premier zscale AVANT conversion float32 (2.6x plus rapide)
// Convertit quality (hauteur) en largeur 16:9 pour réduire les pixels avant le pipeline float32
$hdrWidth = (int)(ceil($quality * 16 / 9 / 2) * 2); // arrondi pair
$videoFilters = match($filterMode) {
'hdr' => 'zscale=w=\'min(' . $hdrWidth . '\\,iw)\':h=-2:t=linear:npl=100:p=bt709,format=gbrpf32le,tonemap=mobius:desat=0,zscale=t=bt709:m=bt709:r=tv',
'anime' => $scaleFilter . ',deband=1thr=0.04:2thr=0.04:3thr=0.04:4thr=0.04,unsharp=5:5:0.7:5:5:0.0',
'detail' => $scaleFilter . ',cas=0.5',
'night' => $scaleFilter . ',eq=gamma=1.4:brightness=0.05:contrast=1.1',
'deinterlace' => 'bwdif=mode=send_frame:parity=auto:deint=all,' . $scaleFilter,
default => $scaleFilter,
};
$videoFilters .= ',format=yuv420p';
if ($burnSub >= 0) {
// Scale vidéo d'abord, puis overlay sous-titres (meilleure lisibilité du texte)
return '"[0:v:0]' . $videoFilters . '[sv];[0:s:' . $burnSub . '][sv]scale2ref[ss][sv2];[sv2][ss]overlay=eof_action=pass[v];'
. '[0:a:' . $audioTrack . ']aresample=async=3000[a]"';
}
return '"[0:v:0]' . $videoFilters . '[v];'
. '[0:a:' . $audioTrack . ']aresample=async=3000[a]"';
}
/**
* Vérifie si un fichier a au moins une piste audio (via probe_cache).
*/
function hasAudioTrack(PDO $db, string $path): bool {
try {
$stmt = $db->prepare("SELECT result FROM probe_cache WHERE path = :p");
$stmt->execute([':p' => $path]);
if ($row = $stmt->fetch()) {
$data = json_decode($row['result'], true);
return !empty($data['audio']);
}
} catch (PDOException $e) { /* ignore */ }
return true; // assume audio exists if no probe data
}
/**
* Construit les arguments d'entrée ffmpeg communs.
*/
function buildFfmpegInputArgs(string $filePath, string $seekBefore = ''): string {
return 'timeout 3600 ionice -c 2 -n 0 nice -n 5 ffmpeg -nostdin' . $seekBefore . ' -thread_queue_size 512 -fflags +genpts+discardcorrupt -i ' . escapeshellarg($filePath);
}
/**
* Construit les arguments encodeur x264+AAC communs.
*/
function buildFfmpegCodecArgs(int $gopSize = FFMPEG_GOP_SIZE_DEFAULT, bool $isHDR = false, bool $isHLS = false): string {
$threads = $isHDR ? FFMPEG_HDR_THREADS : FFMPEG_THREADS;
$crf = $isHDR ? FFMPEG_HDR_CRF : FFMPEG_CRF;
$preset = $isHLS ? FFMPEG_PRESET_HLS : FFMPEG_PRESET;
$args = ' -c:v libx264 -preset ' . $preset;
/** @phpstan-ignore notIdentical.alwaysFalse */
if (FFMPEG_TUNE !== '') {
$args .= ' -tune ' . FFMPEG_TUNE;
}
$args .= ' -crf ' . $crf
. ' -profile:v high -level 4.1';
/** @phpstan-ignore greater.alwaysFalse */
if (FFMPEG_BFRAMES > 0) {
$args .= ' -bf ' . FFMPEG_BFRAMES;
}
/** @phpstan-ignore greater.alwaysFalse */
if (FFMPEG_REFS > 0) {
$args .= ' -refs ' . FFMPEG_REFS;
}
$args .= ' -g ' . $gopSize . ' -threads ' . $threads
. ' -colorspace bt709 -color_primaries bt709 -color_trc bt709'
. ' -c:a aac -ac ' . FFMPEG_AUDIO_CHANNELS . ' -b:a ' . FFMPEG_AUDIO_BITRATE . ' -shortest';
if ($isHLS) {
$args .= ' -force_key_frames "expr:gte(t,n_forced*4)"';
}
return $args;
}
/**
* Arguments muxer fMP4 (fragmented MP4 pour streaming progressif).
*/
function buildFmp4MuxerArgs(): string {
return ' -avoid_negative_ts make_zero -start_at_zero'
. ' -max_muxing_queue_size 4096 -min_frag_duration 2000000'
. ' -movflags frag_keyframe+empty_moov+default_base_moof';
}
/**
* Calcule les épisodes précédent/suivant pour la navigation dans le player.
*
* @param string $subPath Sous-chemin relatif du fichier courant (ex: "Season1/ep02.mkv")
* @param string $basePath Chemin absolu du dossier partagé
* @param string $baseUrl URL de base du lien (ex: "/dl/mon-token")
* @return array{prev: ?array<string, string>, next: ?array<string, string>}
*/
function computeEpisodeNav(string $subPath, string $basePath, string $baseUrl): array {
$prevFile = null;
$nextFile = null;
$parentSub = dirname($subPath);
$parentDir = ($parentSub === '.') ? $basePath : $basePath . '/' . $parentSub;
if (is_dir($parentDir)) {
$siblings = [];
foreach (scandir($parentDir) as $item) {
if ($item[0] === '.') continue;
if (is_file($parentDir . '/' . $item) && get_media_type($item) === 'video') {
$siblings[] = $item;
}
}
usort($siblings, 'strnatcasecmp');
$currentName = basename($subPath);
$idx = array_search($currentName, $siblings, true);
if ($idx !== false) {
if ($idx > 0) {
$pSub = ($parentSub === '.') ? $siblings[$idx - 1] : $parentSub . '/' . $siblings[$idx - 1];
$prevFile = ['name' => $siblings[$idx - 1], 'url' => $baseUrl . '?p=' . rawurlencode($pSub) . '&play=1', 'pp' => 'p=' . rawurlencode($pSub) . '&'];
}
if ($idx < count($siblings) - 1) {
$nSub = ($parentSub === '.') ? $siblings[$idx + 1] : $parentSub . '/' . $siblings[$idx + 1];
$nextFile = ['name' => $siblings[$idx + 1], 'url' => $baseUrl . '?p=' . rawurlencode($nSub) . '&play=1', 'pp' => 'p=' . rawurlencode($nSub) . '&'];
}
}
}
return ['prev' => $prevFile, 'next' => $nextFile];
}
/**
* Warm le fichier dans le page cache si < 2 Go.
*/
function warmFileCache(string $filePath): void {
if (!is_file($filePath)) return;
if (filesize($filePath) < VMTOUCH_SIZE_LIMIT) {
shell_exec('vmtouch -qt ' . escapeshellarg($filePath) . ' >/dev/null 2>&1 &');
}
}
/**
* Change le mot de passe d'un utilisateur.
* Retourne ['ok' => true] ou ['error' => '...'].
*/
function change_password_for_user(PDO $db, string $username, string $currentPwd, string $newPwd, string $confirmPwd): array {
if (strlen($newPwd) < 4) {
return ['error' => 'Nouveau mot de passe : 4 caractères minimum'];
}
if ($newPwd !== $confirmPwd) {
return ['error' => 'La confirmation ne correspond pas'];
}
$stmt = $db->prepare("SELECT password_hash FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if (!$user || !password_verify($currentPwd, $user['password_hash'])) {
return ['error' => 'Mot de passe actuel incorrect'];
}
$db->prepare("UPDATE users SET password_hash = ? WHERE username = ?")
->execute([password_hash($newPwd, PASSWORD_BCRYPT), $username]);
return ['ok' => true];
}
/**
* Supprime tous les liens expirés de la base.
* Retourne le nombre de liens supprimés.
*/
function purge_expired_links(PDO $db): int {
$stmt = $db->prepare("DELETE FROM links WHERE expires_at IS NOT NULL AND expires_at != '' AND expires_at < datetime('now')");
$stmt->execute();
return $stmt->rowCount();
}
/**
* Enregistre un événement dans activity_logs.
* Silencieux en cas d'erreur.
*/
function log_activity(string $event_type, ?string $username, ?string $ip, ?string $details): void
{
try {
$db = get_db();
$db->prepare(
"INSERT INTO activity_logs (event_type, username, ip, details) VALUES (?, ?, ?, ?)"
)->execute([$event_type, $username, $ip, $details]);
// Purge vieux logs max 1x/heure (évite un DELETE full-scan à chaque insert)
$purgeFlag = sys_get_temp_dir() . '/sharebox_purge_actlogs';
if (!file_exists($purgeFlag) || (time() - filemtime($purgeFlag)) > 3600) {
$db->exec("DELETE FROM activity_logs WHERE created_at < datetime('now', '-90 days')");
@touch($purgeFlag);
}
} catch (\Throwable $e) {
// Silencieux — les logs ne doivent pas casser l'app
}
}
/**
* Serve a file — nginx (X-Accel-Redirect) or PHP direct with Range support.
* Auto-detects based on XACCEL_PREFIX: non-empty → nginx, empty → PHP.
*/
function serve_file(string $path, string $contentType, string $disposition): void
{
header('Content-Type: ' . $contentType);
header('Content-Disposition: ' . $disposition);
// nginx: delegate to X-Accel-Redirect (zero-copy, supports resume natively)
if (defined('XACCEL_PREFIX') && XACCEL_PREFIX !== '') {
$encodedPath = XACCEL_PREFIX . str_replace('%2F', '/', rawurlencode($path));
header('X-Accel-Redirect: ' . $encodedPath);
exit;
}
// Apache / PHP direct: serve with Range support
$size = filesize($path);
set_time_limit(0);
while (ob_get_level()) {
ob_end_clean();
}
header('Accept-Ranges: bytes');
$rangeHeader = $_SERVER['HTTP_RANGE'] ?? '';
if ($rangeHeader && preg_match('/bytes=(\d*)-(\d*)/', $rangeHeader, $m)) {
if ($m[1] === '' && $m[2] !== '') {
// Suffix range: bytes=-N → last N bytes
$start = max(0, $size - (int)$m[2]);
$end = $size - 1;
} else {
$start = $m[1] !== '' ? (int)$m[1] : 0;
$end = $m[2] !== '' ? (int)$m[2] : $size - 1;
}
$end = min($end, $size - 1);
if ($start > $end || $start >= $size) {
header('HTTP/1.1 416 Range Not Satisfiable');
header('Content-Range: bytes */' . $size);
exit;
}
$length = $end - $start + 1;
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
header('Content-Length: ' . $length);
$fh = fopen($path, 'rb');
if ($fh === false) { http_response_code(500); exit; }
fseek($fh, $start);
$remaining = $length;
ignore_user_abort(false);
while ($remaining > 0 && !feof($fh) && !connection_aborted()) {
$chunk = fread($fh, min(65536, $remaining));
echo $chunk;
flush();
$remaining -= strlen($chunk);
}
fclose($fh);
} else {
header('Content-Length: ' . $size);
readfile($path);
}
exit;
}