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

torrents.class.php 43KB

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