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

torrentsearch.class.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. <?
  2. class TorrentSearch {
  3. const TAGS_ANY = 0;
  4. const TAGS_ALL = 1;
  5. const SPH_BOOL_AND = ' ';
  6. const SPH_BOOL_OR = ' | ';
  7. // Map of sort mode => attribute name for ungrouped torrent page
  8. public static $SortOrders = array(
  9. 'year' => 'year',
  10. 'time' => 'id',
  11. 'size' => 'size',
  12. 'seeders' => 'seeders',
  13. 'leechers' => 'leechers',
  14. 'snatched' => 'snatched',
  15. 'random' => 1);
  16. // Map of sort mode => attribute name for grouped torrent page
  17. private static $SortOrdersGrouped = array(
  18. 'year' => 'year',
  19. 'time' => 'id',
  20. 'size' => 'maxsize',
  21. 'seeders' => 'sumseeders',
  22. 'leechers' => 'sumleechers',
  23. 'snatched' => 'sumsnatched',
  24. 'random' => 1);
  25. // Map of sort mode => aggregate expression required for some grouped sort orders
  26. private static $AggregateExp = array(
  27. 'size' => 'MAX(size) AS maxsize',
  28. 'seeders' => 'SUM(seeders) AS sumseeders',
  29. 'leechers' => 'SUM(leechers) AS sumleechers',
  30. 'snatched' => 'SUM(snatched) AS sumsnatched');
  31. // Map of attribute name => global variable name with list of values that can be used for filtering
  32. private static $Attributes = array(
  33. 'filter_cat' => false,
  34. 'releasetype' => 'ReleaseTypes',
  35. 'freetorrent' => false,
  36. 'censored' => false,
  37. 'year' => false);
  38. // List of fields that can be used for fulltext searches
  39. private static $Fields = array(
  40. 'artistname' => 1,
  41. 'audioformat' => 1,
  42. 'cataloguenumber' => 1,
  43. 'codec' => 1,
  44. 'container' => 1,
  45. 'description' => 1,
  46. 'dlsiteid' => 1,
  47. 'filelist' => 1,
  48. 'groupname' => 1,
  49. 'groupnamejp' => 1,
  50. 'language' => 1,
  51. 'media' => 1,
  52. 'resolution' => 1,
  53. 'searchstr' => 1,
  54. 'series' => 1,
  55. 'studio' => 1,
  56. 'subber' => 1,
  57. 'subbing' => 1,
  58. 'taglist' => 1);
  59. // List of torrent-specific fields that can be used for filtering
  60. private static $TorrentFields = array(
  61. 'description' => 1,
  62. 'encoding' => 1,
  63. 'censored' => 1,
  64. 'language' => 1,
  65. 'filelist' => 1,
  66. 'format' => 1,
  67. 'media' => 1);
  68. // Some form field names don't match the ones in the index
  69. private static $FormsToFields = array(
  70. 'searchstr' => '(groupname,groupnamejp,artistname,studio,series,dlsiteid,cataloguenumber,yearfulltext)');
  71. // Specify the operator type to use for fields. Empty key sets the default
  72. private static $FieldOperators = array(
  73. '' => self::SPH_BOOL_AND,
  74. 'encoding' => self::SPH_BOOL_OR,
  75. 'format' => self::SPH_BOOL_OR,
  76. 'media' => self::SPH_BOOL_OR);
  77. // Specify the separator character to use for fields. Empty key sets the default
  78. private static $FieldSeparators = array(
  79. '' => ' ',
  80. 'encoding' => '|',
  81. 'format' => '|',
  82. 'media' => '|',
  83. 'taglist' => ',');
  84. // Primary SphinxqlQuery object used to get group IDs or torrent IDs for ungrouped searches
  85. private $SphQL;
  86. // Second SphinxqlQuery object used to get torrent IDs if torrent-specific fulltext filters are used
  87. private $SphQLTor;
  88. // Ordered result array or false if query resulted in an error
  89. private $SphResults;
  90. // Requested page
  91. private $Page;
  92. // Number of results per page
  93. private $PageSize;
  94. // Number of results
  95. private $NumResults = 0;
  96. // Array with info from all matching torrent groups
  97. private $Groups = array();
  98. // Whether any filters were used
  99. private $Filtered = false;
  100. // Whether the random sort order is selected
  101. private $Random = false;
  102. /*
  103. * Storage for fulltext search terms
  104. * ['Field name' => [
  105. * 'include' => [],
  106. * 'exclude' => [],
  107. * 'operator' => self::SPH_BOOL_AND | self::SPH_BOOL_OR
  108. * ]], ...
  109. */
  110. private $Terms = array();
  111. // Unprocessed search terms for retrieval
  112. private $RawTerms = array();
  113. // Storage for used torrent-specific attribute filters
  114. // ['Field name' => 'Search expression', ...]
  115. private $UsedTorrentAttrs = array();
  116. // Storage for used torrent-specific fulltext fields
  117. // ['Field name' => 'Search expression', ...]
  118. private $UsedTorrentFields = array();
  119. /**
  120. * Initialize and configure a TorrentSearch object
  121. *
  122. * @param bool $GroupResults whether results should be grouped by group id
  123. * @param string $OrderBy attribute to use for sorting the results
  124. * @param string $OrderWay Whether to use ascending or descending order
  125. * @param int $Page Page number to display
  126. * @param int $PageSize Number of results per page
  127. */
  128. public function __construct($GroupResults, $OrderBy, $OrderWay, $Page, $PageSize) {
  129. if ($GroupResults && !isset(self::$SortOrdersGrouped[$OrderBy])
  130. || !$GroupResults && !isset(self::$SortOrders[$OrderBy])
  131. || !in_array($OrderWay, array('asc', 'desc'))
  132. ) {
  133. global $Debug;
  134. $ErrMsg = "TorrentSearch constructor arguments:\n" . print_r(func_get_args(), true);
  135. $Debug->analysis('Bad arguments in TorrentSearch constructor', $ErrMsg, 3600*24);
  136. error('-1');
  137. }
  138. if (!is_number($Page) || $Page < 1) {
  139. $Page = 1;
  140. }
  141. if (check_perms('site_search_many')) {
  142. $this->Page = $Page;
  143. } else {
  144. $this->Page = min($Page, SPHINX_MAX_MATCHES / $PageSize);
  145. }
  146. $ResultLimit = $PageSize;
  147. $this->PageSize = $PageSize;
  148. $this->GroupResults = $GroupResults;
  149. $this->SphQL = new SphinxqlQuery();
  150. $this->SphQL->where_match('_all', 'fake', false);
  151. if ($OrderBy === 'random') {
  152. $this->SphQL->select('id, groupid')
  153. ->order_by('RAND()', '');
  154. $this->Random = true;
  155. $this->Page = 1;
  156. if ($GroupResults) {
  157. // Get more results because ORDER BY RAND() can't be used in GROUP BY queries
  158. $ResultLimit *= 5;
  159. }
  160. } elseif ($GroupResults) {
  161. $Select = 'groupid';
  162. if (isset(self::$AggregateExp[$OrderBy])) {
  163. $Select .= ', ' . self::$AggregateExp[$OrderBy];
  164. }
  165. $this->SphQL->select($Select)
  166. ->group_by('groupid')
  167. ->order_group_by(self::$SortOrdersGrouped[$OrderBy], $OrderWay)
  168. ->order_by(self::$SortOrdersGrouped[$OrderBy], $OrderWay);
  169. } else {
  170. $this->SphQL->select('id, groupid')
  171. ->order_by(self::$SortOrders[$OrderBy], $OrderWay);
  172. }
  173. $Offset = ($this->Page - 1) * $ResultLimit;
  174. $MaxMatches = max($Offset + $ResultLimit, 1500);
  175. $this->SphQL->from('torrents, delta')
  176. ->limit($Offset, $ResultLimit, $MaxMatches);
  177. }
  178. /**
  179. * Process search terms and run the main query
  180. *
  181. * @param array $Terms Array containing all search terms (e.g. $_GET)
  182. * @return array List of matching group IDs with torrent ID as key for ungrouped results
  183. */
  184. public function query($Terms = array()) {
  185. $this->process_search_terms($Terms);
  186. $this->build_query();
  187. $this->run_query();
  188. $this->process_results();
  189. return $this->SphResults;
  190. }
  191. public function insert_hidden_tags($tags) {
  192. $this->SphQL->where_match($tags, 'taglist', false);
  193. }
  194. /**
  195. * Internal function that runs the queries needed to get the desired results
  196. */
  197. private function run_query() {
  198. $SphQLResult = $this->SphQL->query();
  199. if ($SphQLResult->Errno > 0) {
  200. $this->SphResults = false;
  201. return;
  202. }
  203. if ($this->Random && $this->GroupResults) {
  204. $TotalCount = $SphQLResult->get_meta('total_found');
  205. $this->SphResults = $SphQLResult->collect('groupid');
  206. $GroupIDs = array_keys($this->SphResults);
  207. $GroupCount = count($GroupIDs);
  208. while ($SphQLResult->get_meta('total') < $TotalCount && $GroupCount < $this->PageSize) {
  209. // Make sure we get $PageSize results, or all of them if there are less than $PageSize hits
  210. $this->SphQL->where('groupid', $GroupIDs, true);
  211. $SphQLResult = $this->SphQL->query();
  212. if (!$SphQLResult->has_results()) {
  213. break;
  214. }
  215. $this->SphResults += $SphQLResult->collect('groupid');
  216. $GroupIDs = array_keys($this->SphResults);
  217. $GroupCount = count($GroupIDs);
  218. }
  219. if ($GroupCount > $this->PageSize) {
  220. $this->SphResults = array_slice($this->SphResults, 0, $this->PageSize, true);
  221. }
  222. $this->NumResults = count($this->SphResults);
  223. } else {
  224. $this->NumResults = (int)$SphQLResult->get_meta('total_found');
  225. if ($this->GroupResults) {
  226. $this->SphResults = $SphQLResult->collect('groupid');
  227. } else {
  228. $this->SphResults = $SphQLResult->to_pair('id', 'groupid');
  229. }
  230. }
  231. }
  232. /**
  233. * Process search terms and store the parts in appropriate arrays until we know if
  234. * the NOT operator can be used
  235. */
  236. private function build_query() {
  237. foreach ($this->Terms as $Field => $Words) {
  238. $SearchString = '';
  239. if (isset(self::$FormsToFields[$Field])) {
  240. $Field = self::$FormsToFields[$Field];
  241. }
  242. $QueryParts = array('include' => array(), 'exclude' => array());
  243. if (!empty($Words['include'])) {
  244. foreach ($Words['include'] as $Word) {
  245. $QueryParts['include'][] = Sphinxql::sph_escape_string($Word);
  246. }
  247. }
  248. if (!empty($Words['exclude'])) {
  249. foreach ($Words['exclude'] as $Word) {
  250. $QueryParts['exclude'][] = '!' . Sphinxql::sph_escape_string(substr($Word, 1));
  251. }
  252. }
  253. if (!empty($QueryParts)) {
  254. if (isset($Words['operator'])) {
  255. // Is the operator already specified?
  256. $Operator = $Words['operator'];
  257. } elseif(isset(self::$FieldOperators[$Field])) {
  258. // Does this field have a non-standard operator?
  259. $Operator = self::$FieldOperators[$Field];
  260. } else {
  261. // Go for the default operator
  262. $Operator = self::$FieldOperators[''];
  263. }
  264. if (!empty($QueryParts['include'])) {
  265. $SearchString .= '( ' . implode($Operator, $QueryParts['include']) . ' ) ';
  266. }
  267. if (!empty($QueryParts['exclude'])) {
  268. $SearchString .= implode(' ', $QueryParts['exclude']);
  269. }
  270. $this->SphQL->where_match($SearchString, $Field, false);
  271. if (isset(self::$TorrentFields[$Field])) {
  272. $this->UsedTorrentFields[$Field] = $SearchString;
  273. }
  274. $this->Filtered = true;
  275. }
  276. }
  277. }
  278. /**
  279. * Look at each search term and figure out what to do with it
  280. *
  281. * @param array $Terms Array with search terms from query()
  282. */
  283. private function process_search_terms($Terms) {
  284. foreach ($Terms as $Key => $Term) {
  285. if (isset(self::$Fields[$Key])) {
  286. $this->process_field($Key, $Term);
  287. } elseif (isset(self::$Attributes[$Key])) {
  288. $this->process_attribute($Key, $Term);
  289. }
  290. $this->RawTerms[$Key] = $Term;
  291. }
  292. $this->post_process_fields();
  293. }
  294. /**
  295. * Process attribute filters and store them in case we need to post-process grouped results
  296. *
  297. * @param string $Attribute Name of the attribute to filter against
  298. * @param mixed $Value The filter's condition for a match
  299. */
  300. private function process_attribute($Attribute, $Value) {
  301. if ($Value === '') {
  302. return;
  303. }
  304. switch ($Attribute) {
  305. case 'year':
  306. if (!$this->search_year($Value)) {
  307. return;
  308. }
  309. break;
  310. case 'freetorrent':
  311. if ($Value == 3) {
  312. $this->SphQL->where('freetorrent', 0, true);
  313. $this->UsedTorrentAttrs['freetorrent'] = 3;
  314. } elseif ($Value >= 0 && $Value < 3) {
  315. $this->SphQL->where('freetorrent', $Value);
  316. $this->UsedTorrentAttrs[$Attribute] = $Value;
  317. } else {
  318. return;
  319. }
  320. break;
  321. case 'filter_cat':
  322. if (!is_array($Value)) {
  323. $Value = array_fill_keys(explode('|', $Value), 1);
  324. }
  325. $CategoryFilter = array();
  326. foreach (array_keys($Value) as $Category) {
  327. if (is_number($Category)) {
  328. $CategoryFilter[] = $Category;
  329. } else {
  330. global $Categories;
  331. $ValidValues = array_map('strtolower', $Categories);
  332. if (($CategoryID = array_search(strtolower($Category), $ValidValues)) !== false) {
  333. $CategoryFilter[] = $CategoryID + 1;
  334. }
  335. }
  336. }
  337. if (empty($CategoryFilter)) {
  338. $CategoryFilter = 0;
  339. }
  340. $this->SphQL->where('categoryid', $CategoryFilter);
  341. break;
  342. default:
  343. if (!is_number($Value) && self::$Attributes[$Attribute] !== false) {
  344. // Check if the submitted value can be converted to a valid one
  345. $ValidValuesVarname = self::$Attributes[$Attribute];
  346. global $$ValidValuesVarname;
  347. $ValidValues = array_map('strtolower', $$ValidValuesVarname);
  348. if (($Value = array_search(strtolower($Value), $ValidValues)) === false) {
  349. // Force the query to return 0 results if value is still invalid
  350. $Value = max(array_keys($ValidValues)) + 1;
  351. }
  352. }
  353. $this->SphQL->where($Attribute, $Value);
  354. $this->UsedTorrentAttrs[$Attribute] = $Value;
  355. break;
  356. }
  357. $this->Filtered = true;
  358. }
  359. /**
  360. * Look at a fulltext search term and figure out if it needs special treatment
  361. *
  362. * @param string $Field Name of the search field
  363. * @param string $Term Search expression for the field
  364. */
  365. private function process_field($Field, $Term) {
  366. $Term = trim($Term);
  367. if ($Term === '') {
  368. return;
  369. }
  370. if ($Field === 'searchstr') {
  371. $this->search_basic($Term);
  372. } elseif ($Field === 'filelist') {
  373. $this->search_filelist($Term);
  374. } elseif ($Field === 'taglist') {
  375. $this->search_taglist($Term);
  376. } else {
  377. $this->add_field($Field, $Term);
  378. }
  379. }
  380. /**
  381. * Some fields may require post-processing
  382. */
  383. private function post_process_fields() {
  384. if (isset($this->Terms['taglist'])) {
  385. // Replace bad tags with tag aliases
  386. $this->Terms['taglist'] = Tags::remove_aliases($this->Terms['taglist']);
  387. if (isset($this->RawTerms['tags_type']) && (int)$this->RawTerms['tags_type'] === self::TAGS_ANY) {
  388. $this->Terms['taglist']['operator'] = self::SPH_BOOL_OR;
  389. }
  390. // Update the RawTerms array so get_terms() can return the corrected search terms
  391. if (isset($this->Terms['taglist']['include'])) {
  392. $AllTags = $this->Terms['taglist']['include'];
  393. } else {
  394. $AllTags = array();
  395. }
  396. if (isset($this->Terms['taglist']['exclude'])) {
  397. $AllTags = array_merge($AllTags, $this->Terms['taglist']['exclude']);
  398. }
  399. $this->RawTerms['taglist'] = str_replace('_', '.', implode(', ', $AllTags));
  400. }
  401. }
  402. /**
  403. * Handle magic keywords in the basic torrent search
  404. *
  405. * @param string $Term Given search expression
  406. */
  407. private function search_basic($Term) {
  408. global $Bitrates, $Formats, $Media;
  409. $SearchBitrates = array_map('strtolower', $Bitrates);
  410. array_push($SearchBitrates, 'v0', 'v1', 'v2', '24bit');
  411. $SearchFormats = array_map('strtolower', $Formats);
  412. $SearchMedia = array_map('strtolower', $Media);
  413. foreach (explode(' ', $Term) as $Word) {
  414. if (in_array($Word, $SearchBitrates)) {
  415. $this->add_word('encoding', $Word);
  416. } elseif (in_array($Word, $SearchFormats)) {
  417. $this->add_word('format', $Word);
  418. } elseif (in_array($Word, $SearchMedia)) {
  419. $this->add_word('media', $Word);
  420. } else {
  421. $this->add_word('searchstr', $Word);
  422. }
  423. }
  424. }
  425. /**
  426. * Use phrase boundary for file searches to make sure we don't count
  427. * partial hits from multiple files
  428. *
  429. * @param string $Term Given search expression
  430. */
  431. private function search_filelist($Term) {
  432. $SearchString = '"' . Sphinxql::sph_escape_string($Term) . '"~20';
  433. $this->SphQL->where_match($SearchString, 'filelist', false);
  434. $this->UsedTorrentFields['filelist'] = $SearchString;
  435. $this->Filtered = true;
  436. }
  437. /**
  438. * Prepare tag searches before sending them to the normal treatment
  439. *
  440. * @param string $Term Given search expression
  441. */
  442. private function search_taglist($Term) {
  443. $Term = strtr($Term, '.', '_');
  444. $this->add_field('taglist', $Term);
  445. }
  446. /**
  447. * The year filter accepts a range. Figure out how to handle the filter value
  448. *
  449. * @param string $Term Filter condition. Can be an integer or a range with the format X-Y
  450. * @return bool True if parameters are valid
  451. */
  452. private function search_year($Term) {
  453. $Years = explode('-', $Term);
  454. if (count($Years) === 1 && is_number($Years[0])) {
  455. // Exact year
  456. $this->SphQL->where('year', $Years[0]);
  457. } elseif (count($Years) === 2) {
  458. if (empty($Years[0]) && is_number($Years[1])) {
  459. // Range: 0 - 2005
  460. $this->SphQL->where_lt('year', $Years[1], true);
  461. } elseif (empty($Years[1]) && is_number($Years[0])) {
  462. // Range: 2005 - 2^32-1
  463. $this->SphQL->where_gt('year', $Years[0], true);
  464. } elseif (is_number($Years[0]) && is_number($Years[1])) {
  465. // Range: 2005 - 2009
  466. $this->SphQL->where_between('year', array(min($Years), max($Years)));
  467. } else {
  468. // Invalid input
  469. return false;
  470. }
  471. } else {
  472. // Invalid input
  473. return false;
  474. }
  475. return true;
  476. }
  477. /**
  478. * Add a field filter that doesn't need special treatment
  479. *
  480. * @param string $Field Name of the search field
  481. * @param string $Term Search expression for the field
  482. */
  483. private function add_field($Field, $Term) {
  484. if (isset(self::$FieldSeparators[$Field])) {
  485. $Separator = self::$FieldSeparators[$Field];
  486. } else {
  487. $Separator = self::$FieldSeparators[''];
  488. }
  489. $Words = explode($Separator, $Term);
  490. foreach ($Words as $Word) {
  491. $this->add_word($Field, $Word);
  492. }
  493. }
  494. /**
  495. * Add a keyword to the array of search terms
  496. *
  497. * @param string $Field Name of the search field
  498. * @param string $Word Keyword
  499. */
  500. private function add_word($Field, $Word) {
  501. $Word = trim($Word);
  502. // Skip isolated hyphens to enable "Artist - Title" searches
  503. if ($Word === '' || $Word === '-') {
  504. return;
  505. }
  506. if ($Word[0] === '!' && strlen($Word) >= 2 && strpos($Word, '!', 1) === false) {
  507. $this->Terms[$Field]['exclude'][] = $Word;
  508. } else {
  509. $this->Terms[$Field]['include'][] = $Word;
  510. }
  511. }
  512. /**
  513. * @return array Torrent group information for the matches from Torrents::get_groups
  514. */
  515. public function get_groups() {
  516. return $this->Groups;
  517. }
  518. /**
  519. * @param string $Type Field or attribute name
  520. * @return string Unprocessed search terms
  521. */
  522. public function get_terms($Type) {
  523. return $this->RawTerms[$Type] ?? '';
  524. }
  525. /**
  526. * @return int Result count
  527. */
  528. public function record_count() {
  529. return $this->NumResults;
  530. }
  531. /**
  532. * @return bool Whether any filters were used
  533. */
  534. public function has_filters() {
  535. return $this->Filtered;
  536. }
  537. /**
  538. * @return bool Whether any torrent-specific fulltext filters were used
  539. */
  540. public function need_torrent_ft() {
  541. return $this->GroupResults && $this->NumResults > 0 && !empty($this->UsedTorrentFields);
  542. }
  543. /**
  544. * Get torrent group info and remove any torrents that don't match
  545. */
  546. private function process_results() {
  547. if (count($this->SphResults) == 0) {
  548. return;
  549. }
  550. $this->Groups = Torrents::get_groups($this->SphResults);
  551. if ($this->need_torrent_ft()) {
  552. // Query Sphinx for torrent IDs if torrent-specific fulltext filters were used
  553. $this->filter_torrents_sph();
  554. } elseif ($this->GroupResults) {
  555. // Otherwise, let PHP discard unmatching torrents
  556. $this->filter_torrents_internal();
  557. }
  558. // Ungrouped searches don't need any additional filtering
  559. }
  560. /**
  561. * Build and run a query that gets torrent IDs from Sphinx when fulltext filters
  562. * were used to get primary results and they are grouped
  563. */
  564. private function filter_torrents_sph() {
  565. $AllTorrents = array();
  566. foreach ($this->Groups as $GroupID => $Group) {
  567. if (!empty($Group['Torrents'])) {
  568. $AllTorrents += array_fill_keys(array_keys($Group['Torrents']), $GroupID);
  569. }
  570. }
  571. $TorrentCount = count($AllTorrents);
  572. $this->SphQLTor = new SphinxqlQuery();
  573. $this->SphQLTor->select('id')->from('torrents, delta');
  574. foreach ($this->UsedTorrentFields as $Field => $Term) {
  575. $this->SphQLTor->where_match($Term, $Field, false);
  576. }
  577. $this->SphQLTor->copy_attributes_from($this->SphQL);
  578. $this->SphQLTor->where('id', array_keys($AllTorrents))->limit(0, $TorrentCount, $TorrentCount);
  579. $SphQLResultTor = $this->SphQLTor->query();
  580. $MatchingTorrentIDs = $SphQLResultTor->to_pair('id', 'id');
  581. foreach ($AllTorrents as $TorrentID => $GroupID) {
  582. if (!isset($MatchingTorrentIDs[$TorrentID])) {
  583. unset($this->Groups[$GroupID]['Torrents'][$TorrentID]);
  584. }
  585. }
  586. }
  587. /**
  588. * Non-Sphinx method of collecting IDs of torrents that match any
  589. * torrent-specific attribute filters that were used in the search query
  590. */
  591. private function filter_torrents_internal() {
  592. foreach ($this->Groups as $GroupID => $Group) {
  593. if (empty($Group['Torrents'])) {
  594. continue;
  595. }
  596. foreach ($Group['Torrents'] as $TorrentID => $Torrent) {
  597. if (!$this->filter_torrent_internal($Torrent)) {
  598. unset($this->Groups[$GroupID]['Torrents'][$TorrentID]);
  599. }
  600. }
  601. }
  602. }
  603. /**
  604. * Post-processing to determine if a torrent is a real hit or if it was
  605. * returned because another torrent in the group matched. Only used if
  606. * there are no torrent-specific fulltext conditions
  607. *
  608. * @param array $Torrent Torrent array, probably from Torrents::get_groups()
  609. * @return bool True if it's a real hit
  610. */
  611. private function filter_torrent_internal($Torrent) {
  612. if (isset($this->UsedTorrentAttrs['freetorrent'])) {
  613. $FilterValue = $this->UsedTorrentAttrs['freetorrent'];
  614. if ($FilterValue == '3' && $Torrent['FreeTorrent'] == '0') {
  615. // Either FL or NL is ok
  616. return false;
  617. } elseif ($FilterValue != '3' && $FilterValue != (int)$Torrent['FreeTorrent']) {
  618. return false;
  619. }
  620. }
  621. return true;
  622. }
  623. }