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

torrents.class.php 50KB

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