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

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