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

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