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

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