BioTorrents.de’s version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

upload_handle.php 34KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. <?php
  2. //****************************************************************************//
  3. //--------------- Take upload ------------------------------------------------//
  4. // This pages handles the backend of the torrent upload function. It checks //
  5. // the data, and if it all validates, it builds the torrent file, then writes //
  6. // the data to the database and the torrent to the disk. //
  7. //****************************************************************************//
  8. // Maximum allowed size for uploaded files
  9. // https://php.net/upload-max-filesize
  10. ini_set('upload_max_filesize', 2097152); // 2 MiB
  11. # Allow many uncompressed files,
  12. # e.g., http://academictorrents.com/details/5a447ff50062194bd58dd11c0fedead59e6d873c/tech
  13. ini_set('max_file_uploads', 10000);
  14. define('MAX_FILENAME_LENGTH', 255);
  15. include(SERVER_ROOT.'/classes/validate.class.php');
  16. include(SERVER_ROOT.'/classes/feed.class.php');
  17. include(SERVER_ROOT.'/sections/torrents/functions.php');
  18. include(SERVER_ROOT.'/classes/file_checker.class.php');
  19. enforce_login();
  20. authorize();
  21. $Validate = new Validate;
  22. $Feed = new Feed;
  23. //*****************************************************************************//
  24. //--------------- Set $Properties array ---------------------------------------//
  25. // This is used if the form doesn't validate, and when the time comes to enter //
  26. // it into the database.
  27. // todo: Do something about this mess
  28. //****************************************************************************//
  29. $Properties = [];
  30. $Type = $Categories[(int)$_POST['type']];
  31. $TypeID = $_POST['type'] + 1;
  32. $Properties['CategoryID'] = $TypeID;
  33. $Properties['CategoryName'] = $Type;
  34. # todo: Associate containers with categories beforehand
  35. # It may have to happen structurally in config.php, e.g.,
  36. # $Categories = [
  37. # 'GazelleName' => [$Name, $Icon, $Description, $Containers],
  38. # ...
  39. # ];
  40. $Properties['ArchiveTypes'] = $Archives;
  41. $Properties['FileTypes'] = [
  42. 'DNA' => $Containers,
  43. 'RNA' => $Containers,
  44. 'Proteins' => $ContainersProt,
  45. 'Imaging' => $ContainersGames,
  46. 'Extras' => $ContainersExtra
  47. ];
  48. $Properties['Title'] = $_POST['title'];
  49. $Properties['TitleRJ'] = $_POST['title_rj'];
  50. $Properties['TitleJP'] = $_POST['title_jp'];
  51. $Properties['Year'] = $_POST['year'];
  52. $Properties['Studio'] = isset($_POST['studio']) ? $_POST['studio'] : '';
  53. $Properties['Series'] = isset($_POST['series']) ? $_POST['series'] : '';
  54. $Properties['CatalogueNumber'] = isset($_POST['catalogue']) ? $_POST['catalogue'] : '';
  55. $Properties['Pages'] = isset($_POST['pages']) ? $_POST['pages'] : 0;
  56. $Properties['Container'] = isset($_POST['container']) ? $_POST['container'] : '';
  57. $Properties['Media'] = $_POST['media'];
  58. $Properties['Codec'] = isset($_POST['codec']) ? $_POST['codec'] : '';
  59. if (!($_POST['resolution'] ?? false)) {
  60. $_POST['resolution'] = $_POST['ressel'] ?? '';
  61. }
  62. $Properties['Resolution'] = $_POST['resolution'] ?? '';
  63. $Properties['AudioFormat'] = $_POST['audioformat'] ?? '';
  64. $Properties['Subbing'] = 'nil';
  65. $Properties['Language'] = 'nil';
  66. $Properties['Subber'] = isset($_POST['subber']) ? $_POST['subber'] : '';
  67. $Properties['DLsiteID'] = (isset($_POST['dlsiteid'])) ? $_POST['dlsiteid'] : '';
  68. $Properties['Censored'] = (isset($_POST['censored'])) ? '1' : '0';
  69. $Properties['Anonymous'] = (isset($_POST['anonymous'])) ? '1' : '0';
  70. $Properties['Archive'] = (isset($_POST['archive']) && $_POST['archive'] !== '---') ? $_POST['archive'] : '';
  71. if (isset($_POST['library_image'])) {
  72. $Properties['LibraryImage'] = $_POST['library_image'];
  73. }
  74. if (isset($_POST['tags'])) {
  75. $Properties['TagList'] = implode(',', array_unique(explode(',', str_replace(' ', '', $_POST['tags']))));
  76. }
  77. if (isset($_POST['image'])) {
  78. $Properties['Image'] = $_POST['image'];
  79. }
  80. if (isset($_POST['release'])) {
  81. $Properties['ReleaseGroup'] = $_POST['release'];
  82. }
  83. $Properties['GroupDescription'] = trim($_POST['album_desc']);
  84. $Properties['TorrentDescription'] = $_POST['release_desc'];
  85. $Properties['MediaInfo'] = 'nil';
  86. $Properties['Screenshots'] = isset($_POST['screenshots']) ? $_POST['screenshots'] : '';
  87. $Properties['Mirrors'] = isset($_POST['mirrors']) ? $_POST['mirrors'] : '';
  88. if ($_POST['album_desc']) {
  89. $Properties['GroupDescription'] = trim($_POST['album_desc']);
  90. } elseif ($_POST['desc']) {
  91. $Properties['GroupDescription'] = trim($_POST['desc']);
  92. $Properties['MediaInfo'] = 'nil';
  93. }
  94. if (isset($_POST['groupid'])) {
  95. $Properties['GroupID'] = $_POST['groupid'];
  96. }
  97. if (isset($Properties['GroupID'])) {
  98. $Properties['Artists'] = Artists::get_artist($Properties['GroupID']);
  99. }
  100. # todo: Make this more generalized
  101. if ($Type === 'Movies' || $Type === 'Manga' || $Type === 'Anime' || $Type === 'Games') {
  102. if (empty($_POST['idols'])) {
  103. $Err = "You didn't enter any artists/idols";
  104. } else {
  105. $Artists = $_POST['idols'];
  106. }
  107. } else {
  108. if (!empty($_POST['idols'])) {
  109. $Artists = $_POST['idols'];
  110. }
  111. }
  112. if (!empty($_POST['requestid'])) {
  113. $RequestID = $_POST['requestid'];
  114. $Properties['RequestID'] = $RequestID;
  115. }
  116. //******************************************************************************//
  117. //--------------- Validate data in upload form ---------------------------------//
  118. # torrents_group.CategoryID
  119. $Validate->SetFields(
  120. 'type',
  121. '1',
  122. 'inarray',
  123. 'Please select a valid type.',
  124. array('inarray' => array_keys($Categories))
  125. );
  126. # todo: Remove the switch statement
  127. switch ($Type) {
  128. /*
  129. case 'Imaging':
  130. if (!isset($_POST['groupid']) || !$_POST['groupid']) {
  131. # torrents.Media
  132. $Validate->SetFields(
  133. 'media',
  134. '1',
  135. 'inarray',
  136. 'Please select a valid platform.',
  137. array('inarray' => array_merge($Media, $MediaManga, $Platform))
  138. );
  139. # torrents.Container
  140. $Validate->SetFields(
  141. 'container',
  142. '1',
  143. 'inarray',
  144. 'Please select a valid format.',
  145. array('inarray' => array_merge($Containers, $ContainersGames))
  146. );
  147. }
  148. break;
  149. */
  150. default:
  151. if (!isset($_POST['groupid']) || !$_POST['groupid']) {
  152. # torrents_group.CatalogueNumber
  153. $Validate->SetFields(
  154. 'catalogue',
  155. '0',
  156. 'string',
  157. 'Accession Number must be between 0 and 50 characters.',
  158. array('maxlength' => 50, 'minlength' => 0)
  159. );
  160. # torrents.AudioFormat
  161. $Validate->SetFields(
  162. 'audioformat',
  163. '0',
  164. 'string',
  165. 'Version must be between 0 and 10 characters.',
  166. array('maxlength' => 10, 'minlength' => 0)
  167. );
  168. # torrents_group.Name
  169. $Validate->SetFields(
  170. 'title',
  171. '1',
  172. 'string',
  173. 'Torrent Title must be between 10 and 255 characters.',
  174. array('maxlength' => 255, 'minlength' => 10)
  175. );
  176. # torrents_group.NameRJ
  177. $Validate->SetFields(
  178. 'title_rj',
  179. '0',
  180. 'string',
  181. 'Organism must be between 0 and 255 characters.',
  182. array('maxlength' => 255, 'minlength' => 0)
  183. );
  184. # torrents_group.NameJP
  185. $Validate->SetFields(
  186. 'title_jp',
  187. '0',
  188. 'string',
  189. 'Strain/Variety must be between 0 and 255 characters.',
  190. array('maxlength' => 255, 'minlength' => 0)
  191. );
  192. # torrents_group.Studio
  193. $Validate->SetFields(
  194. 'studio',
  195. '0',
  196. 'string',
  197. 'Department/Lab must be between 0 and 100 characters.',
  198. array('maxlength' => 100, 'minlength' => 0)
  199. );
  200. # torrents_group.Series
  201. $Validate->SetFields(
  202. 'series',
  203. '0',
  204. 'string',
  205. 'Location must be between 0 and 100 characters.',
  206. array('maxlength' => 100, 'minlength' => 0)
  207. );
  208. /* todo: Fix the year validation
  209. # torrents_group.Year
  210. $Validate->SetFields(
  211. 'year',
  212. '1',
  213. 'number',
  214. 'The year of the original release must be entered.',
  215. array('maxlength' => 4, 'minlength' => 4)
  216. );
  217. */
  218. # torrents.Media
  219. $Validate->SetFields(
  220. 'media',
  221. '1',
  222. 'inarray',
  223. 'Please select a valid platform.',
  224. array('inarray' => array_merge($Media, $MediaManga))
  225. );
  226. /*
  227. # torrents.Container
  228. $Validate->SetFields(
  229. 'container',
  230. '1',
  231. 'inarray',
  232. 'Please select a valid format.',
  233. array('inarray' => array_merge($Containers, $ContainersGames))
  234. );
  235. */
  236. # torrents_group.TagList
  237. $Validate->SetFields(
  238. 'tags',
  239. '1',
  240. 'string',
  241. 'You must enter at least five tags. Maximum length is 500 characters.',
  242. array('maxlength' => 500, 'minlength' => 10)
  243. );
  244. # torrents_group.WikiImage
  245. $Validate->SetFields(
  246. 'image',
  247. '0',
  248. 'link',
  249. 'The image URL you entered was invalid.',
  250. array('maxlength' => 255, 'minlength' => 10) # x.yz/a.bc
  251. );
  252. }
  253. # torrents_group.WikiBody
  254. $Validate->SetFields(
  255. 'album_desc',
  256. '1',
  257. 'string',
  258. 'The description must be between 100 and 65535 characters.',
  259. array('maxlength' => 65535, 'minlength' => 100)
  260. );
  261. /* todo: Fix the Group ID validation
  262. # torrents_group.ID
  263. $Validate->SetFields(
  264. 'groupid',
  265. '0',
  266. 'number',
  267. 'Group ID was not numeric.'
  268. );
  269. */
  270. }
  271. $Err = $Validate->ValidateForm($_POST); // Validate the form
  272. # todo: Move all this validation code to the Validate class
  273. if (count(explode(',', $Properties['TagList'])) < 5) {
  274. $Err = 'You must enter at least 5 tags.';
  275. }
  276. if (!(isset($_POST['title']) || isset($_POST['title_rj']) || isset($_POST['title_jp']))) {
  277. $Err = 'You must enter at least one title.';
  278. }
  279. $File = $_FILES['file_input']; // This is our torrent file
  280. $TorrentName = $File['tmp_name'];
  281. if (!is_uploaded_file($TorrentName) || !filesize($TorrentName)) {
  282. $Err = 'No torrent file uploaded, or file is empty.';
  283. } elseif (substr(strtolower($File['name']), strlen($File['name']) - strlen('.torrent')) !== '.torrent') {
  284. $Err = "You seem to have put something other than a torrent file into the upload field. (".$File['name'].").";
  285. }
  286. // Multiple artists!
  287. $LogName = '';
  288. if (empty($Properties['GroupID']) && empty($ArtistForm)) {
  289. $ArtistNames = [];
  290. $ArtistForm = [];
  291. for ($i = 0; $i < count($Artists); $i++) {
  292. if (trim($Artists[$i]) !== '') {
  293. if (!in_array($Artists[$i], $ArtistNames)) {
  294. $ArtistForm[$i] = array('name' => Artists::normalise_artist_name($Artists[$i]));
  295. array_push($ArtistNames, $ArtistForm[$i]['name']);
  296. }
  297. }
  298. }
  299. $LogName .= Artists::display_artists($ArtistForm, false, true, false);
  300. } elseif (empty($ArtistForm)) {
  301. $DB->query("
  302. SELECT ta.ArtistID, ag.Name
  303. FROM torrents_artists AS ta
  304. JOIN artists_group AS ag ON ta.ArtistID = ag.ArtistID
  305. WHERE ta.GroupID = ?
  306. ORDER BY ag.Name ASC", $Properties['GroupID']);
  307. $ArtistForm = [];
  308. while (list($ArtistID, $ArtistName) = $DB->next_record(MYSQLI_BOTH, false)) {
  309. array_push($ArtistForm, array('id' => $ArtistID, 'name' => display_str($ArtistName)));
  310. array_push($ArtistsUnescaped, array('name' => $ArtistName));
  311. }
  312. $LogName .= Artists::display_artists($ArtistsUnescaped, false, true, false);
  313. }
  314. if ($Err) { // Show the upload form, with the data the user entered
  315. $UploadForm = $Type;
  316. include(SERVER_ROOT.'/sections/upload/upload.php');
  317. die();
  318. }
  319. ImageTools::blacklisted($Properties['Image']);
  320. //******************************************************************************//
  321. //--------------- Make variables ready for database input ----------------------//
  322. // Prepared SQL statements do this for us, so there is nothing to do here anymore
  323. $T = $Properties;
  324. //******************************************************************************//
  325. //--------------- Generate torrent file ----------------------------------------//
  326. $Tor = new BencodeTorrent($TorrentName, true);
  327. $PublicTorrent = $Tor->make_private(); // The torrent is now private
  328. $UnsourcedTorrent = $Tor->make_sourced(); // The torrent now has the source field set
  329. $InfoHash = pack('H*', $Tor->info_hash());
  330. if (isset($Tor->Dec['encrypted_files'])) {
  331. $Err = 'This torrent contains an encrypted file list which is not supported here.';
  332. }
  333. // File list and size
  334. list($TotalSize, $FileList) = $Tor->file_list();
  335. $NumFiles = count($FileList);
  336. $TmpFileList = [];
  337. $TooLongPaths = [];
  338. $DirName = (isset($Tor->Dec['info']['files']) ? Format::make_utf8($Tor->get_name()) : '');
  339. check_name($DirName); // Check the folder name against the blacklist
  340. foreach ($FileList as $File) {
  341. list($Size, $Name) = $File;
  342. // Check file name and extension against blacklist/whitelist
  343. check_file($Type, $Name);
  344. // Make sure the filename is not too long
  345. if (mb_strlen($Name, 'UTF-8') + mb_strlen($DirName, 'UTF-8') + 1 > MAX_FILENAME_LENGTH) {
  346. $TooLongPaths[] = "$DirName/$Name";
  347. }
  348. // Add file info to array
  349. $TmpFileList[] = Torrents::filelist_format_file($File);
  350. }
  351. if (count($TooLongPaths) > 0) {
  352. $Names = implode(' <br />', $TooLongPaths);
  353. $Err = "The torrent contained one or more files with too long a name:<br /> $Names";
  354. }
  355. $FilePath = $DirName;
  356. $FileString = implode("\n", $TmpFileList);
  357. $Debug->set_flag('upload: torrent decoded');
  358. if (!empty($Err)) { // Show the upload form, with the data the user entered
  359. $UploadForm = $Type;
  360. include(SERVER_ROOT.'/sections/upload/upload.php');
  361. die();
  362. }
  363. //******************************************************************************//
  364. //--------------- Autofill format and archive ----------------------------------//
  365. if ($T['Container'] === 'Autofill') {
  366. # torrents.Container
  367. $Validate->ParseExtensions(
  368. # $FileList
  369. $Tor->file_list(),
  370. # $Category
  371. $T['CategoryName'],
  372. # $FileTypes
  373. $T['FileTypes'],
  374. );
  375. }
  376. if ($T['Archive'] === 'Autofill') {
  377. /*
  378. # torrents.Archive
  379. $Validate->ParseExtensions(
  380. # $FileList
  381. $Tor->file_list(),
  382. # $Category
  383. $T['CategoryName'],
  384. # $FileTypes
  385. $T['FileTypes'],
  386. );
  387. */
  388. }
  389. //******************************************************************************//
  390. //--------------- Start database stuff -----------------------------------------//
  391. $Body = $T['GroupDescription'];
  392. // Trickery
  393. if (!preg_match('/^'.IMAGE_REGEX.'$/i', $T['Image'])) {
  394. $T['Image'] = '';
  395. }
  396. // Does it belong in a group?
  397. if ($T['GroupID']) {
  398. $DB->query("
  399. SELECT
  400. ID,
  401. WikiImage,
  402. WikiBody,
  403. RevisionID,
  404. Name,
  405. Year,
  406. TagList
  407. FROM torrents_group
  408. WHERE id = ?", $T['GroupID']);
  409. if ($DB->has_results()) {
  410. // Don't escape tg.Name. It's written directly to the log table
  411. list($GroupID, $WikiImage, $WikiBody, $RevisionID, $T['Title'], $T['Year'], $T['TagList']) = $DB->next_record(MYSQLI_NUM, array(4));
  412. $T['TagList'] = str_replace(array(' ', '.', '_'), array(', ', '.', '.'), $T['TagList']);
  413. if (!$T['Image'] && $WikiImage) {
  414. $T['Image'] = $WikiImage;
  415. }
  416. if (strlen($WikiBody) > strlen($Body)) {
  417. $Body = $WikiBody;
  418. if (!$T['Image'] || $T['Image'] === $WikiImage) {
  419. $NoRevision = true;
  420. }
  421. }
  422. $T['Artist'] = Artists::display_artists(Artists::get_artist($GroupID), false, false);
  423. }
  424. }
  425. if (!isset($GroupID) || !$GroupID) {
  426. foreach ($ArtistForm as $Num => $Artist) {
  427. // The album hasn't been uploaded. Try to get the artist IDs
  428. $DB->query("
  429. SELECT
  430. ArtistID,
  431. Name
  432. FROM artists_group
  433. WHERE Name = ?", $Artist['name']);
  434. if ($DB->has_results()) {
  435. while (list($ArtistID, $Name) = $DB->next_record(MYSQLI_NUM, false)) {
  436. if (!strcasecmp($Artist['name'], $Name)) {
  437. $ArtistForm[$Num] = ['id' => $ArtistID, 'name' => $Name];
  438. break;
  439. }
  440. }
  441. }
  442. }
  443. }
  444. // Needs to be here as it isn't set for add format until now
  445. $LogName .= $T['Title'];
  446. // For notifications. Take note now whether it's a new group
  447. $IsNewGroup = !isset($GroupID) || !$GroupID;
  448. //----- Start inserts
  449. if ((!isset($GroupID) || !$GroupID)) {
  450. // Array to store which artists we have added already, to prevent adding an artist twice
  451. $ArtistsAdded = [];
  452. foreach ($ArtistForm as $Num => $Artist) {
  453. if (!isset($Artist['id']) || !$Artist['id']) {
  454. if (isset($ArtistsAdded[strtolower($Artist['name'])])) {
  455. $ArtistForm[$Num] = $ArtistsAdded[strtolower($Artist['name'])];
  456. } else {
  457. // Create artist
  458. $DB->query("
  459. INSERT INTO artists_group (Name)
  460. VALUES ( ? )", $Artist['name']);
  461. $ArtistID = $DB->inserted_id();
  462. $Cache->increment('stats_artist_count');
  463. $ArtistForm[$Num] = array('id' => $ArtistID, 'name' => $Artist['name']);
  464. $ArtistsAdded[strtolower($Artist['name'])] = $ArtistForm[$Num];
  465. }
  466. }
  467. }
  468. unset($ArtistsAdded);
  469. }
  470. if (!isset($GroupID) || !$GroupID) {
  471. // Create torrent group
  472. $DB->query(
  473. "
  474. INSERT INTO torrents_group
  475. (CategoryID, Name, NameRJ, NameJP, Year,
  476. Series, Studio, CatalogueNumber, Pages, Time,
  477. WikiBody, WikiImage, DLsiteID)
  478. VALUES
  479. ( ?, ?, ?, ?, ?,
  480. ?, ?, ?, ?, NOW(),
  481. ?, ?, ? )",
  482. $TypeID,
  483. $T['Title'],
  484. $T['TitleRJ'],
  485. $T['TitleJP'],
  486. $T['Year'],
  487. $T['Series'],
  488. $T['Studio'],
  489. $T['CatalogueNumber'],
  490. $T['Pages'],
  491. $Body,
  492. $T['Image'],
  493. $T['DLsiteID']
  494. );
  495. $GroupID = $DB->inserted_id();
  496. foreach ($ArtistForm as $Num => $Artist) {
  497. $DB->query("
  498. INSERT IGNORE INTO torrents_artists (GroupID, ArtistID, UserID)
  499. VALUES ( ?, ?, ? )", $GroupID, $Artist['id'], $LoggedUser['ID']);
  500. $Cache->increment('stats_album_count');
  501. $Cache->delete_value('artist_groups_'.$Artist['id']);
  502. }
  503. $Cache->increment('stats_group_count');
  504. // Add screenshots
  505. // todo: Clear DB_MYSQL::exec_prepared_query() errors
  506. $Screenshots = explode("\n", $T['Screenshots']);
  507. $Screenshots = array_map('trim', $Screenshots);
  508. $Screenshots = array_filter($Screenshots, function ($s) {
  509. return preg_match('/^'.DOI_REGEX.'$/i', $s);
  510. });
  511. $Screenshots = array_unique($Screenshots);
  512. $Screenshots = array_slice($Screenshots, 0, 10);
  513. # Add optional web seeds similar to screenshots
  514. # Support an arbitrary and limited number of sources
  515. $Mirrors = explode("\n", $T['Mirrors']);
  516. $Mirrors = array_map('trim', $Mirrors);
  517. $Mirrors = array_filter($Mirrors, function ($s) {
  518. return preg_match('/^'.URL_REGEX.'$/i', $s);
  519. });
  520. $Mirrors = array_unique($Mirrors);
  521. $Mirrors = array_slice($Mirrors, 0, 2);
  522. # Downgrade TLS on resource URIs
  523. # Required for BEP 19 compatibility
  524. $Mirrors = str_ireplace('tps://', 'tp://', $Mirrors);
  525. # Perform the DB inserts here
  526. # Screenshots (Publications)
  527. if (!empty($Screenshots)) {
  528. $Screenshot = '';
  529. $DB->prepare_query("
  530. INSERT INTO torrents_screenshots
  531. (GroupID, UserID, Time, Image)
  532. VALUES (?, ?, NOW(), ?)", $GroupID, $LoggedUser['ID'], $Screenshot);
  533. foreach ($Screenshots as $Screenshot) {
  534. $DB->exec_prepared_query();
  535. }
  536. }
  537. # Mirrors
  538. if (!empty($Mirrors)) {
  539. $Mirror = '';
  540. $DB->prepare_query("
  541. INSERT INTO torrents_mirrors
  542. (GroupID, UserID, Time, Resource)
  543. VALUES (?, ?, NOW(), ?)", $GroupID, $LoggedUser['ID'], $Mirror);
  544. foreach ($Mirrors as $Mirror) {
  545. $DB->exec_prepared_query();
  546. }
  547. }
  548. # Main if/else
  549. } else {
  550. $DB->query("
  551. UPDATE torrents_group
  552. SET Time = NOW()
  553. WHERE ID = ?", $GroupID);
  554. $Cache->delete_value("torrent_group_$GroupID");
  555. $Cache->delete_value("torrents_details_$GroupID");
  556. $Cache->delete_value("detail_files_$GroupID");
  557. }
  558. // Description
  559. if (!isset($NoRevision) || !$NoRevision) {
  560. $DB->query("
  561. INSERT INTO wiki_torrents
  562. (PageID, Body, UserID, Summary, Time, Image)
  563. VALUES
  564. ( ?, ?, ?, 'Uploaded new torrent', NOW(), ? )", $GroupID, $T['GroupDescription'], $LoggedUser['ID'], $T['Image']);
  565. $RevisionID = $DB->inserted_id();
  566. // Revision ID
  567. $DB->query("
  568. UPDATE torrents_group
  569. SET RevisionID = ?
  570. WHERE ID = ?", $RevisionID, $GroupID);
  571. }
  572. // Tags
  573. $Tags = explode(',', $T['TagList']);
  574. if (!$T['GroupID']) {
  575. foreach ($Tags as $Tag) {
  576. $Tag = Misc::sanitize_tag($Tag);
  577. if (!empty($Tag)) {
  578. $Tag = Misc::get_alias_tag($Tag);
  579. $DB->query("
  580. INSERT INTO tags
  581. (Name, UserID)
  582. VALUES
  583. ( ?, ? )
  584. ON DUPLICATE KEY UPDATE
  585. Uses = Uses + 1;", $Tag, $LoggedUser['ID']);
  586. $TagID = $DB->inserted_id();
  587. $DB->query("
  588. INSERT INTO torrents_tags
  589. (TagID, GroupID, UserID)
  590. VALUES
  591. ( ?, ?, ? )
  592. ON DUPLICATE KEY UPDATE TagID=TagID", $TagID, $GroupID, $LoggedUser['ID']);
  593. }
  594. }
  595. }
  596. // Use this section to control freeleeches
  597. $T['FreeTorrent'] = '0';
  598. $T['FreeLeechType'] = '0';
  599. $DB->query("
  600. SELECT Name, First, Second
  601. FROM misc
  602. WHERE Second = 'freeleech'");
  603. if ($DB->has_results()) {
  604. $FreeLeechTags = $DB->to_array('Name');
  605. foreach ($FreeLeechTags as $Tag => $Exp) {
  606. if ($Tag === 'global' || in_array($Tag, $Tags)) {
  607. $T['FreeTorrent'] = '1';
  608. $T['FreeLeechType'] = '3';
  609. break;
  610. }
  611. }
  612. }
  613. // Torrents over a size in bytes are neutral leech
  614. // Download doesn't count, upload does
  615. if (($TotalSize > 10737418240)) { # 10 GiB
  616. $T['FreeTorrent'] = '2';
  617. $T['FreeLeechType'] = '2';
  618. }
  619. // Torrent
  620. $DB->query(
  621. "
  622. INSERT INTO torrents
  623. (GroupID, UserID, Media, Container, Codec, Resolution,
  624. AudioFormat, Subbing, Language, Subber, Censored,
  625. Anonymous, Archive, info_hash, FileCount, FileList, FilePath, Size, Time,
  626. Description, MediaInfo, FreeTorrent, FreeLeechType)
  627. VALUES
  628. ( ?, ?, ?, ?, ?, ?,
  629. ?, ?, ?, ?, ?,
  630. ?, ?, ?, ?, ?, ?, ?, NOW(),
  631. ?, ?, ?, ? )",
  632. $GroupID,
  633. $LoggedUser['ID'],
  634. $T['Media'],
  635. $T['Container'],
  636. $T['Codec'],
  637. $T['Resolution'],
  638. $T['AudioFormat'],
  639. $T['Subbing'],
  640. $T['Language'],
  641. $T['Subber'],
  642. $T['Censored'],
  643. $T['Anonymous'],
  644. $T['Archive'],
  645. $InfoHash,
  646. $NumFiles,
  647. $FileString,
  648. $FilePath,
  649. $TotalSize,
  650. $T['TorrentDescription'],
  651. $T['MediaInfo'],
  652. $T['FreeTorrent'],
  653. $T['FreeLeechType']
  654. );
  655. $TorrentID = $DB->inserted_id();
  656. $Cache->increment('stats_torrent_count');
  657. $Tor->Dec['comment'] = 'https://'.SITE_DOMAIN.'/torrents.php?torrentid='.$TorrentID;
  658. Tracker::update_tracker('add_torrent', [
  659. 'id' => $TorrentID,
  660. 'info_hash' => rawurlencode($InfoHash),
  661. 'freetorrent' => $T['FreeTorrent']
  662. ]);
  663. $Debug->set_flag('upload: ocelot updated');
  664. // Prevent deletion of this torrent until the rest of the upload process is done
  665. // (expire the key after 10 minutes to prevent locking it for too long in case there's a fatal error below)
  666. $Cache->cache_value("torrent_{$TorrentID}_lock", true, 600);
  667. // Give BP if necessary
  668. // todo: Repurpose this
  669. if (($Type === "Movies" || $Type === "Anime") && ($T['Container'] === 'ISO' || $T['Container'] === 'M2TS' || $T['Container'] === 'VOB IFO')) {
  670. $BPAmt = (int) 2*($TotalSize / (1024*1024*1024))*1000;
  671. $DB->query("
  672. UPDATE users_main
  673. SET BonusPoints = BonusPoints + ?
  674. WHERE ID = ?", $BPAmt, $LoggedUser['ID']);
  675. $DB->query("
  676. UPDATE users_info
  677. SET AdminComment = CONCAT(NOW(), ' - Received $BPAmt ".BONUS_POINTS." for uploading a torrent $TorrentID\n\n', AdminComment)
  678. WHERE UserID = ?", $LoggedUser['ID']);
  679. $Cache->delete_value('user_info_heavy_'.$LoggedUser['ID']);
  680. $Cache->delete_value('user_stats_'.$LoggedUser['ID']);
  681. }
  682. // Add to shop freeleeches if necessary
  683. if ($T['FreeLeechType'] === 3) {
  684. // Figure out which duration to use
  685. $Expiry = 0;
  686. foreach ($FreeLeechTags as $Tag => $Exp) {
  687. if ($Tag === 'global' || in_array($Tag, $Tags)) {
  688. if (((int) $FreeLeechTags[$Tag]['First']) > $Expiry) {
  689. $Expiry = (int) $FreeLeechTags[$Tag]['First'];
  690. }
  691. }
  692. }
  693. if ($Expiry > 0) {
  694. $DB->query("
  695. INSERT INTO shop_freeleeches
  696. (TorrentID, ExpiryTime)
  697. VALUES
  698. (" . $TorrentID . ", FROM_UNIXTIME(" . $Expiry . "))
  699. ON DUPLICATE KEY UPDATE
  700. ExpiryTime = FROM_UNIXTIME(UNIX_TIMESTAMP(ExpiryTime) + ($Expiry - FROM_UNIXTIME(NOW())))");
  701. } else {
  702. Torrents::freeleech_torrents($TorrentID, 0, 0);
  703. }
  704. }
  705. //******************************************************************************//
  706. //--------------- Write torrent file -------------------------------------------//
  707. file_put_contents(TORRENT_STORE.$TorrentID.'.torrent', $Tor->encode());
  708. Misc::write_log("Torrent $TorrentID ($LogName) (".number_format($TotalSize / (1024 * 1024), 2).' MB) was uploaded by ' . $LoggedUser['Username']);
  709. Torrents::write_group_log($GroupID, $TorrentID, $LoggedUser['ID'], 'uploaded ('.number_format($TotalSize / (1024 * 1024), 2).' MB)', 0);
  710. Torrents::update_hash($GroupID);
  711. $Debug->set_flag('upload: sphinx updated');
  712. //******************************************************************************//
  713. //---------------------- Recent Uploads ----------------------------------------//
  714. if (trim($T['Image']) !== '') {
  715. $RecentUploads = $Cache->get_value("recent_uploads_$UserID");
  716. if (is_array($RecentUploads)) {
  717. do {
  718. foreach ($RecentUploads as $Item) {
  719. if ($Item['ID'] === $GroupID) {
  720. break 2;
  721. }
  722. }
  723. // Only reached if no matching GroupIDs in the cache already.
  724. if (count($RecentUploads) === 5) {
  725. array_pop($RecentUploads);
  726. }
  727. array_unshift($RecentUploads, array(
  728. 'ID' => $GroupID,
  729. 'Name' => trim($T['Title']),
  730. 'Artist' => Artists::display_artists($ArtistForm, false, true),
  731. 'WikiImage' => trim($T['Image'])));
  732. $Cache->cache_value("recent_uploads_$UserID", $RecentUploads, 0);
  733. } while (0);
  734. }
  735. }
  736. //******************************************************************************//
  737. //------------------------------- Post-processing ------------------------------//
  738. /* Because tracker updates and notifications can be slow, we're
  739. * redirecting the user to the destination page and flushing the buffers
  740. * to make it seem like the PHP process is working in the background.
  741. */
  742. if ($PublicTorrent) {
  743. View::show_header('Warning'); ?>
  744. <h1>Warning</h1>
  745. <p>
  746. <strong>Your torrent has been uploaded but you must re-download your torrent file from
  747. <a
  748. href="torrents.php?id=<?=$GroupID?>&torrentid=<?=$TorrentID?>">here</a>
  749. because the site modified it to make it private.</strong>
  750. </p>
  751. <?php
  752. View::show_footer();
  753. } elseif ($UnsourcedTorrent) {
  754. View::show_header('Warning'); ?>
  755. <h1>Warning</h1>
  756. <p>
  757. <strong>Your torrent has been uploaded but you must re-download your torrent file from
  758. <a
  759. href="torrents.php?id=<?=$GroupID?>&torrentid=<?=$TorrentID?>">here</a>
  760. because the site modified it to add a source flag.</strong>
  761. </p>
  762. <?php
  763. View::show_footer();
  764. } elseif ($RequestID) {
  765. header("Location: requests.php?action=takefill&requestid=$RequestID&torrentid=$TorrentID&auth=".$LoggedUser['AuthKey']);
  766. } else {
  767. header("Location: torrents.php?id=$GroupID&torrentid=$TorrentID");
  768. }
  769. if (function_exists('fastcgi_finish_request')) {
  770. fastcgi_finish_request();
  771. } else {
  772. ignore_user_abort(true);
  773. ob_flush();
  774. flush();
  775. ob_start(); // So we don't keep sending data to the client
  776. }
  777. //******************************************************************************//
  778. //--------------------------- IRC announce and feeds ---------------------------//
  779. $Announce = '';
  780. $Announce .= Artists::display_artists($ArtistForm, false);
  781. $Announce .= substr(trim(empty($T['Title']) ? (empty($T['TitleRJ']) ? $T['TitleJP'] : $T['TitleRJ']) : $T['Title']), 0, 100);
  782. $Announce .= ' ';
  783. if ($Type !== 'Other') {
  784. $Announce .= '['.Torrents::torrent_info($T, false, false, false).']';
  785. }
  786. $Title = '['.$T['CategoryName'].'] '.$Announce;
  787. $Announce = "$Title - ".site_url()."torrents.php?id=$GroupID / ".site_url()."torrents.php?action=download&id=$TorrentID";
  788. $Announce .= ' - '.trim($T['TagList']);
  789. // ENT_QUOTES is needed to decode single quotes/apostrophes
  790. send_irc('PRIVMSG '.BOT_ANNOUNCE_CHAN.' '.html_entity_decode($Announce, ENT_QUOTES));
  791. $Debug->set_flag('upload: announced on irc');
  792. // Manage notifications
  793. // For RSS
  794. $Item = $Feed->item($Title, Text::strip_bbcode($Body), 'torrents.php?action=download&amp;authkey=[[AUTHKEY]]&amp;torrent_pass=[[PASSKEY]]&amp;id='.$TorrentID, $Properties['Anonymous'] ? 'Anonymous' : $LoggedUser['Username'], 'torrents.php?id='.$GroupID, trim($T['TagList']));
  795. // Notifications
  796. $SQL = "
  797. SELECT unf.ID, unf.UserID, torrent_pass
  798. FROM users_notify_filters AS unf
  799. JOIN users_main AS um ON um.ID = unf.UserID
  800. WHERE um.Enabled = '1'";
  801. if (empty($ArtistsUnescaped)) {
  802. $ArtistsUnescaped = $ArtistForm;
  803. }
  804. if (!empty($ArtistsUnescaped)) {
  805. $ArtistNameList = [];
  806. $GuestArtistNameList = [];
  807. foreach ($ArtistsUnescaped as $Importance => $Artist) {
  808. $ArtistNameList[] = "Artists LIKE '%|".db_string(str_replace('\\', '\\\\', $Artist['name']), true)."|%'";
  809. }
  810. // Don't add notification if >2 main artists or if tracked artist isn't a main artist
  811. /*
  812. if (count($ArtistNameList) > 2 || $Artist['name'] === 'Various Artists') {
  813. $SQL .= " AND (ExcludeVA = '0' AND (";
  814. $SQL .= implode(' OR ', array_merge($ArtistNameList, $GuestArtistNameList));
  815. $SQL .= " OR Artists = '')) AND (";
  816. } else {
  817. */
  818. $SQL .= " AND (";
  819. if (!empty($GuestArtistNameList)) {
  820. $SQL .= "(ExcludeVA = '0' AND (";
  821. $SQL .= implode(' OR ', $GuestArtistNameList);
  822. $SQL .= ')) OR ';
  823. }
  824. if (count($ArtistNameList) > 0) {
  825. $SQL .= implode(' OR ', $ArtistNameList);
  826. $SQL .= " OR ";
  827. }
  828. $SQL .= "Artists = '') AND (";
  829. #}
  830. } else {
  831. $SQL .= "AND (Artists = '') AND (";
  832. }
  833. reset($Tags);
  834. $TagSQL = [];
  835. $NotTagSQL = [];
  836. foreach ($Tags as $Tag) {
  837. $TagSQL[] = " Tags LIKE '%|".db_string(trim($Tag))."|%' ";
  838. $NotTagSQL[] = " NotTags LIKE '%|".db_string(trim($Tag))."|%' ";
  839. }
  840. $TagSQL[] = "Tags = ''";
  841. $SQL .= implode(' OR ', $TagSQL);
  842. $SQL .= ") AND !(".implode(' OR ', $NotTagSQL).')';
  843. $SQL .= " AND (Categories LIKE '%|".db_string(trim($Type))."|%' OR Categories = '') ";
  844. if ($T['ReleaseType']) {
  845. $SQL .= " AND (ReleaseTypes LIKE '%|".db_string(trim($ReleaseTypes[$T['ReleaseType']]))."|%' OR ReleaseTypes = '') ";
  846. } else {
  847. $SQL .= " AND (ReleaseTypes = '') ";
  848. }
  849. /*
  850. Notify based on the following:
  851. 1. The torrent must match the formatbitrate filter on the notification
  852. 2. If they set NewGroupsOnly to 1, it must also be the first torrent in the group to match the formatbitrate filter on the notification
  853. */
  854. if ($T['Format']) {
  855. $SQL .= " AND (Formats LIKE '%|".db_string(trim($T['Format']))."|%' OR Formats = '') ";
  856. } else {
  857. $SQL .= " AND (Formats = '') ";
  858. }
  859. if ($_POST['bitrate']) {
  860. $SQL .= " AND (Encodings LIKE '%|".db_string(trim($_POST['bitrate']))."|%' OR Encodings = '') ";
  861. } else {
  862. $SQL .= " AND (Encodings = '') ";
  863. }
  864. if ($T['Media']) {
  865. $SQL .= " AND (Media LIKE '%|".db_string(trim($T['Media']))."|%' OR Media = '') ";
  866. } else {
  867. $SQL .= " AND (Media = '') ";
  868. }
  869. // Either they aren't using NewGroupsOnly
  870. $SQL .= "AND ((NewGroupsOnly = '0' ";
  871. // Or this is the first torrent in the group to match the formatbitrate filter
  872. $SQL .= ") OR ( NewGroupsOnly = '1' ";
  873. $SQL .= '))';
  874. if ($T['Year']) {
  875. $SQL .= " AND (('".db_string(trim($T['Year']))."' BETWEEN FromYear AND ToYear)
  876. OR (FromYear = 0 AND ToYear = 0)) ";
  877. } else {
  878. $SQL .= " AND (FromYear = 0 AND ToYear = 0) ";
  879. }
  880. $SQL .= " AND UserID !== '".$LoggedUser['ID']."' ";
  881. $DB->query("
  882. SELECT Paranoia
  883. FROM users_main
  884. WHERE ID = $LoggedUser[ID]");
  885. list($Paranoia) = $DB->next_record();
  886. $Paranoia = unserialize($Paranoia);
  887. if (!is_array($Paranoia)) {
  888. $Paranoia = [];
  889. }
  890. if (!in_array('notifications', $Paranoia)) {
  891. $SQL .= " AND (Users LIKE '%|".$LoggedUser['ID']."|%' OR Users = '') ";
  892. }
  893. $SQL .= " AND UserID !== '".$LoggedUser['ID']."' ";
  894. $DB->query($SQL);
  895. $Debug->set_flag('upload: notification query finished');
  896. if ($DB->has_results()) {
  897. $UserArray = $DB->to_array('UserID');
  898. $FilterArray = $DB->to_array('ID');
  899. $InsertSQL = '
  900. INSERT IGNORE INTO users_notify_torrents (UserID, GroupID, TorrentID, FilterID)
  901. VALUES ';
  902. $Rows = [];
  903. foreach ($UserArray as $User) {
  904. list($FilterID, $UserID, $Passkey) = $User;
  905. $Rows[] = "('$UserID', '$GroupID', '$TorrentID', '$FilterID')";
  906. $Feed->populate("torrents_notify_$Passkey", $Item);
  907. $Cache->delete_value("notifications_new_$UserID");
  908. }
  909. $InsertSQL .= implode(',', $Rows);
  910. $DB->query($InsertSQL);
  911. $Debug->set_flag('upload: notification inserts finished');
  912. foreach ($FilterArray as $Filter) {
  913. list($FilterID, $UserID, $Passkey) = $Filter;
  914. $Feed->populate("torrents_notify_{$FilterID}_$Passkey", $Item);
  915. }
  916. }
  917. // RSS for bookmarks
  918. $DB->query("
  919. SELECT u.ID, u.torrent_pass
  920. FROM users_main AS u
  921. JOIN bookmarks_torrents AS b ON b.UserID = u.ID
  922. WHERE b.GroupID = $GroupID");
  923. while (list($UserID, $Passkey) = $DB->next_record()) {
  924. $Feed->populate("torrents_bookmarks_t_$Passkey", $Item);
  925. }
  926. $Feed->populate('torrents_all', $Item);
  927. $Feed->populate('torrents_'.strtolower($Type), $Item);
  928. $Debug->set_flag('upload: notifications handled');
  929. // Clear cache
  930. $Cache->delete_value("torrents_details_$GroupID");
  931. $Cache->delete_value("contest_scores");
  932. // Allow deletion of this torrent now
  933. $Cache->delete_value("torrent_{$TorrentID}_lock");