BioTorrents.de’s version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

upload_handle.php 33KB

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