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

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