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

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