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

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