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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. G::$DB->query("
  297. DELETE FROM torrents_files
  298. WHERE TorrentID = '$ID'");
  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, TagList, Year, CataLogueNumber, CategoryID, Time,
  475. Size, Snatched, Seeders, Leechers,
  476. FreeTorrent, Media, Container, Codec, Resolution, AudioFormat, Subbing, Language, Description,
  477. FileList, VoteScore, ArtistName)
  478. SELECT
  479. t.ID, g.ID, Name, TagList, Year, CatalogueNumber, CategoryID, UNIX_TIMESTAMP(t.Time),
  480. Size, Snatched, Seeders,
  481. Leechers,
  482. CAST(FreeTorrent AS CHAR), Media, Container, Codec, Resolution, AudioFormat, Subbing, Language, Description,
  483. REPLACE(REPLACE(FileList, '_', ' '), '/', ' ') AS FileList, $VoteScore, '".db_string($ArtistName)."'
  484. FROM torrents AS t
  485. JOIN torrents_group AS g ON g.ID = t.GroupID
  486. WHERE g.ID = $GroupID");
  487. G::$Cache->delete_value("torrents_details_$GroupID");
  488. G::$Cache->delete_value("torrent_group_$GroupID");
  489. G::$Cache->delete_value("torrent_group_light_$GroupID");
  490. $ArtistInfo = Artists::get_artist($GroupID);
  491. /*
  492. foreach ($ArtistInfo as $Importances => $Importance) {
  493. foreach ($Importance as $Artist) {
  494. G::$Cache->delete_value('artist_groups_'.$Artist['id']); //Needed for at least freeleech change, if not others.
  495. }
  496. }
  497. */
  498. G::$Cache->delete_value("groups_artists_$GroupID");
  499. G::$DB->set_query_id($QueryID);
  500. }
  501. /**
  502. * Regenerate a torrent's file list from its meta data,
  503. * update the database record and clear relevant cache keys
  504. *
  505. * @param int $TorrentID
  506. */
  507. public static function regenerate_filelist($TorrentID) {
  508. $QueryID = G::$DB->get_query_id();
  509. G::$DB->query("
  510. SELECT tg.ID,
  511. tf.File
  512. FROM torrents_files AS tf
  513. JOIN torrents AS t ON t.ID = tf.TorrentID
  514. JOIN torrents_group AS tg ON tg.ID = t.GroupID
  515. WHERE tf.TorrentID = $TorrentID");
  516. if (G::$DB->has_results()) {
  517. list($GroupID, $Contents) = G::$DB->next_record(MYSQLI_NUM, false);
  518. if (Misc::is_new_torrent($Contents)) {
  519. $Tor = new BencodeTorrent($Contents);
  520. $FilePath = (isset($Tor->Dec['info']['files']) ? Format::make_utf8($Tor->get_name()) : '');
  521. } else {
  522. $Tor = new TORRENT(unserialize(base64_decode($Contents)), true);
  523. $FilePath = (isset($Tor->Val['info']->Val['files']) ? Format::make_utf8($Tor->get_name()) : '');
  524. }
  525. list($TotalSize, $FileList) = $Tor->file_list();
  526. foreach ($FileList as $File) {
  527. $TmpFileList[] = self::filelist_format_file($File);
  528. }
  529. $FileString = implode("\n", $TmpFileList);
  530. G::$DB->query("
  531. UPDATE torrents
  532. SET Size = $TotalSize, FilePath = '".db_string($FilePath)."', FileList = '".db_string($FileString)."'
  533. WHERE ID = $TorrentID");
  534. G::$Cache->delete_value("torrents_details_$GroupID");
  535. }
  536. G::$DB->set_query_id($QueryID);
  537. }
  538. /**
  539. * Return UTF-8 encoded string to use as file delimiter in torrent file lists
  540. */
  541. public static function filelist_delim() {
  542. static $FilelistDelimUTF8;
  543. if (isset($FilelistDelimUTF8)) {
  544. return $FilelistDelimUTF8;
  545. }
  546. return $FilelistDelimUTF8 = utf8_encode(chr(self::FILELIST_DELIM));
  547. }
  548. /**
  549. * Create a string that contains file info in a format that's easy to use for Sphinx
  550. *
  551. * @param array $File (File size, File name)
  552. * @return string with the format .EXT sSIZEs NAME DELIMITER
  553. */
  554. public static function filelist_format_file($File) {
  555. list($Size, $Name) = $File;
  556. $Name = Format::make_utf8(strtr($Name, "\n\r\t", ' '));
  557. $ExtPos = strrpos($Name, '.');
  558. // Should not be $ExtPos !== false. Extensionless files that start with a . should not get extensions
  559. $Ext = ($ExtPos ? trim(substr($Name, $ExtPos + 1)) : '');
  560. return sprintf("%s s%ds %s %s", ".$Ext", $Size, $Name, self::filelist_delim());
  561. }
  562. /**
  563. * Create a string that contains file info in the old format for the API
  564. *
  565. * @param string $File string with the format .EXT sSIZEs NAME DELIMITER
  566. * @return string with the format NAME{{{SIZE}}}
  567. */
  568. public static function filelist_old_format($File) {
  569. $File = self::filelist_get_file($File);
  570. return $File['name'] . '{{{' . $File['size'] . '}}}';
  571. }
  572. /**
  573. * Translate a formatted file info string into a more useful array structure
  574. *
  575. * @param string $File string with the format .EXT sSIZEs NAME DELIMITER
  576. * @return file info array with the keys 'ext', 'size' and 'name'
  577. */
  578. public static function filelist_get_file($File) {
  579. // Need this hack because filelists are always display_str()ed
  580. $DelimLen = strlen(display_str(self::filelist_delim())) + 1;
  581. list($FileExt, $Size, $Name) = explode(' ', $File, 3);
  582. if ($Spaces = strspn($Name, ' ')) {
  583. $Name = str_replace(' ', '&nbsp;', substr($Name, 0, $Spaces)) . substr($Name, $Spaces);
  584. }
  585. return array(
  586. 'ext' => $FileExt,
  587. 'size' => substr($Size, 1, -1),
  588. 'name' => substr($Name, 0, -$DelimLen)
  589. );
  590. }
  591. /**
  592. * Format the information about a torrent.
  593. * @param $Data an array a subset of the following keys:
  594. * Format, Encoding, HasLog, LogScore HasCue, Media, Scene, RemasterYear
  595. * RemasterTitle, FreeTorrent, PersonalFL
  596. * @param boolean $ShowMedia if false, Media key will be omitted
  597. * @param boolean $ShowEdition if false, RemasterYear/RemasterTitle will be omitted
  598. */
  599. public static function torrent_info($Data, $ShowMedia = true, $ShowEdition = false, $HTMLy = true) {
  600. $Info = array();
  601. if ($ShowMedia && !empty($Data['Media'])) {
  602. $Info[] = $Data['Media'];
  603. }
  604. if (!empty($Data['Container'])) {
  605. $Info[] = $Data['Container'];
  606. }
  607. if (!empty($Data['Codec'])) {
  608. $Info[] = $Data['Codec'];
  609. }
  610. if (!empty($Data['Resolution'])) {
  611. $Info[] = $Data['Resolution'];
  612. }
  613. if (!empty($Data['AudioFormat'])) {
  614. $Info[] = $Data['AudioFormat'];
  615. }
  616. if (!empty($Data['Language'])) {
  617. if (!empty($Data['Subber']) && isset($Data['CategoryID']) && ($Data['CategoryID'] == 3 || $Data['CategoryID'] == 4)) {
  618. $Info[] = $Data['Language']." (".$Data['Subber'].")";
  619. } else {
  620. $Info[] = $Data['Language'];
  621. }
  622. }
  623. if (!empty($Data['Subbing'])) {
  624. if (!empty($Data['Subber'])) {
  625. if (isset($Data['CategoryID']) && ($Data['CategoryID'] == 2 || $Data['CategoryID'] == 1) && $Data['Subbing'] != "RAW") {
  626. $Info[] = $Data['Subbing'] . " (" . $Data['Subber'] . ")";
  627. }
  628. } else {
  629. $Info[] = $Data['Subbing'];
  630. }
  631. }
  632. if (!empty($Data['Archive'])) {
  633. $Info[] = 'Archived ('.$Data['Archive'].')';
  634. }
  635. if (isset($Data['Censored']) && !$Data['Censored']) {
  636. $Info[] = $HTMLy ? Format::torrent_label('Uncensored') : 'Uncensored';
  637. }
  638. if ($Data['IsLeeching']) {
  639. $Info[] = $HTMLy ? Format::torrent_label('Leeching') : 'Leeching';
  640. } else if ($Data['IsSeeding']) {
  641. $Info[] = $HTMLy ? Format::torrent_label('Seeding') : 'Seeding';
  642. } else if ($Data['IsSnatched']) {
  643. $Info[] = $HTMLy ? Format::torrent_label('Snatched') : 'Snatched';
  644. }
  645. if ($Data['FreeTorrent'] == '1') {
  646. if ($Data['FreeLeechType'] == '3') {
  647. $QueryID = G::$DB->get_query_id();
  648. G::$DB->query("
  649. SELECT GREATEST(NOW(), ExpiryTime)
  650. FROM shop_freeleeches
  651. WHERE TorrentID = ".$Data['ID']);
  652. if (G::$DB->has_results()) {
  653. $ExpiryTime = G::$DB->next_record(MYSQLI_NUM, false)[0];
  654. $Info[] = ($HTMLy ? Format::torrent_label('Freeleech!') : 'Freeleech!') . ($HTMLy ? " <strong>(" : " (") . str_replace(['day','hour','min','Just now','s',' '],['d','h','m','0m'],time_diff($ExpiryTime, 1, false)) . ($HTMLy ? ")</strong>" : ")");
  655. } else {
  656. $Info[] = $HTMLy ? Format::torrent_label('Freeleech!') : 'Freeleech!';
  657. }
  658. G::$DB->set_query_id($QueryID);
  659. } else {
  660. $Info[] = $HTMLy ? Format::torrent_label('Freeleech!') : 'Freeleech!';
  661. }
  662. }
  663. if ($Data['FreeTorrent'] == '2') {
  664. $Info[] = $HTMLy ? Format::torrent_label('Neutral Leech!') : 'Neutral Leech!';
  665. }
  666. if ($Data['PersonalFL']) {
  667. $Info[] = $HTMLy ? Format::torrent_label('Personal Freeleech!') : 'Personal Freeleech!';
  668. }
  669. return implode(' / ', $Info);
  670. }
  671. /**
  672. * Will freeleech / neutral leech / normalise a set of torrents
  673. *
  674. * @param array $TorrentIDs An array of torrent IDs to iterate over
  675. * @param int $FreeNeutral 0 = normal, 1 = fl, 2 = nl
  676. * @param int $FreeLeechType 0 = Unknown, 1 = Staff picks, 2 = Perma-FL (Toolbox, etc.), 3 = Vanity House
  677. */
  678. public static function freeleech_torrents($TorrentIDs, $FreeNeutral = 1, $FreeLeechType = 0, $Announce = true) {
  679. if (!is_array($TorrentIDs)) {
  680. $TorrentIDs = array($TorrentIDs);
  681. }
  682. $QueryID = G::$DB->get_query_id();
  683. G::$DB->query("
  684. UPDATE torrents
  685. SET FreeTorrent = '$FreeNeutral', FreeLeechType = '$FreeLeechType'
  686. WHERE ID IN (".implode(', ', $TorrentIDs).')');
  687. G::$DB->query('
  688. SELECT ID, GroupID, info_hash
  689. FROM torrents
  690. WHERE ID IN ('.implode(', ', $TorrentIDs).')
  691. ORDER BY GroupID ASC');
  692. $Torrents = G::$DB->to_array(false, MYSQLI_NUM, false);
  693. $GroupIDs = G::$DB->collect('GroupID');
  694. G::$DB->set_query_id($QueryID);
  695. foreach ($Torrents as $Torrent) {
  696. list($TorrentID, $GroupID, $InfoHash) = $Torrent;
  697. Tracker::update_tracker('update_torrent', array('info_hash' => rawurlencode($InfoHash), 'freetorrent' => $FreeNeutral));
  698. G::$Cache->delete_value("torrent_download_$TorrentID");
  699. Misc::write_log((G::$LoggedUser['Username']??'System')." marked torrent $TorrentID freeleech type $FreeLeechType");
  700. Torrents::write_group_log($GroupID, $TorrentID, (G::$LoggedUser['ID']??0), "marked as freeleech type $FreeLeechType", 0);
  701. if ($Announce && ($FreeLeechType == 1 || $FreeLeechType == 3)) {
  702. send_irc('PRIVMSG '.BOT_ANNOUNCE_CHAN.' FREELEECH - '.site_url()."torrents.php?id=$GroupID / ".site_url()."torrents.php?action=download&id=$TorrentID");
  703. }
  704. }
  705. foreach ($GroupIDs as $GroupID) {
  706. Torrents::update_hash($GroupID);
  707. }
  708. }
  709. /**
  710. * Convenience function to allow for passing groups to Torrents::freeleech_torrents()
  711. *
  712. * @param array $GroupIDs the groups in question
  713. * @param int $FreeNeutral see Torrents::freeleech_torrents()
  714. * @param int $FreeLeechType see Torrents::freeleech_torrents()
  715. */
  716. public static function freeleech_groups($GroupIDs, $FreeNeutral = 1, $FreeLeechType = 0) {
  717. $QueryID = G::$DB->get_query_id();
  718. if (!is_array($GroupIDs)) {
  719. $GroupIDs = array($GroupIDs);
  720. }
  721. G::$DB->query('
  722. SELECT ID
  723. FROM torrents
  724. WHERE GroupID IN ('.implode(', ', $GroupIDs).')');
  725. if (G::$DB->has_results()) {
  726. $TorrentIDs = G::$DB->collect('ID');
  727. Torrents::freeleech_torrents($TorrentIDs, $FreeNeutral, $FreeLeechType);
  728. }
  729. G::$DB->set_query_id($QueryID);
  730. }
  731. /**
  732. * Check if the logged in user has an active freeleech token
  733. *
  734. * @param int $TorrentID
  735. * @return true if an active token exists
  736. */
  737. public static function has_token($TorrentID) {
  738. if (empty(G::$LoggedUser)) {
  739. return false;
  740. }
  741. static $TokenTorrents;
  742. $UserID = G::$LoggedUser['ID'];
  743. if (!isset($TokenTorrents)) {
  744. $TokenTorrents = G::$Cache->get_value("users_tokens_$UserID");
  745. if ($TokenTorrents === false) {
  746. $QueryID = G::$DB->get_query_id();
  747. G::$DB->query("
  748. SELECT TorrentID
  749. FROM users_freeleeches
  750. WHERE UserID = $UserID
  751. AND Expired = 0");
  752. $TokenTorrents = array_fill_keys(G::$DB->collect('TorrentID', false), true);
  753. G::$DB->set_query_id($QueryID);
  754. G::$Cache->cache_value("users_tokens_$UserID", $TokenTorrents);
  755. }
  756. }
  757. return isset($TokenTorrents[$TorrentID]);
  758. }
  759. /**
  760. * Check if the logged in user can use a freeleech token on this torrent
  761. *
  762. * @param int $Torrent
  763. * @return boolen True if user is allowed to use a token
  764. */
  765. public static function can_use_token($Torrent) {
  766. if (empty(G::$LoggedUser)) {
  767. return false;
  768. }
  769. return (G::$LoggedUser['FLTokens'] > 0
  770. && $Torrent['Size'] <= 10737418240
  771. && !$Torrent['PersonalFL']
  772. && empty($Torrent['FreeTorrent'])
  773. && G::$LoggedUser['CanLeech'] == '1');
  774. }
  775. /**
  776. * Build snatchlists and check if a torrent has been snatched
  777. * if a user has the 'ShowSnatched' option enabled
  778. * @param int $TorrentID
  779. * @return bool
  780. */
  781. public static function has_snatched($TorrentID) {
  782. if (empty(G::$LoggedUser) || !isset(G::$LoggedUser['ShowSnatched']) || !G::$LoggedUser['ShowSnatched']) {
  783. return false;
  784. }
  785. $UserID = G::$LoggedUser['ID'];
  786. $Buckets = 64;
  787. $LastBucket = $Buckets - 1;
  788. $BucketID = $TorrentID & $LastBucket;
  789. static $SnatchedTorrents = array(), $UpdateTime = array();
  790. if (empty($SnatchedTorrents)) {
  791. $SnatchedTorrents = array_fill(0, $Buckets, false);
  792. $UpdateTime = G::$Cache->get_value("users_snatched_{$UserID}_time");
  793. if ($UpdateTime === false) {
  794. $UpdateTime = array(
  795. 'last' => 0,
  796. 'next' => 0);
  797. }
  798. } elseif (isset($SnatchedTorrents[$BucketID][$TorrentID])) {
  799. return true;
  800. }
  801. // Torrent was not found in the previously inspected snatch lists
  802. $CurSnatchedTorrents =& $SnatchedTorrents[$BucketID];
  803. if ($CurSnatchedTorrents === false) {
  804. $CurTime = time();
  805. // This bucket hasn't been checked before
  806. $CurSnatchedTorrents = G::$Cache->get_value("users_snatched_{$UserID}_$BucketID", true);
  807. if ($CurSnatchedTorrents === false || $CurTime > $UpdateTime['next']) {
  808. $Updated = array();
  809. $QueryID = G::$DB->get_query_id();
  810. if ($CurSnatchedTorrents === false || $UpdateTime['last'] == 0) {
  811. for ($i = 0; $i < $Buckets; $i++) {
  812. $SnatchedTorrents[$i] = array();
  813. }
  814. // Not found in cache. Since we don't have a suitable index, it's faster to update everything
  815. G::$DB->query("
  816. SELECT fid
  817. FROM xbt_snatched
  818. WHERE uid = '$UserID'");
  819. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  820. $SnatchedTorrents[$ID & $LastBucket][(int)$ID] = true;
  821. }
  822. $Updated = array_fill(0, $Buckets, true);
  823. } elseif (isset($CurSnatchedTorrents[$TorrentID])) {
  824. // Old cache, but torrent is snatched, so no need to update
  825. return true;
  826. } else {
  827. // Old cache, check if torrent has been snatched recently
  828. G::$DB->query("
  829. SELECT fid
  830. FROM xbt_snatched
  831. WHERE uid = '$UserID'
  832. AND tstamp >= $UpdateTime[last]");
  833. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  834. $CurBucketID = $ID & $LastBucket;
  835. if ($SnatchedTorrents[$CurBucketID] === false) {
  836. $SnatchedTorrents[$CurBucketID] = G::$Cache->get_value("users_snatched_{$UserID}_$CurBucketID", true);
  837. if ($SnatchedTorrents[$CurBucketID] === false) {
  838. $SnatchedTorrents[$CurBucketID] = array();
  839. }
  840. }
  841. $SnatchedTorrents[$CurBucketID][(int)$ID] = true;
  842. $Updated[$CurBucketID] = true;
  843. }
  844. }
  845. G::$DB->set_query_id($QueryID);
  846. for ($i = 0; $i < $Buckets; $i++) {
  847. if (isset($Updated[$i])) {
  848. G::$Cache->cache_value("users_snatched_{$UserID}_$i", $SnatchedTorrents[$i], 0);
  849. }
  850. }
  851. $UpdateTime['last'] = $CurTime;
  852. $UpdateTime['next'] = $CurTime + self::SNATCHED_UPDATE_INTERVAL;
  853. G::$Cache->cache_value("users_snatched_{$UserID}_time", $UpdateTime, 0);
  854. }
  855. }
  856. return isset($CurSnatchedTorrents[$TorrentID]);
  857. }
  858. public static function is_seeding($TorrentID) {
  859. if (empty(G::$LoggedUser) || !isset(G::$LoggedUser['ShowSnatched']) || !G::$LoggedUser['ShowSnatched']) {
  860. return false;
  861. }
  862. $UserID = G::$LoggedUser['ID'];
  863. $Buckets = 64;
  864. $LastBucket = $Buckets - 1;
  865. $BucketID = $TorrentID & $LastBucket;
  866. static $SeedingTorrents = array(), $UpdateTime = array();
  867. if (empty($SeedingTorrents)) {
  868. $SeedingTorrents = array_fill(0, $Buckets, false);
  869. $UpdateTime = G::$Cache->get_value("users_seeding_{$UserID}_time");
  870. if ($UpdateTime === false) {
  871. $UpdateTime = array(
  872. 'last' => 0,
  873. 'next' => 0);
  874. }
  875. } elseif (isset($SeedingTorrents[$BucketID][$TorrentID])) {
  876. return true;
  877. }
  878. // Torrent was not found in the previously inspected seeding lists
  879. $CurSeedingTorrents =& $SeedingTorrents[$BucketID];
  880. if ($CurSeedingTorrents === false) {
  881. $CurTime = time();
  882. // This bucket hasn't been checked before
  883. $CurSeedingTorrents = G::$Cache->get_value("users_seeding_{$UserID}_$BucketID", true);
  884. if ($CurSeedingTorrents === false || $CurTime > $UpdateTime['next']) {
  885. $Updated = array();
  886. $QueryID = G::$DB->get_query_id();
  887. if ($CurSeedingTorrents === false || $UpdateTime['last'] == 0) {
  888. for ($i = 0; $i < $Buckets; $i++) {
  889. $SeedingTorrents[$i] = array();
  890. }
  891. // Not found in cache. Since we don't have a suitable index, it's faster to update everything
  892. G::$DB->query("
  893. SELECT fid
  894. FROM xbt_files_users
  895. WHERE uid = $UserID
  896. AND active = 1
  897. AND Remaining = 0");
  898. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  899. $SeedingTorrents[$ID & $LastBucket][(int)$ID] = true;
  900. }
  901. $Updated = array_fill(0, $Buckets, true);
  902. } elseif (isset($CurSeedingTorrents[$TorrentID])) {
  903. // Old cache, but torrent is seeding, so no need to update
  904. return true;
  905. } else {
  906. // Old cache, check if torrent has been seeding recently
  907. G::$DB->query("
  908. SELECT fid
  909. FROM xbt_files_users
  910. WHERE uid = '$UserID'
  911. AND active = 1
  912. AND Remaining = 0
  913. AND mtime >= $UpdateTime[last]");
  914. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  915. $CurBucketID = $ID & $LastBucket;
  916. if ($SeedingTorrents[$CurBucketID] === false) {
  917. $SeedingTorrents[$CurBucketID] = G::$Cache->get_value("users_seeding_{$UserID}_$CurBucketID", true);
  918. if ($SeedingTorrents[$CurBucketID] === false) {
  919. $SeedingTorrents[$CurBucketID] = array();
  920. }
  921. }
  922. $SeedingTorrents[$CurBucketID][(int)$ID] = true;
  923. $Updated[$CurBucketID] = true;
  924. }
  925. }
  926. G::$DB->set_query_id($QueryID);
  927. for ($i = 0; $i < $Buckets; $i++) {
  928. if (isset($Updated[$i])) {
  929. G::$Cache->cache_value("users_seeding_{$UserID}_$i", $SeedingTorrents[$i], 3600);
  930. }
  931. }
  932. $UpdateTime['last'] = $CurTime;
  933. $UpdateTime['next'] = $CurTime + self::SNATCHED_UPDATE_INTERVAL;
  934. G::$Cache->cache_value("users_seeding_{$UserID}_time", $UpdateTime, 3600);
  935. }
  936. }
  937. return isset($CurSeedingTorrents[$TorrentID]);
  938. }
  939. public static function is_leeching($TorrentID) {
  940. if (empty(G::$LoggedUser) || !isset(G::$LoggedUser['ShowSnatched']) || !G::$LoggedUser['ShowSnatched']) {
  941. return false;
  942. }
  943. $UserID = G::$LoggedUser['ID'];
  944. $Buckets = 64;
  945. $LastBucket = $Buckets - 1;
  946. $BucketID = $TorrentID & $LastBucket;
  947. static $LeechingTorrents = array(), $UpdateTime = array();
  948. if (empty($LeechingTorrents)) {
  949. $LeechingTorrents = array_fill(0, $Buckets, false);
  950. $UpdateTime = G::$Cache->get_value("users_leeching_{$UserID}_time");
  951. if ($UpdateTime === false) {
  952. $UpdateTime = array(
  953. 'last' => 0,
  954. 'next' => 0);
  955. }
  956. } elseif (isset($LeechingTorrents[$BucketID][$TorrentID])) {
  957. return true;
  958. }
  959. // Torrent was not found in the previously inspected snatch lists
  960. $CurLeechingTorrents =& $LeechingTorrents[$BucketID];
  961. if ($CurLeechingTorrents === false) {
  962. $CurTime = time();
  963. // This bucket hasn't been checked before
  964. $CurLeechingTorrents = G::$Cache->get_value("users_leeching_{$UserID}_$BucketID", true);
  965. if ($CurLeechingTorrents === false || $CurTime > $UpdateTime['next']) {
  966. $Updated = array();
  967. $QueryID = G::$DB->get_query_id();
  968. if ($CurLeechingTorrents === false || $UpdateTime['last'] == 0) {
  969. for ($i = 0; $i < $Buckets; $i++) {
  970. $LeechingTorrents[$i] = array();
  971. }
  972. // Not found in cache. Since we don't have a suitable index, it's faster to update everything
  973. G::$DB->query("
  974. SELECT fid
  975. FROM xbt_files_users
  976. WHERE uid = $UserID
  977. AND active = 1
  978. AND Remaining > 0");
  979. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  980. $LeechingTorrents[$ID & $LastBucket][(int)$ID] = true;
  981. }
  982. $Updated = array_fill(0, $Buckets, true);
  983. } elseif (isset($CurLeechingTorrents[$TorrentID])) {
  984. // Old cache, but torrent is leeching, so no need to update
  985. return true;
  986. } else {
  987. // Old cache, check if torrent has been leeching recently
  988. G::$DB->query("
  989. SELECT fid
  990. FROM xbt_files_users
  991. WHERE uid = '$UserID'
  992. AND active = 1
  993. AND Remaining > 0
  994. AND mtime >= $UpdateTime[last]");
  995. while (list($ID) = G::$DB->next_record(MYSQLI_NUM, false)) {
  996. $CurBucketID = $ID & $LastBucket;
  997. if ($LeechingTorrents[$CurBucketID] === false) {
  998. $LeechingTorrents[$CurBucketID] = G::$Cache->get_value("users_leeching_{$UserID}_$CurBucketID", true);
  999. if ($LeechingTorrents[$CurBucketID] === false) {
  1000. $LeechingTorrents[$CurBucketID] = array();
  1001. }
  1002. }
  1003. $LeechingTorrents[$CurBucketID][(int)$ID] = true;
  1004. $Updated[$CurBucketID] = true;
  1005. }
  1006. }
  1007. G::$DB->set_query_id($QueryID);
  1008. for ($i = 0; $i < $Buckets; $i++) {
  1009. if (isset($Updated[$i])) {
  1010. G::$Cache->cache_value("users_leeching_{$UserID}_$i", $LeechingTorrents[$i], 3600);
  1011. }
  1012. }
  1013. $UpdateTime['last'] = $CurTime;
  1014. $UpdateTime['next'] = $CurTime + self::SNATCHED_UPDATE_INTERVAL;
  1015. G::$Cache->cache_value("users_leeching_{$UserID}_time", $UpdateTime, 3600);
  1016. }
  1017. }
  1018. return isset($CurLeechingTorrents[$TorrentID]);
  1019. }
  1020. /*public static function is_seeding_or_leeching($TorrentID) {
  1021. if (empty(G::$LoggedUser))
  1022. return false;
  1023. $UserID = G::$LoggedUser['ID'];
  1024. $Result = array("IsSeeding" => false, "IsLeeching" => false);
  1025. $QueryID = G::$DB->get_query_id();
  1026. G::$DB->query("
  1027. SELECT Remaining
  1028. FROM xbt_files_users
  1029. WHERE fid = $TorrentID
  1030. AND uid = $UserID
  1031. AND active = 1");
  1032. if (G::$DB->has_results()) {
  1033. while (($Row = G::$DB->next_record(MYSQLI_ASSOC, true)) && !($Result['IsSeeding'] && $Result['IsLeeching'])) {
  1034. if ($Row['Remaining'] == 0)
  1035. $Result['IsSeeding'] = true;
  1036. if ($Row['Remaining'] > 0)
  1037. $Result['IsLeeching'] = true;
  1038. }
  1039. }
  1040. G::$DB->set_query_id($QueryID);
  1041. return $Result;
  1042. }*/
  1043. /**
  1044. * Change the schedule for when the next update to a user's cached snatch list should be performed.
  1045. * By default, the change will only be made if the new update would happen sooner than the current
  1046. * @param int $Time Seconds until the next update
  1047. * @param bool $Force Whether to accept changes that would push back the update
  1048. */
  1049. public static function set_snatch_update_time($UserID, $Time, $Force = false) {
  1050. if (!$UpdateTime = G::$Cache->get_value("users_snatched_{$UserID}_time")) {
  1051. return;
  1052. }
  1053. $NextTime = time() + $Time;
  1054. if ($Force || $NextTime < $UpdateTime['next']) {
  1055. // Skip if the change would delay the next update
  1056. $UpdateTime['next'] = $NextTime;
  1057. G::$Cache->cache_value("users_snatched_{$UserID}_time", $UpdateTime, 0);
  1058. }
  1059. }
  1060. // Some constants for self::display_string's $Mode parameter
  1061. const DISPLAYSTRING_HTML = 1; // Whether or not to use HTML for the output (e.g. VH tooltip)
  1062. const DISPLAYSTRING_ARTISTS = 2; // Whether or not to display artists
  1063. const DISPLAYSTRING_YEAR = 4; // Whether or not to display the group's year
  1064. const DISPLAYSTRING_VH = 8; // Whether or not to display the VH flag
  1065. const DISPLAYSTRING_RELEASETYPE = 16; // Whether or not to display the release type
  1066. const DISPLAYSTRING_LINKED = 33; // Whether or not to link artists and the group
  1067. // 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
  1068. // Keep this in mind when defining presets below!
  1069. // Presets to facilitate the use of $Mode
  1070. const DISPLAYSTRING_DEFAULT = 63; // HTML|ARTISTS|YEAR|VH|RELEASETYPE|LINKED = 63
  1071. const DISPLAYSTRING_SHORT = 6; // Very simple format, only artists and year, no linking (e.g. for forum thread titles)
  1072. /**
  1073. * Return the display string for a given torrent group $GroupID.
  1074. * @param int $GroupID
  1075. * @return string
  1076. */
  1077. public static function display_string($GroupID, $Mode = self::DISPLAYSTRING_DEFAULT) {
  1078. global $ReleaseTypes; // I hate this
  1079. $GroupInfo = self::get_groups(array($GroupID), true, true, false)[$GroupID];
  1080. $ExtendedArtists = $GroupInfo['ExtendedArtists'];
  1081. if ($Mode & self::DISPLAYSTRING_ARTISTS) {
  1082. if (!empty($ExtendedArtists[1])
  1083. || !empty($ExtendedArtists[4])
  1084. || !empty($ExtendedArtists[5])
  1085. || !empty($ExtendedArtists[6])
  1086. ) {
  1087. unset($ExtendedArtists[2], $ExtendedArtists[3]);
  1088. $DisplayName = Artists::display_artists($ExtendedArtists, ($Mode & self::DISPLAYSTRING_LINKED));
  1089. } else {
  1090. $DisplayName = '';
  1091. }
  1092. }
  1093. if ($Mode & self::DISPLAYSTRING_LINKED) {
  1094. $DisplayName .= "<a href=\"torrents.php?id=$GroupID\" class=\"tooltip\" title=\"View torrent group\" dir=\"ltr\">$GroupInfo[Name]</a>";
  1095. } else {
  1096. $DisplayName .= $GroupInfo['Name'];
  1097. }
  1098. if (($Mode & self::DISPLAYSTRING_YEAR) && $GroupInfo['Year'] > 0) {
  1099. $DisplayName .= " [$GroupInfo[Year]]";
  1100. }
  1101. if (($Mode & self::DISPLAYSTRING_RELEASETYPE) && $GroupInfo['ReleaseType'] > 0) {
  1102. $DisplayName .= ' ['.$ReleaseTypes[$GroupInfo['ReleaseType']].']';
  1103. }
  1104. return $DisplayName;
  1105. }
  1106. public static function edition_string(array $Torrent, array $Group) {
  1107. $AddExtra = ' / ';
  1108. $EditionName = 'Original Release';
  1109. $EditionName .= $AddExtra . display_str($Torrent['Media']);
  1110. return $EditionName;
  1111. }
  1112. //Used to get reports info on a unison cache in both browsing pages and torrent pages.
  1113. public static function get_reports($TorrentID) {
  1114. $Reports = G::$Cache->get_value("reports_torrent_$TorrentID");
  1115. if ($Reports === false) {
  1116. $QueryID = G::$DB->get_query_id();
  1117. G::$DB->query("
  1118. SELECT
  1119. ID,
  1120. ReporterID,
  1121. Type,
  1122. UserComment,
  1123. ReportedTime
  1124. FROM reportsv2
  1125. WHERE TorrentID = $TorrentID
  1126. AND Status != 'Resolved'");
  1127. $Reports = G::$DB->to_array(false, MYSQLI_ASSOC, false);
  1128. G::$DB->set_query_id($QueryID);
  1129. G::$Cache->cache_value("reports_torrent_$TorrentID", $Reports, 0);
  1130. }
  1131. if (!check_perms('admin_reports')) {
  1132. $Return = array();
  1133. foreach ($Reports as $Report) {
  1134. if ($Report['Type'] !== 'edited') {
  1135. $Return[] = $Report;
  1136. }
  1137. }
  1138. return $Return;
  1139. }
  1140. return $Reports;
  1141. }
  1142. }
  1143. ?>