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

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