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 32KB

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