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

torrents.class.php 44KB

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