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

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