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

torrents.class.php 43KB

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