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

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