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

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