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.

torrents.class.php 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. <?php
  2. #declare(strict_types=1);
  3. class Torrents
  4. {
  5. const FILELIST_DELIM = 0xF7; // Hex for &divide; Must be the same as phrase_boundary in sphinx.conf!
  6. const SNATCHED_UPDATE_INTERVAL = 3600; // How often we want to update users' snatch lists
  7. const SNATCHED_UPDATE_AFTERDL = 300; // How long after a torrent download we want to update a user's snatch lists
  8. /**
  9. * Function to get data and torrents for an array of GroupIDs. Order of keys doesn't matter
  10. *
  11. * @param array $GroupIDs
  12. * @param boolean $Return if false, nothing is returned. For priming cache.
  13. * @param boolean $GetArtists if true, each group will contain the result of
  14. * Artists::get_artists($GroupID), in result[$GroupID]['ExtendedArtists']
  15. * @param boolean $Torrents if true, each group contains a list of torrents, in result[$GroupID]['Torrents']
  16. *
  17. * @return array each row of the following format:
  18. * GroupID => (
  19. * ID
  20. * Name
  21. * Year
  22. * RecordLabel
  23. * CatalogueNumber
  24. * TagList
  25. * ReleaseType
  26. * VanityHouse
  27. * WikiImage
  28. * CategoryID
  29. * Torrents => {
  30. * ID => {
  31. * GroupID, Media, Format, Encoding, RemasterYear, Remastered,
  32. * RemasterTitle, RemasterRecordLabel, RemasterCatalogueNumber, Scene,
  33. * HasLog, HasCue, LogScore, FileCount, FreeTorrent, Size, Leechers,
  34. * Seeders, Snatched, Time, HasFile, PersonalFL, IsSnatched
  35. * }
  36. * }
  37. * Artists => {
  38. * {
  39. * id, name, aliasid // Only main artists
  40. * }
  41. * }
  42. * ExtendedArtists => {
  43. * [1-6] => { // See documentation on Artists::get_artists
  44. * id, name, aliasid
  45. * }
  46. * }
  47. * Flags => {
  48. * IsSnatched
  49. * }
  50. */
  51. public static function get_groups($GroupIDs, $Return = true, $GetArtists = true, $Torrents = true)
  52. {
  53. $Found = $NotFound = array_fill_keys($GroupIDs, false);
  54. $Key = $Torrents ? 'torrent_group_' : 'torrent_group_light_';
  55. foreach ($GroupIDs as $i => $GroupID) {
  56. if (!is_number($GroupID)) {
  57. unset($GroupIDs[$i], $Found[$GroupID], $NotFound[$GroupID]);
  58. continue;
  59. }
  60. $Data = G::$Cache->get_value($Key . $GroupID, true);
  61. if (!empty($Data) && is_array($Data) && $Data['ver'] === Cache::GROUP_VERSION) {
  62. unset($NotFound[$GroupID]);
  63. $Found[$GroupID] = $Data['d'];
  64. }
  65. }
  66. // Make sure there's something in $GroupIDs, otherwise the SQL will break
  67. if (count($GroupIDs) === 0) {
  68. return [];
  69. }
  70. /**
  71. * Changing any of these attributes returned will cause very large, very dramatic site-wide chaos.
  72. * Do not change what is returned or the order thereof without updating:
  73. * torrents, artists, collages, bookmarks, better, the front page,
  74. * and anywhere else the get_groups function is used.
  75. * Update self::array_group(), too.
  76. */
  77. if (count($NotFound) > 0) {
  78. $IDs = implode(',', array_keys($NotFound));
  79. $NotFound = [];
  80. $QueryID = G::$DB->get_query_id();
  81. G::$DB->query("
  82. SELECT
  83. `id`,
  84. `title`,
  85. `subject`,
  86. `object`,
  87. `published`,
  88. `identifier`,
  89. `workgroup`,
  90. `location`,
  91. `tag_list`,
  92. `picture`,
  93. `category_id`
  94. FROM
  95. `torrents_group`
  96. WHERE
  97. `id` IN($IDs)
  98. ");
  99. while ($Group = G::$DB->next_record(MYSQLI_ASSOC, true)) {
  100. $NotFound[$Group['id']] = $Group;
  101. $NotFound[$Group['id']]['Torrents'] = [];
  102. $NotFound[$Group['id']]['Artists'] = [];
  103. }
  104. G::$DB->set_query_id($QueryID);
  105. if ($Torrents) {
  106. $QueryID = G::$DB->get_query_id();
  107. G::$DB->query("
  108. SELECT
  109. `ID`,
  110. `GroupID`,
  111. `Media`,
  112. `Container`,
  113. `Codec`,
  114. `Resolution`,
  115. `Version`,
  116. `Censored`,
  117. `Archive`,
  118. `FileCount`,
  119. `FreeTorrent`,
  120. `Size`,
  121. `Leechers`,
  122. `Seeders`,
  123. `Snatched`,
  124. `Time`,
  125. f.`ExpiryTime`,
  126. `ID` AS `HasFile`,
  127. `FreeLeechType`,
  128. HEX(`info_hash`) AS `info_hash`
  129. FROM
  130. `torrents`
  131. LEFT JOIN `shop_freeleeches` AS f
  132. ON
  133. f.`TorrentID` = `ID`
  134. WHERE
  135. `GroupID` IN($IDs)
  136. ORDER BY
  137. `GroupID`,
  138. `Media`,
  139. `Container`,
  140. `Codec`,
  141. `ID`
  142. ");
  143. while ($Torrent = G::$DB->next_record(MYSQLI_ASSOC, true)) {
  144. $NotFound[$Torrent['GroupID']]['Torrents'][$Torrent['ID']] = $Torrent;
  145. }
  146. G::$DB->set_query_id($QueryID);
  147. }
  148. foreach ($NotFound as $GroupID => $GroupInfo) {
  149. G::$Cache->cache_value($Key . $GroupID, array('ver' => Cache::GROUP_VERSION, 'd' => $GroupInfo), 0);
  150. }
  151. $Found = $NotFound + $Found;
  152. }
  153. // Filter out orphans (elements that are === false)
  154. $Found = array_filter($Found);
  155. if ($GetArtists) {
  156. $Artists = Artists::get_artists($GroupIDs);
  157. } else {
  158. $Artists = [];
  159. }
  160. if ($Return) { // If we're interested in the data, and not just caching it
  161. foreach ($Artists as $GroupID => $Data) {
  162. if (!isset($Found[$GroupID])) {
  163. continue;
  164. }
  165. $Found[$GroupID]['Artists'] = $Data;
  166. }
  167. // Fetch all user specific torrent properties
  168. if ($Torrents) {
  169. foreach ($Found as &$Group) {
  170. $Group['Flags'] = array('IsSnatched' => false, 'IsSeeding' => false, 'IsLeeching' => false);
  171. if (!empty($Group['Torrents'])) {
  172. foreach ($Group['Torrents'] as &$Torrent) {
  173. self::torrent_properties($Torrent, $Group['Flags']);
  174. }
  175. }
  176. }
  177. }
  178. return $Found;
  179. }
  180. }
  181. /**
  182. * Returns a reconfigured array from a Torrent Group
  183. *
  184. * Use this with extract() instead of the volatile list($GroupID, ...)
  185. * Then use the variables $GroupID, $GroupName, etc
  186. *
  187. * @example extract(Torrents::array_group($SomeGroup));
  188. * @param array $Group torrent group
  189. * @return array Re-key'd array
  190. */
  191. public static function array_group(array &$Group)
  192. {
  193. return array(
  194. 'id' => $Group['id'],
  195. 'title' => $Group['title'],
  196. 'subject' => $Group['subject'],
  197. 'object' => $Group['object'],
  198. 'published' => $Group['published'],
  199. 'category_id' => $Group['category_id'],
  200. 'identifier' => $Group['identifier'],
  201. 'workgroup' => $Group['workgroup'],
  202. 'location' => $Group['location'],
  203. 'GroupFlags' => ($Group['Flags'] ?? ''),
  204. 'tag_list' => $Group['tag_list'],
  205. 'picture' => $Group['picture'],
  206. 'Torrents' => $Group['Torrents'],
  207. 'Artists' => $Group['Artists']
  208. );
  209. }
  210. /**
  211. * Supplements a torrent array with information that only concerns certain users and therefore cannot be cached
  212. *
  213. * @param array $Torrent torrent array preferably in the form used by Torrents::get_groups() or get_group_info()
  214. * @param int $TorrentID
  215. */
  216. public static function torrent_properties(&$Torrent, &$Flags)
  217. {
  218. # FL Token
  219. $Torrent['PersonalFL'] = empty($Torrent['FreeTorrent']) && self::has_token($Torrent['ID']);
  220. # Snatched
  221. if ($Torrent['IsSnatched'] = self::has_snatched($Torrent['ID'])) {
  222. $Flags['IsSnatched'] = true;
  223. } else {
  224. $Flags['IsSnatched'] = false;
  225. }
  226. # Seeding
  227. if ($Torrent['IsSeeding'] = self::is_seeding($Torrent['ID'])) {
  228. $Flags['IsSeeding'] = true;
  229. } else {
  230. $Flags['IsSeeding'] = false;
  231. }
  232. # Leeching
  233. if ($Torrent['IsLeeching'] = self::is_leeching($Torrent['ID'])) {
  234. $Flags['IsLeeching'] = true;
  235. } else {
  236. $Flags['IsLeeching'] = false;
  237. }
  238. }
  239. /*
  240. * Write to the group log.
  241. *
  242. * @param int $GroupID
  243. * @param int $TorrentID
  244. * @param int $UserID
  245. * @param string $Message
  246. * @param boolean $Hidden Currently does fuck all.
  247. *
  248. * todo: Fix that
  249. */
  250. public static function write_group_log($GroupID, $TorrentID, $UserID, $Message, $Hidden)
  251. {
  252. global $Time;
  253. $QueryID = G::$DB->get_query_id();
  254. G::$DB->query("
  255. INSERT INTO `group_log`(
  256. `GroupID`,
  257. `TorrentID`,
  258. `UserID`,
  259. `Info`,
  260. `Time`,
  261. `Hidden`
  262. )
  263. VALUES(
  264. '$GroupID',
  265. '$TorrentID',
  266. '$UserID',
  267. '$Message',
  268. NOW(),
  269. '$Hidden'
  270. )
  271. ");
  272. G::$DB->set_query_id($QueryID);
  273. }
  274. /**
  275. * Delete a torrent.
  276. *
  277. * @param int $ID The ID of the torrent to delete.
  278. * @param int $GroupID Set it if you have it handy, to save a query. Otherwise, it will be found.
  279. * @param string $OcelotReason The deletion reason for ocelot to report to users.
  280. */
  281. public static function delete_torrent($ID, $GroupID = 0, $OcelotReason = -1)
  282. {
  283. $QueryID = G::$DB->get_query_id();
  284. if (!$GroupID) {
  285. G::$DB->query("
  286. SELECT GroupID, UserID
  287. FROM torrents
  288. WHERE ID = '$ID'");
  289. list($GroupID, $UploaderID) = G::$DB->next_record();
  290. }
  291. if (empty($UserID)) {
  292. G::$DB->query("
  293. SELECT UserID
  294. FROM torrents
  295. WHERE ID = '$ID'");
  296. list($UserID) = G::$DB->next_record();
  297. }
  298. $RecentUploads = G::$Cache->get_value("recent_uploads_$UserID");
  299. if (is_array($RecentUploads)) {
  300. foreach ($RecentUploads as $Key => $Recent) {
  301. if ($Recent['ID'] == $GroupID) {
  302. G::$Cache->delete_value("recent_uploads_$UserID");
  303. }
  304. }
  305. }
  306. G::$DB->query("
  307. SELECT info_hash
  308. FROM torrents
  309. WHERE ID = $ID");
  310. list($InfoHash) = G::$DB->next_record(MYSQLI_BOTH, false);
  311. G::$DB->query("
  312. DELETE FROM torrents
  313. WHERE ID = $ID");
  314. Tracker::update_tracker('delete_torrent', array('info_hash' => rawurlencode($InfoHash), 'id' => $ID, 'reason' => $OcelotReason));
  315. G::$Cache->decrement('stats_torrent_count');
  316. G::$DB->query("
  317. SELECT COUNT(ID)
  318. FROM torrents
  319. WHERE GroupID = '$GroupID'");
  320. list($Count) = G::$DB->next_record();
  321. if ($Count == 0) {
  322. Torrents::delete_group($GroupID);
  323. } else {
  324. Torrents::update_hash($GroupID);
  325. }
  326. // Torrent notifications
  327. G::$DB->query("
  328. SELECT UserID
  329. FROM users_notify_torrents
  330. WHERE TorrentID = '$ID'");
  331. while (list($UserID) = G::$DB->next_record()) {
  332. G::$Cache->delete_value("notifications_new_$UserID");
  333. }
  334. G::$DB->query("
  335. DELETE FROM users_notify_torrents
  336. WHERE TorrentID = '$ID'");
  337. G::$DB->query("
  338. UPDATE reportsv2
  339. SET
  340. Status = 'Resolved',
  341. LastChangeTime = NOW(),
  342. ModComment = 'Report already dealt with (torrent deleted)'
  343. WHERE TorrentID = ?
  344. AND Status != 'Resolved'", $ID);
  345. $Reports = G::$DB->affected_rows();
  346. if ($Reports) {
  347. G::$Cache->decrement('num_torrent_reportsv2', $Reports);
  348. }
  349. unlink(TORRENT_STORE.$ID.'.torrent');
  350. G::$DB->query("
  351. DELETE FROM torrents_bad_tags
  352. WHERE TorrentID = ?", $ID);
  353. G::$DB->query("
  354. DELETE FROM torrents_bad_folders
  355. WHERE TorrentID = ?", $ID);
  356. G::$DB->query("
  357. DELETE FROM torrents_bad_files
  358. WHERE TorrentID = ?", $ID);
  359. G::$DB->query("
  360. DELETE FROM shop_freeleeches
  361. WHERE TorrentID = ?", $ID);
  362. $FLs = G::$DB->affected_rows();
  363. if ($FLs) {
  364. G::$Cache->delete_value('shop_freeleech_list');
  365. }
  366. // Tells Sphinx that the group is removed
  367. G::$DB->query("
  368. REPLACE INTO sphinx_delta (ID, Time)
  369. VALUES (?, UNIX_TIMESTAMP())", $ID);
  370. G::$Cache->delete_value("torrent_download_$ID");
  371. G::$Cache->delete_value("torrent_group_$GroupID");
  372. G::$Cache->delete_value("torrents_details_$GroupID");
  373. G::$DB->set_query_id($QueryID);
  374. }
  375. /**
  376. * Delete a group, called after all of its torrents have been deleted.
  377. * IMPORTANT: Never call this unless you're certain the group is no longer used by any torrents
  378. *
  379. * @param int $GroupID
  380. */
  381. public static function delete_group($GroupID)
  382. {
  383. $QueryID = G::$DB->get_query_id();
  384. Misc::write_log("Group $GroupID automatically deleted (No torrents have this group).");
  385. G::$DB->query("
  386. SELECT
  387. `category_id`
  388. FROM
  389. `torrents_group`
  390. WHERE
  391. `id` = '$GroupID'
  392. ");
  393. list($Category) = G::$DB->next_record();
  394. if ($Category == 1) {
  395. G::$Cache->decrement('stats_album_count');
  396. }
  397. G::$Cache->decrement('stats_group_count');
  398. // Collages
  399. G::$DB->query("
  400. SELECT CollageID
  401. FROM collages_torrents
  402. WHERE GroupID = ?", $GroupID);
  403. if (G::$DB->has_results()) {
  404. $CollageIDs = G::$DB->collect('CollageID');
  405. G::$DB->query("
  406. UPDATE collages
  407. SET NumTorrents = NumTorrents - 1
  408. WHERE ID IN (".implode(', ', $CollageIDs).')');
  409. G::$DB->query("
  410. DELETE FROM collages_torrents
  411. WHERE GroupID = ?", $GroupID);
  412. foreach ($CollageIDs as $CollageID) {
  413. G::$Cache->delete_value("collage_$CollageID");
  414. }
  415. G::$Cache->delete_value("torrent_collages_$GroupID");
  416. }
  417. // Artists
  418. // Collect the artist IDs and then wipe the torrents_artist entry
  419. G::$DB->query("
  420. SELECT ArtistID
  421. FROM torrents_artists
  422. WHERE GroupID = ?", $GroupID);
  423. $Artists = G::$DB->collect('ArtistID');
  424. G::$DB->query("
  425. DELETE FROM torrents_artists
  426. WHERE GroupID = ?", $GroupID);
  427. foreach ($Artists as $ArtistID) {
  428. if (empty($ArtistID)) {
  429. continue;
  430. }
  431. // Get a count of how many groups or requests use the artist ID
  432. G::$DB->query("
  433. SELECT COUNT(ag.ArtistID)
  434. FROM artists_group AS ag
  435. LEFT JOIN requests_artists AS ra ON ag.ArtistID = ra.ArtistID
  436. WHERE ra.ArtistID IS NOT NULL
  437. AND ag.ArtistID = ?", $ArtistID);
  438. list($ReqCount) = G::$DB->next_record();
  439. G::$DB->query("
  440. SELECT COUNT(ag.ArtistID)
  441. FROM artists_group AS ag
  442. LEFT JOIN torrents_artists AS ta ON ag.ArtistID = ta.ArtistID
  443. WHERE ta.ArtistID IS NOT NULL
  444. AND ag.ArtistID = ?", $ArtistID);
  445. list($GroupCount) = G::$DB->next_record();
  446. if (($ReqCount + $GroupCount) == 0) {
  447. //The only group to use this artist
  448. Artists::delete_artist($ArtistID);
  449. } else {
  450. //Not the only group, still need to clear cache
  451. G::$Cache->delete_value("artist_groups_$ArtistID");
  452. }
  453. }
  454. // Requests
  455. G::$DB->query("
  456. SELECT ID
  457. FROM requests
  458. WHERE GroupID = ?", $GroupID);
  459. $Requests = G::$DB->collect('ID');
  460. G::$DB->query("
  461. UPDATE requests
  462. SET GroupID = NULL
  463. WHERE GroupID = ?", $GroupID);
  464. foreach ($Requests as $RequestID) {
  465. G::$Cache->delete_value("request_$RequestID");
  466. }
  467. // Comments
  468. Comments::delete_page('torrents', $GroupID);
  469. G::$DB->query("
  470. DELETE
  471. FROM
  472. `torrents_group`
  473. WHERE
  474. `id` = '$GroupID'
  475. ");
  476. G::$DB->query("
  477. DELETE FROM torrents_tags
  478. WHERE GroupID = ?", $GroupID);
  479. G::$DB->query("
  480. DELETE FROM bookmarks_torrents
  481. WHERE GroupID = ?", $GroupID);
  482. G::$DB->query("
  483. DELETE FROM wiki_torrents
  484. WHERE PageID = ?", $GroupID);
  485. G::$Cache->delete_value("torrents_details_$GroupID");
  486. G::$Cache->delete_value("torrent_group_$GroupID");
  487. G::$Cache->delete_value("groups_artists_$GroupID");
  488. G::$DB->set_query_id($QueryID);
  489. }
  490. /**
  491. * Update the cache and sphinx delta index to keep everything up-to-date.
  492. *
  493. * @param int $GroupID
  494. */
  495. public static function update_hash($GroupID)
  496. {
  497. $QueryID = G::$DB->get_query_id();
  498. G::$DB->query("
  499. UPDATE
  500. `torrents_group`
  501. SET
  502. `tag_list` =(
  503. SELECT
  504. REPLACE
  505. (
  506. GROUP_CONCAT(tags.Name SEPARATOR ' '),
  507. '.',
  508. '_'
  509. )
  510. FROM
  511. `torrents_tags` AS t
  512. INNER JOIN `tags` ON tags.`ID` = t.`TagID`
  513. WHERE
  514. t.`GroupID` = '$GroupID'
  515. GROUP BY
  516. t.`GroupID`
  517. )
  518. WHERE
  519. `ID` = '$GroupID'
  520. ");
  521. // Fetch album artists
  522. G::$DB->query("
  523. SELECT GROUP_CONCAT(ag.Name separator ' ')
  524. FROM torrents_artists AS ta
  525. JOIN artists_group AS ag ON ag.ArtistID = ta.ArtistID
  526. WHERE ta.GroupID = ?
  527. GROUP BY ta.GroupID", $GroupID);
  528. if (G::$DB->has_results()) {
  529. list($ArtistName) = G::$DB->next_record(MYSQLI_NUM, false);
  530. } else {
  531. $ArtistName = '';
  532. }
  533. G::$DB->query("
  534. REPLACE
  535. INTO sphinx_delta(
  536. `ID`,
  537. `GroupID`,
  538. `GroupName`,
  539. `GroupTitle2`,
  540. `GroupNameJP`,
  541. `TagList`,
  542. `Year`,
  543. `CatalogueNumber`,
  544. `CategoryID`,
  545. `Time`,
  546. `Size`,
  547. `Snatched`,
  548. `Seeders`,
  549. `Leechers`,
  550. `Censored`,
  551. `Studio`,
  552. `Series`,
  553. `FreeTorrent`,
  554. `Media`,
  555. `Container`,
  556. `Codec`,
  557. `Resolution`,
  558. `Version`,
  559. `Description`,
  560. `FileList`,
  561. `ArtistName`
  562. )
  563. SELECT
  564. t.`ID`,
  565. g.`id`,
  566. `Name`,
  567. `Title2`,
  568. `NameJP`,
  569. `TagList`,
  570. `Year`,
  571. `CatalogueNumber`,
  572. `CategoryID`,
  573. UNIX_TIMESTAMP(t.`Time`),
  574. `Size`,
  575. `Snatched`,
  576. `Seeders`,
  577. `Leechers`,
  578. `Censored`,
  579. `Studio`,
  580. `Series`,
  581. CAST(`FreeTorrent` AS CHAR),
  582. `Media`,
  583. `Container`,
  584. `Codec`,
  585. `Resolution`,
  586. `Version`,
  587. `Description`,
  588. REPLACE
  589. (
  590. REPLACE
  591. (`FileList`, '_', ' '),
  592. '/',
  593. ' '
  594. ) AS FileList,
  595. '$ArtistName'
  596. FROM
  597. `torrents` AS t
  598. JOIN `torrents_group` AS g
  599. ON
  600. g.`id` = t.`GroupID`
  601. WHERE
  602. g.`id` = '$GroupID'
  603. ");
  604. G::$Cache->delete_value("torrents_details_$GroupID");
  605. G::$Cache->delete_value("torrent_group_$GroupID");
  606. G::$Cache->delete_value("torrent_group_light_$GroupID");
  607. $ArtistInfo = Artists::get_artist($GroupID);
  608. G::$Cache->delete_value("groups_artists_$GroupID");
  609. G::$DB->set_query_id($QueryID);
  610. }
  611. /**
  612. * Regenerate a torrent's file list from its meta data,
  613. * update the database record and clear relevant cache keys
  614. *
  615. * @param int $TorrentID
  616. */
  617. public static function regenerate_filelist($TorrentID)
  618. {
  619. $QueryID = G::$DB->get_query_id();
  620. G::$DB->query("
  621. SELECT GroupID
  622. FROM torrents
  623. WHERE ID = ?", $TorrentID);
  624. if (G::$DB->has_results()) {
  625. list($GroupID) = G::$DB->next_record(MYSQLI_NUM, false);
  626. $Contents = file_get_contents(TORRENT_STORE.$TorrentID.'.torrent');
  627. if (Misc::is_new_torrent($Contents)) {
  628. $Tor = new BencodeTorrent($Contents);
  629. $FilePath = (isset($Tor->Dec['info']['files']) ? Format::make_utf8($Tor->get_name()) : '');
  630. } else {
  631. $Tor = new TORRENT(unserialize(base64_decode($Contents)), true);
  632. $FilePath = (isset($Tor->Val['info']->Val['files']) ? Format::make_utf8($Tor->get_name()) : '');
  633. }
  634. list($TotalSize, $FileList) = $Tor->file_list();
  635. foreach ($FileList as $File) {
  636. $TmpFileList[] = self::filelist_format_file($File);
  637. }
  638. $FileString = implode("\n", $TmpFileList);
  639. G::$DB->query(
  640. "
  641. UPDATE torrents
  642. SET Size = ?, FilePath = ?, FileList = ?
  643. WHERE ID = ?",
  644. $TotalSize,
  645. $FilePath,
  646. $FileString,
  647. $TorrentID
  648. );
  649. G::$Cache->delete_value("torrents_details_$GroupID");
  650. }
  651. G::$DB->set_query_id($QueryID);
  652. }
  653. /**
  654. * Return UTF-8 encoded string to use as file delimiter in torrent file lists
  655. */
  656. public static function filelist_delim()
  657. {
  658. static $FilelistDelimUTF8;
  659. if (isset($FilelistDelimUTF8)) {
  660. return $FilelistDelimUTF8;
  661. }
  662. return $FilelistDelimUTF8 = utf8_encode(chr(self::FILELIST_DELIM));
  663. }
  664. /**
  665. * Create a string that contains file info in a format that's easy to use for Sphinx
  666. *
  667. * @param array $File (File size, File name)
  668. * @return string with the format .EXT sSIZEs NAME DELIMITER
  669. */
  670. public static function filelist_format_file($File)
  671. {
  672. list($Size, $Name) = $File;
  673. $Name = Format::make_utf8(strtr($Name, "\n\r\t", ' '));
  674. $ExtPos = strrpos($Name, '.');
  675. // Should not be $ExtPos !== false. Extensionless files that start with a . should not get extensions
  676. $Ext = ($ExtPos ? trim(substr($Name, $ExtPos + 1)) : '');
  677. return sprintf("%s s%ds %s %s", ".$Ext", $Size, $Name, self::filelist_delim());
  678. }
  679. /**
  680. * Create a string that contains file info in the old format for the API
  681. *
  682. * @param string $File string with the format .EXT sSIZEs NAME DELIMITER
  683. * @return string with the format NAME{{{SIZE}}}
  684. */
  685. public static function filelist_old_format($File)
  686. {
  687. $File = self::filelist_get_file($File);
  688. return $File['name'] . '{{{' . $File['size'] . '}}}';
  689. }
  690. /**
  691. * Translate a formatted file info string into a more useful array structure
  692. *
  693. * @param string $File string with the format .EXT sSIZEs NAME DELIMITER
  694. * @return file info array with the keys 'ext', 'size' and 'name'
  695. */
  696. public static function filelist_get_file($File)
  697. {
  698. // Need this hack because filelists are always display_str()ed
  699. $DelimLen = strlen(display_str(self::filelist_delim())) + 1;
  700. list($FileExt, $Size, $Name) = explode(' ', $File, 3);
  701. if ($Spaces = strspn($Name, ' ')) {
  702. $Name = str_replace(' ', '&nbsp;', substr($Name, 0, $Spaces)) . substr($Name, $Spaces);
  703. }
  704. return array(
  705. 'ext' => $FileExt,
  706. 'size' => substr($Size, 1, -1),
  707. 'name' => substr($Name, 0, -$DelimLen)
  708. );
  709. }
  710. /**
  711. * Format the information about a torrent.
  712. * @param $Data an array a subset of the following keys:
  713. * Format, Encoding, HasLog, LogScore HasCue, Media, Scene, RemasterYear
  714. * RemasterTitle, FreeTorrent, PersonalFL
  715. * @param boolean $ShowMedia if false, Media key will be omitted
  716. * @param boolean $ShowEdition if false, RemasterYear/RemasterTitle will be omitted
  717. */
  718. public static function torrent_info($Data, $ShowMedia = true, $ShowEdition = false, $HTMLy = true)
  719. {
  720. # Main torrent search results info!
  721. $Info = [];
  722. # Platform
  723. if ($ShowMedia && !empty($Data['Media'])) {
  724. $Info[] = ($HTMLy)
  725. ? '<a class="search_link" href="torrents.php?action=advanced&media='
  726. . display_str($Data['Media'])
  727. . '">'
  728. . display_str($Data['Media'])
  729. . '</a>'
  730. : display_str($Data['Media']);
  731. }
  732. # Format
  733. if (!empty($Data['Container'])) {
  734. $Info[] = ($HTMLy)
  735. ? '<a class="search_link" href="torrents.php?action=advanced&container='
  736. . display_str($Data['Container'])
  737. . '">'
  738. . display_str($Data['Container'])
  739. . '</a>'
  740. : display_str($Data['Container']);
  741. }
  742. # Archive
  743. if (!empty($Data['Archive'])) {
  744. # todo: Search on archives, lowest priority
  745. $Info[] = display_str($Data['Archive']);
  746. }
  747. # Resolution
  748. if (!empty($Data['Resolution'])) {
  749. $Info[] = ($HTMLy)
  750. ? '<a class="search_link" href="torrents.php?action=advanced&resolution='
  751. . display_str($Data['Resolution'])
  752. . '">'
  753. . display_str($Data['Resolution'])
  754. . '</a>'
  755. : display_str($Data['Resolution']);
  756. }
  757. # License
  758. if (!empty($Data['Codec'])) {
  759. $Info[] = ($HTMLy)
  760. ? '<a class="search_link" href="torrents.php?action=advanced&codec='
  761. . display_str($Data['Codec'])
  762. . '">'
  763. . display_str($Data['Codec'])
  764. . '</a>'
  765. : display_str($Data['Codec']);
  766. }
  767. # Alignned/Annotated
  768. if ($Data['Censored'] === 1) {
  769. $Info[] = ($HTMLy)
  770. ? '<a class="search_link" href="torrents.php?action=advanced&censored=1">Aligned</a>'
  771. : 'Aligned';
  772. } else {
  773. $Info[] = ($HTMLy)
  774. ? '<a class="search_link" href="torrents.php?action=advanced&censored=0">Not Aligned</a>'
  775. : 'Not Aligned';
  776. }
  777. /*
  778. if (!empty($Data['Version'])) {
  779. $Info[] = $Data['Version'];
  780. }
  781. */
  782. if ($Data['IsLeeching']) {
  783. $Info[] = $HTMLy ? Format::torrent_label('Leeching', 'important_text_semi') : 'Leeching';
  784. } elseif ($Data['IsSeeding']) {
  785. $Info[] = $HTMLy ? Format::torrent_label('Seeding', 'important_text_alt') : 'Seeding';
  786. } elseif ($Data['IsSnatched']) {
  787. $Info[] = $HTMLy ? Format::torrent_label('Snatched', 'bold') : 'Snatched';
  788. }
  789. if ($Data['FreeTorrent'] === '1') {
  790. if ($Data['FreeLeechType'] === '3') {
  791. if ($Data['ExpiryTime']) {
  792. $Info[] = ($HTMLy ? Format::torrent_label('Freeleech', 'important_text_alt') : 'Freeleech') . ($HTMLy ? " <strong>(" : " (").str_replace(['month','week','day','hour','min','s'], ['m','w','d','h','m',''], time_diff(max(strtotime($Data['ExpiryTime']), time()), 1, false)).($HTMLy ? ")</strong>" : ")");
  793. } else {
  794. $Info[] = $HTMLy ? Format::torrent_label('Freeleech', 'important_text_alt') : 'Freeleech';
  795. }
  796. } else {
  797. $Info[] = $HTMLy ? Format::torrent_label('Freeleech', 'important_text_alt') : 'Freeleech';
  798. }
  799. }
  800. if ($Data['FreeTorrent'] == '2') {
  801. $Info[] = $HTMLy ? Format::torrent_label('Neutral Leech', 'bold') : 'Neutral Leech';
  802. }
  803. if ($Data['PersonalFL']) {
  804. $Info[] = $HTMLy ? Format::torrent_label('Personal Freeleech', 'important_text_alt') : 'Personal Freeleech';
  805. }
  806. return implode(' | ', $Info);
  807. }
  808. /**
  809. * Will freeleech / neutral leech / normalise a set of torrents
  810. *
  811. * @param array $TorrentIDs An array of torrent IDs to iterate over
  812. * @param int $FreeNeutral 0 = normal, 1 = fl, 2 = nl
  813. * @param int $FreeLeechType 0 = Unknown, 1 = Staff picks, 2 = Perma-FL (Toolbox, etc.), 3 = Vanity House
  814. */
  815. public static function freeleech_torrents($TorrentIDs, $FreeNeutral = 1, $FreeLeechType = 0, $Announce = true)
  816. {
  817. if (!is_array($TorrentIDs)) {
  818. $TorrentIDs = array($TorrentIDs);
  819. }
  820. $QueryID = G::$DB->get_query_id();
  821. G::$DB->query("
  822. UPDATE torrents
  823. SET FreeTorrent = '$FreeNeutral', FreeLeechType = '$FreeLeechType'
  824. WHERE ID IN (".implode(', ', $TorrentIDs).')');
  825. G::$DB->query('
  826. SELECT ID, GroupID, info_hash
  827. FROM torrents
  828. WHERE ID IN ('.implode(', ', $TorrentIDs).')
  829. ORDER BY GroupID ASC');
  830. $Torrents = G::$DB->to_array(false, MYSQLI_NUM, false);
  831. $GroupIDs = G::$DB->collect('GroupID');
  832. G::$DB->set_query_id($QueryID);
  833. foreach ($Torrents as $Torrent) {
  834. list($TorrentID, $GroupID, $InfoHash) = $Torrent;
  835. Tracker::update_tracker('update_torrent', array('info_hash' => rawurlencode($InfoHash), 'freetorrent' => $FreeNeutral));
  836. G::$Cache->delete_value("torrent_download_$TorrentID");
  837. Misc::write_log((G::$LoggedUser['Username']??'System')." marked torrent $TorrentID freeleech type $FreeLeechType");
  838. Torrents::write_group_log($GroupID, $TorrentID, (G::$LoggedUser['ID']??0), "marked as freeleech type $FreeLeechType", 0);
  839. if ($Announce && ($FreeLeechType === 1 || $FreeLeechType === 3)) {
  840. send_irc(ANNOUNCE_CHAN, 'FREELEECH - '.site_url()."torrents.php?id=$GroupID / ".site_url()."torrents.php?action=download&id=$TorrentID");
  841. }
  842. }
  843. foreach ($GroupIDs as $GroupID) {
  844. Torrents::update_hash($GroupID);
  845. }
  846. }
  847. /**
  848. * Convenience function to allow for passing groups to Torrents::freeleech_torrents()
  849. *
  850. * @param array $GroupIDs the groups in question
  851. * @param int $FreeNeutral see Torrents::freeleech_torrents()
  852. * @param int $FreeLeechType see Torrents::freeleech_torrents()
  853. */
  854. public static function freeleech_groups($GroupIDs, $FreeNeutral = 1, $FreeLeechType = 0)
  855. {
  856. $QueryID = G::$DB->get_query_id();
  857. if (!is_array($GroupIDs)) {
  858. $GroupIDs = [$GroupIDs];
  859. }
  860. G::$DB->query('
  861. SELECT ID
  862. FROM torrents
  863. WHERE GroupID IN ('.implode(', ', $GroupIDs).')');
  864. if (G::$DB->has_results()) {
  865. $TorrentIDs = G::$DB->collect('ID');
  866. Torrents::freeleech_torrents($TorrentIDs, $FreeNeutral, $FreeLeechType);
  867. }
  868. G::$DB->set_query_id($QueryID);
  869. }
  870. /**
  871. * Check if the logged in user has an active freeleech token
  872. *
  873. * @param int $TorrentID
  874. * @return true if an active token exists
  875. */
  876. public static function has_token($TorrentID)
  877. {
  878. if (empty(G::$LoggedUser)) {
  879. return false;
  880. }
  881. static $TokenTorrents;
  882. $UserID = G::$LoggedUser['ID'];
  883. if (!isset($TokenTorrents)) {
  884. $TokenTorrents = G::$Cache->get_value("users_tokens_$UserID");
  885. if ($TokenTorrents === false) {
  886. $QueryID = G::$DB->get_query_id();
  887. G::$DB->query("
  888. SELECT TorrentID
  889. FROM users_freeleeches
  890. WHERE UserID = ?
  891. AND Expired = 0", $UserID);
  892. $TokenTorrents = array_fill_keys(G::$DB->collect('TorrentID', false), true);
  893. G::$DB->set_query_id($QueryID);
  894. G::$Cache->cache_value("users_tokens_$UserID", $TokenTorrents);
  895. }
  896. }
  897. return isset($TokenTorrents[$TorrentID]);
  898. }
  899. /**
  900. * Check if the logged in user can use a freeleech token on this torrent
  901. *
  902. * @param int $Torrent
  903. * @return boolen True if user is allowed to use a token
  904. */
  905. public static function can_use_token($Torrent)
  906. {
  907. if (empty(G::$LoggedUser)) {
  908. return false;
  909. }
  910. return (G::$LoggedUser['FLTokens'] > 0
  911. && $Torrent['Size'] <= 10737418240
  912. && !$Torrent['PersonalFL']
  913. && empty($Torrent['FreeTorrent'])
  914. && G::$LoggedUser['CanLeech'] == '1');
  915. }
  916. /**
  917. * Build snatchlists and check if a torrent has been snatched
  918. * if a user has the 'ShowSnatched' option enabled
  919. * @param int $TorrentID
  920. * @return bool
  921. */
  922. public static function has_snatched($TorrentID)
  923. {
  924. if (empty(G::$LoggedUser) || !isset(G::$LoggedUser['ShowSnatched']) || !G::$LoggedUser['ShowSnatched']) {
  925. return false;
  926. }
  927. $UserID = G::$LoggedUser['ID'];
  928. $Buckets = 64;
  929. $LastBucket = $Buckets - 1;
  930. $BucketID = $TorrentID & $LastBucket;
  931. static $SnatchedTorrents = [], $UpdateTime = [];
  932. if (empty($SnatchedTorrents)) {
  933. $SnatchedTorrents = array_fill(0, $Buckets, false);
  934. $UpdateTime = G::$Cache->get_value("users_snatched_{$UserID}_time");
  935. if ($UpdateTime === false) {
  936. $UpdateTime = array(
  937. 'last' => 0,
  938. 'next' => 0);
  939. }
  940. } elseif (isset($SnatchedTorrents[$BucketID][$TorrentID])) {
  941. return true;
  942. }
  943. // Torrent was not found in the previously inspected snatch lists
  944. $CurSnatchedTorrents =& $SnatchedTorrents[$BucketID];
  945. if ($CurSnatchedTorrents === false) {
  946. $CurTime = time();
  947. // This bucket hasn't been checked before
  948. $CurSnatchedTorrents = G::$Cache->get_value("users_snatched_{$UserID}_$BucketID", true);
  949. if ($CurSnatchedTorrents === false || $CurTime > $UpdateTime['next']) {
  950. $Updated = [];
  951. $QueryID = G::$DB->get_query_id();
  952. if ($CurSnatchedTorrents === false || $UpdateTime['last'] == 0) {
  953. for ($i = 0; $i < $Buckets; $i++) {
  954. $SnatchedTorrents[$i] = [];
  955. }
  956. // Not found in cache. Since we don't have a suitable index, it's faster to update everything
  957. G::$DB->query("
  958. SELECT fid
  959. FROM xbt_snatched
  960. WHERE uid = ?", $UserID);
  961. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  962. $SnatchedTorrents[$ID & $LastBucket][(int)$ID] = true;
  963. }
  964. $Updated = array_fill(0, $Buckets, true);
  965. } elseif (isset($CurSnatchedTorrents[$TorrentID])) {
  966. // Old cache, but torrent is snatched, so no need to update
  967. return true;
  968. } else {
  969. // Old cache, check if torrent has been snatched recently
  970. G::$DB->query("
  971. SELECT fid
  972. FROM xbt_snatched
  973. WHERE uid = ?
  974. AND tstamp >= ?", $UserID, $UpdateTime['last']);
  975. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  976. $CurBucketID = $ID & $LastBucket;
  977. if ($SnatchedTorrents[$CurBucketID] === false) {
  978. $SnatchedTorrents[$CurBucketID] = G::$Cache->get_value("users_snatched_{$UserID}_$CurBucketID", true);
  979. if ($SnatchedTorrents[$CurBucketID] === false) {
  980. $SnatchedTorrents[$CurBucketID] = [];
  981. }
  982. }
  983. $SnatchedTorrents[$CurBucketID][(int)$ID] = true;
  984. $Updated[$CurBucketID] = true;
  985. }
  986. }
  987. G::$DB->set_query_id($QueryID);
  988. for ($i = 0; $i < $Buckets; $i++) {
  989. if (isset($Updated[$i])) {
  990. G::$Cache->cache_value("users_snatched_{$UserID}_$i", $SnatchedTorrents[$i], 0);
  991. }
  992. }
  993. $UpdateTime['last'] = $CurTime;
  994. $UpdateTime['next'] = $CurTime + self::SNATCHED_UPDATE_INTERVAL;
  995. G::$Cache->cache_value("users_snatched_{$UserID}_time", $UpdateTime, 0);
  996. }
  997. }
  998. return isset($CurSnatchedTorrents[$TorrentID]);
  999. }
  1000. public static function is_seeding($TorrentID)
  1001. {
  1002. if (empty(G::$LoggedUser) || !isset(G::$LoggedUser['ShowSnatched']) || !G::$LoggedUser['ShowSnatched']) {
  1003. return false;
  1004. }
  1005. $UserID = G::$LoggedUser['ID'];
  1006. $Buckets = 64;
  1007. $LastBucket = $Buckets - 1;
  1008. $BucketID = $TorrentID & $LastBucket;
  1009. static $SeedingTorrents = [], $UpdateTime = [];
  1010. if (empty($SeedingTorrents)) {
  1011. $SeedingTorrents = array_fill(0, $Buckets, false);
  1012. $UpdateTime = G::$Cache->get_value("users_seeding_{$UserID}_time");
  1013. if ($UpdateTime === false) {
  1014. $UpdateTime = array(
  1015. 'last' => 0,
  1016. 'next' => 0);
  1017. }
  1018. } elseif (isset($SeedingTorrents[$BucketID][$TorrentID])) {
  1019. return true;
  1020. }
  1021. // Torrent was not found in the previously inspected seeding lists
  1022. $CurSeedingTorrents =& $SeedingTorrents[$BucketID];
  1023. if ($CurSeedingTorrents === false) {
  1024. $CurTime = time();
  1025. // This bucket hasn't been checked before
  1026. $CurSeedingTorrents = G::$Cache->get_value("users_seeding_{$UserID}_$BucketID", true);
  1027. if ($CurSeedingTorrents === false || $CurTime > $UpdateTime['next']) {
  1028. $Updated = [];
  1029. $QueryID = G::$DB->get_query_id();
  1030. if ($CurSeedingTorrents === false || $UpdateTime['last'] == 0) {
  1031. for ($i = 0; $i < $Buckets; $i++) {
  1032. $SeedingTorrents[$i] = [];
  1033. }
  1034. // Not found in cache. Since we don't have a suitable index, it's faster to update everything
  1035. G::$DB->query("
  1036. SELECT fid
  1037. FROM xbt_files_users
  1038. WHERE uid = ?
  1039. AND active = 1
  1040. AND Remaining = 0", $UserID);
  1041. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  1042. $SeedingTorrents[$ID & $LastBucket][(int)$ID] = true;
  1043. }
  1044. $Updated = array_fill(0, $Buckets, true);
  1045. } elseif (isset($CurSeedingTorrents[$TorrentID])) {
  1046. // Old cache, but torrent is seeding, so no need to update
  1047. return true;
  1048. } else {
  1049. // Old cache, check if torrent has been seeding recently
  1050. G::$DB->query("
  1051. SELECT fid
  1052. FROM xbt_files_users
  1053. WHERE uid = ?
  1054. AND active = 1
  1055. AND Remaining = 0
  1056. AND mtime >= ?", $UserID, $UpdateTime['last']);
  1057. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  1058. $CurBucketID = $ID & $LastBucket;
  1059. if ($SeedingTorrents[$CurBucketID] === false) {
  1060. $SeedingTorrents[$CurBucketID] = G::$Cache->get_value("users_seeding_{$UserID}_$CurBucketID", true);
  1061. if ($SeedingTorrents[$CurBucketID] === false) {
  1062. $SeedingTorrents[$CurBucketID] = [];
  1063. }
  1064. }
  1065. $SeedingTorrents[$CurBucketID][(int)$ID] = true;
  1066. $Updated[$CurBucketID] = true;
  1067. }
  1068. }
  1069. G::$DB->set_query_id($QueryID);
  1070. for ($i = 0; $i < $Buckets; $i++) {
  1071. if (isset($Updated[$i])) {
  1072. G::$Cache->cache_value("users_seeding_{$UserID}_$i", $SeedingTorrents[$i], 3600);
  1073. }
  1074. }
  1075. $UpdateTime['last'] = $CurTime;
  1076. $UpdateTime['next'] = $CurTime + self::SNATCHED_UPDATE_INTERVAL;
  1077. G::$Cache->cache_value("users_seeding_{$UserID}_time", $UpdateTime, 3600);
  1078. }
  1079. }
  1080. return isset($CurSeedingTorrents[$TorrentID]);
  1081. }
  1082. public static function is_leeching($TorrentID)
  1083. {
  1084. if (empty(G::$LoggedUser) || !isset(G::$LoggedUser['ShowSnatched']) || !G::$LoggedUser['ShowSnatched']) {
  1085. return false;
  1086. }
  1087. $UserID = G::$LoggedUser['ID'];
  1088. $Buckets = 64;
  1089. $LastBucket = $Buckets - 1;
  1090. $BucketID = $TorrentID & $LastBucket;
  1091. static $LeechingTorrents = [], $UpdateTime = [];
  1092. if (empty($LeechingTorrents)) {
  1093. $LeechingTorrents = array_fill(0, $Buckets, false);
  1094. $UpdateTime = G::$Cache->get_value("users_leeching_{$UserID}_time");
  1095. if ($UpdateTime === false) {
  1096. $UpdateTime = array(
  1097. 'last' => 0,
  1098. 'next' => 0);
  1099. }
  1100. } elseif (isset($LeechingTorrents[$BucketID][$TorrentID])) {
  1101. return true;
  1102. }
  1103. // Torrent was not found in the previously inspected snatch lists
  1104. $CurLeechingTorrents =& $LeechingTorrents[$BucketID];
  1105. if ($CurLeechingTorrents === false) {
  1106. $CurTime = time();
  1107. // This bucket hasn't been checked before
  1108. $CurLeechingTorrents = G::$Cache->get_value("users_leeching_{$UserID}_$BucketID", true);
  1109. if ($CurLeechingTorrents === false || $CurTime > $UpdateTime['next']) {
  1110. $Updated = [];
  1111. $QueryID = G::$DB->get_query_id();
  1112. if ($CurLeechingTorrents === false || $UpdateTime['last'] == 0) {
  1113. for ($i = 0; $i < $Buckets; $i++) {
  1114. $LeechingTorrents[$i] = [];
  1115. }
  1116. // Not found in cache. Since we don't have a suitable index, it's faster to update everything
  1117. G::$DB->query("
  1118. SELECT fid
  1119. FROM xbt_files_users
  1120. WHERE uid = ?
  1121. AND active = 1
  1122. AND Remaining > 0", $UserID);
  1123. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  1124. $LeechingTorrents[$ID & $LastBucket][(int)$ID] = true;
  1125. }
  1126. $Updated = array_fill(0, $Buckets, true);
  1127. } elseif (isset($CurLeechingTorrents[$TorrentID])) {
  1128. // Old cache, but torrent is leeching, so no need to update
  1129. return true;
  1130. } else {
  1131. // Old cache, check if torrent has been leeching recently
  1132. G::$DB->query("
  1133. SELECT fid
  1134. FROM xbt_files_users
  1135. WHERE uid = ?
  1136. AND active = 1
  1137. AND Remaining > 0
  1138. AND mtime >= ?", $UserID, $UpdateTime['last']);
  1139. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  1140. $CurBucketID = $ID & $LastBucket;
  1141. if ($LeechingTorrents[$CurBucketID] === false) {
  1142. $LeechingTorrents[$CurBucketID] = G::$Cache->get_value("users_leeching_{$UserID}_$CurBucketID", true);
  1143. if ($LeechingTorrents[$CurBucketID] === false) {
  1144. $LeechingTorrents[$CurBucketID] = [];
  1145. }
  1146. }
  1147. $LeechingTorrents[$CurBucketID][(int)$ID] = true;
  1148. $Updated[$CurBucketID] = true;
  1149. }
  1150. }
  1151. G::$DB->set_query_id($QueryID);
  1152. for ($i = 0; $i < $Buckets; $i++) {
  1153. if (isset($Updated[$i])) {
  1154. G::$Cache->cache_value("users_leeching_{$UserID}_$i", $LeechingTorrents[$i], 3600);
  1155. }
  1156. }
  1157. $UpdateTime['last'] = $CurTime;
  1158. $UpdateTime['next'] = $CurTime + self::SNATCHED_UPDATE_INTERVAL;
  1159. G::$Cache->cache_value("users_leeching_{$UserID}_time", $UpdateTime, 3600);
  1160. }
  1161. }
  1162. return isset($CurLeechingTorrents[$TorrentID]);
  1163. }
  1164. /*
  1165. public static function is_seeding_or_leeching($TorrentID) {
  1166. if (empty(G::$LoggedUser))
  1167. return false;
  1168. $UserID = G::$LoggedUser['ID'];
  1169. $Result = array("IsSeeding" => false, "IsLeeching" => false);
  1170. $QueryID = G::$DB->get_query_id();
  1171. G::$DB->query("
  1172. SELECT Remaining
  1173. FROM xbt_files_users
  1174. WHERE fid = $TorrentID
  1175. AND uid = $UserID
  1176. AND active = 1");
  1177. if (G::$DB->has_results()) {
  1178. while (($Row = G::$DB->next_record(MYSQLI_ASSOC, true)) && !($Result['IsSeeding'] && $Result['IsLeeching'])) {
  1179. if ($Row['Remaining'] == 0)
  1180. $Result['IsSeeding'] = true;
  1181. if ($Row['Remaining'] > 0)
  1182. $Result['IsLeeching'] = true;
  1183. }
  1184. }
  1185. G::$DB->set_query_id($QueryID);
  1186. return $Result;
  1187. }
  1188. */
  1189. /**
  1190. * Change the schedule for when the next update to a user's cached snatch list should be performed.
  1191. * By default, the change will only be made if the new update would happen sooner than the current
  1192. * @param int $Time Seconds until the next update
  1193. * @param bool $Force Whether to accept changes that would push back the update
  1194. */
  1195. public static function set_snatch_update_time($UserID, $Time, $Force = false)
  1196. {
  1197. if (!$UpdateTime = G::$Cache->get_value("users_snatched_{$UserID}_time")) {
  1198. return;
  1199. }
  1200. $NextTime = time() + $Time;
  1201. if ($Force || $NextTime < $UpdateTime['next']) {
  1202. // Skip if the change would delay the next update
  1203. $UpdateTime['next'] = $NextTime;
  1204. G::$Cache->cache_value("users_snatched_{$UserID}_time", $UpdateTime, 0);
  1205. }
  1206. }
  1207. // Some constants for self::display_string's $Mode parameter
  1208. const DISPLAYSTRING_HTML = 1; // Whether or not to use HTML for the output (e.g. VH tooltip)
  1209. const DISPLAYSTRING_ARTISTS = 2; // Whether or not to display artists
  1210. const DISPLAYSTRING_YEAR = 4; // Whether or not to display the group's year
  1211. const DISPLAYSTRING_VH = 8; // Whether or not to display the VH flag
  1212. const DISPLAYSTRING_RELEASETYPE = 16; // Whether or not to display the release type
  1213. const DISPLAYSTRING_LINKED = 33; // Whether or not to link artists and the group
  1214. // The constant for linking is 32, but because linking only works with HTML, this constant is defined as 32|1 = 33, i.e. LINKED also includes HTML
  1215. // Keep this in mind when defining presets below!
  1216. // Presets to facilitate the use of $Mode
  1217. const DISPLAYSTRING_DEFAULT = 63; // HTML|ARTISTS|YEAR|VH|RELEASETYPE|LINKED = 63
  1218. const DISPLAYSTRING_SHORT = 6; // Very simple format, only artists and year, no linking (e.g. for forum thread titles)
  1219. /**
  1220. * Return the display string for a given torrent group $GroupID.
  1221. * @param int $GroupID
  1222. * @return string
  1223. */
  1224. public static function display_string($GroupID, $Mode = self::DISPLAYSTRING_DEFAULT)
  1225. {
  1226. #global $ReleaseTypes; // I hate this
  1227. $GroupInfo = self::get_groups(array($GroupID), true, true, false)[$GroupID];
  1228. $ExtendedArtists = $GroupInfo['ExtendedArtists'];
  1229. if ($Mode & self::DISPLAYSTRING_ARTISTS) {
  1230. if (!empty($ExtendedArtists[1])
  1231. || !empty($ExtendedArtists[4])
  1232. || !empty($ExtendedArtists[5])
  1233. || !empty($ExtendedArtists[6])
  1234. ) {
  1235. unset($ExtendedArtists[2], $ExtendedArtists[3]);
  1236. $DisplayName = Artists::display_artists($ExtendedArtists, ($Mode & self::DISPLAYSTRING_LINKED));
  1237. } else {
  1238. $DisplayName = '';
  1239. }
  1240. }
  1241. if ($Mode & self::DISPLAYSTRING_LINKED) {
  1242. $DisplayName .= "<a href=\"torrents.php?id=$GroupID\" class=\"tooltip\" title=\"View torrent group\" dir=\"ltr\">$GroupInfo[Name]</a>";
  1243. } else {
  1244. $DisplayName .= $GroupInfo['Name'];
  1245. }
  1246. if (($Mode & self::DISPLAYSTRING_YEAR) && $GroupInfo['Year'] > 0) {
  1247. $DisplayName .= " [$GroupInfo[Year]]";
  1248. }
  1249. if (($Mode & self::DISPLAYSTRING_RELEASETYPE) && $GroupInfo['ReleaseType'] > 0) {
  1250. $DisplayName .= ' ['.$ReleaseTypes[$GroupInfo['ReleaseType']].']';
  1251. }
  1252. return $DisplayName;
  1253. }
  1254. public static function edition_string(array $Torrent, array $Group)
  1255. {
  1256. /*
  1257. $AddExtra = '&thinsp;|&thinsp;'; # breaking
  1258. $EditionName = 'Original Release';
  1259. $EditionName .= $AddExtra . display_str($Torrent['Media']);
  1260. return $EditionName;
  1261. */
  1262. }
  1263. // Used to get reports info on a unison cache in both browsing pages and torrent pages.
  1264. public static function get_reports($TorrentID)
  1265. {
  1266. $Reports = G::$Cache->get_value("reports_torrent_$TorrentID");
  1267. if ($Reports === false) {
  1268. $QueryID = G::$DB->get_query_id();
  1269. G::$DB->query("
  1270. SELECT
  1271. ID,
  1272. ReporterID,
  1273. Type,
  1274. UserComment,
  1275. ReportedTime
  1276. FROM reportsv2
  1277. WHERE TorrentID = ?
  1278. AND Status != 'Resolved'", $TorrentID);
  1279. $Reports = G::$DB->to_array(false, MYSQLI_ASSOC, false);
  1280. G::$DB->set_query_id($QueryID);
  1281. G::$Cache->cache_value("reports_torrent_$TorrentID", $Reports, 0);
  1282. }
  1283. if (!check_perms('admin_reports')) {
  1284. $Return = [];
  1285. foreach ($Reports as $Report) {
  1286. if ($Report['Type'] !== 'edited') {
  1287. $Return[] = $Report;
  1288. }
  1289. }
  1290. return $Return;
  1291. }
  1292. return $Reports;
  1293. }
  1294. }