Oppaitime'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

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