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

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