Contributing back some bug fixes
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

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