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

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