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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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, SPHINX_MIN_MAX_MATCHES);
  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. if ($Field == 'taglist') {
  266. foreach ($QueryParts['include'] as $key => $Tag) {
  267. $QueryParts['include'][$key] = '( '.$Tag.' | '.$Tag.':* )';
  268. }
  269. }
  270. $SearchString .= '( ' . implode($Operator, $QueryParts['include']) . ' ) ';
  271. }
  272. if (!empty($QueryParts['exclude'])) {
  273. $SearchString .= implode(' ', $QueryParts['exclude']);
  274. }
  275. $this->SphQL->where_match($SearchString, $Field, false);
  276. if (isset(self::$TorrentFields[$Field])) {
  277. $this->UsedTorrentFields[$Field] = $SearchString;
  278. }
  279. $this->Filtered = true;
  280. }
  281. }
  282. }
  283. /**
  284. * Look at each search term and figure out what to do with it
  285. *
  286. * @param array $Terms Array with search terms from query()
  287. */
  288. private function process_search_terms($Terms) {
  289. foreach ($Terms as $Key => $Term) {
  290. if (isset(self::$Fields[$Key])) {
  291. $this->process_field($Key, $Term);
  292. } elseif (isset(self::$Attributes[$Key])) {
  293. $this->process_attribute($Key, $Term);
  294. }
  295. $this->RawTerms[$Key] = $Term;
  296. }
  297. $this->post_process_fields();
  298. }
  299. /**
  300. * Process attribute filters and store them in case we need to post-process grouped results
  301. *
  302. * @param string $Attribute Name of the attribute to filter against
  303. * @param mixed $Value The filter's condition for a match
  304. */
  305. private function process_attribute($Attribute, $Value) {
  306. if ($Value === '') {
  307. return;
  308. }
  309. switch ($Attribute) {
  310. case 'year':
  311. if (!$this->search_year($Value)) {
  312. return;
  313. }
  314. break;
  315. case 'freetorrent':
  316. if ($Value == 3) {
  317. $this->SphQL->where('freetorrent', 0, true);
  318. $this->UsedTorrentAttrs['freetorrent'] = 3;
  319. } elseif ($Value >= 0 && $Value < 3) {
  320. $this->SphQL->where('freetorrent', $Value);
  321. $this->UsedTorrentAttrs[$Attribute] = $Value;
  322. } else {
  323. return;
  324. }
  325. break;
  326. case 'filter_cat':
  327. if (!is_array($Value)) {
  328. $Value = array_fill_keys(explode('|', $Value), 1);
  329. }
  330. $CategoryFilter = array();
  331. foreach (array_keys($Value) as $Category) {
  332. if (is_number($Category)) {
  333. $CategoryFilter[] = $Category;
  334. } else {
  335. global $Categories;
  336. $ValidValues = array_map('strtolower', $Categories);
  337. if (($CategoryID = array_search(strtolower($Category), $ValidValues)) !== false) {
  338. $CategoryFilter[] = $CategoryID + 1;
  339. }
  340. }
  341. }
  342. if (empty($CategoryFilter)) {
  343. $CategoryFilter = 0;
  344. }
  345. $this->SphQL->where('categoryid', $CategoryFilter);
  346. break;
  347. default:
  348. if (!is_number($Value) && self::$Attributes[$Attribute] !== false) {
  349. // Check if the submitted value can be converted to a valid one
  350. $ValidValuesVarname = self::$Attributes[$Attribute];
  351. global $$ValidValuesVarname;
  352. $ValidValues = array_map('strtolower', $$ValidValuesVarname);
  353. if (($Value = array_search(strtolower($Value), $ValidValues)) === false) {
  354. // Force the query to return 0 results if value is still invalid
  355. $Value = max(array_keys($ValidValues)) + 1;
  356. }
  357. }
  358. $this->SphQL->where($Attribute, $Value);
  359. $this->UsedTorrentAttrs[$Attribute] = $Value;
  360. break;
  361. }
  362. $this->Filtered = true;
  363. }
  364. /**
  365. * Look at a fulltext search term and figure out if it needs special treatment
  366. *
  367. * @param string $Field Name of the search field
  368. * @param string $Term Search expression for the field
  369. */
  370. private function process_field($Field, $Term) {
  371. $Term = trim($Term);
  372. if ($Term === '') {
  373. return;
  374. }
  375. if ($Field === 'searchstr') {
  376. $this->search_basic($Term);
  377. } elseif ($Field === 'filelist') {
  378. $this->search_filelist($Term);
  379. } elseif ($Field === 'taglist') {
  380. $this->search_taglist($Term);
  381. } else {
  382. $this->add_field($Field, $Term);
  383. }
  384. }
  385. /**
  386. * Some fields may require post-processing
  387. */
  388. private function post_process_fields() {
  389. if (isset($this->Terms['taglist'])) {
  390. // Replace bad tags with tag aliases
  391. $this->Terms['taglist'] = Tags::remove_aliases($this->Terms['taglist']);
  392. if (isset($this->RawTerms['tags_type']) && (int)$this->RawTerms['tags_type'] === self::TAGS_ANY) {
  393. $this->Terms['taglist']['operator'] = self::SPH_BOOL_OR;
  394. }
  395. // Update the RawTerms array so get_terms() can return the corrected search terms
  396. if (isset($this->Terms['taglist']['include'])) {
  397. $AllTags = $this->Terms['taglist']['include'];
  398. } else {
  399. $AllTags = array();
  400. }
  401. if (isset($this->Terms['taglist']['exclude'])) {
  402. $AllTags = array_merge($AllTags, $this->Terms['taglist']['exclude']);
  403. }
  404. $this->RawTerms['taglist'] = str_replace('_', '.', implode(', ', $AllTags));
  405. }
  406. }
  407. /**
  408. * Handle magic keywords in the basic torrent search
  409. *
  410. * @param string $Term Given search expression
  411. */
  412. private function search_basic($Term) {
  413. global $Bitrates, $Formats, $Media;
  414. $SearchBitrates = array_map('strtolower', $Bitrates);
  415. array_push($SearchBitrates, 'v0', 'v1', 'v2', '24bit');
  416. $SearchFormats = array_map('strtolower', $Formats);
  417. $SearchMedia = array_map('strtolower', $Media);
  418. foreach (explode(' ', $Term) as $Word) {
  419. if (in_array($Word, $SearchBitrates)) {
  420. $this->add_word('encoding', $Word);
  421. } elseif (in_array($Word, $SearchFormats)) {
  422. $this->add_word('format', $Word);
  423. } elseif (in_array($Word, $SearchMedia)) {
  424. $this->add_word('media', $Word);
  425. } else {
  426. $this->add_word('searchstr', $Word);
  427. }
  428. }
  429. }
  430. /**
  431. * Use phrase boundary for file searches to make sure we don't count
  432. * partial hits from multiple files
  433. *
  434. * @param string $Term Given search expression
  435. */
  436. private function search_filelist($Term) {
  437. $SearchString = '"' . Sphinxql::sph_escape_string($Term) . '"~20';
  438. $this->SphQL->where_match($SearchString, 'filelist', false);
  439. $this->UsedTorrentFields['filelist'] = $SearchString;
  440. $this->Filtered = true;
  441. }
  442. /**
  443. * Prepare tag searches before sending them to the normal treatment
  444. *
  445. * @param string $Term Given search expression
  446. */
  447. private function search_taglist($Term) {
  448. $Term = strtr($Term, '.', '_');
  449. $this->add_field('taglist', $Term);
  450. }
  451. /**
  452. * The year filter accepts a range. Figure out how to handle the filter value
  453. *
  454. * @param string $Term Filter condition. Can be an integer or a range with the format X-Y
  455. * @return bool True if parameters are valid
  456. */
  457. private function search_year($Term) {
  458. $Years = explode('-', $Term);
  459. if (count($Years) === 1 && is_number($Years[0])) {
  460. // Exact year
  461. $this->SphQL->where('year', $Years[0]);
  462. } elseif (count($Years) === 2) {
  463. if (empty($Years[0]) && is_number($Years[1])) {
  464. // Range: 0 - 2005
  465. $this->SphQL->where_lt('year', $Years[1], true);
  466. } elseif (empty($Years[1]) && is_number($Years[0])) {
  467. // Range: 2005 - 2^32-1
  468. $this->SphQL->where_gt('year', $Years[0], true);
  469. } elseif (is_number($Years[0]) && is_number($Years[1])) {
  470. // Range: 2005 - 2009
  471. $this->SphQL->where_between('year', array(min($Years), max($Years)));
  472. } else {
  473. // Invalid input
  474. return false;
  475. }
  476. } else {
  477. // Invalid input
  478. return false;
  479. }
  480. return true;
  481. }
  482. /**
  483. * Add a field filter that doesn't need special treatment
  484. *
  485. * @param string $Field Name of the search field
  486. * @param string $Term Search expression for the field
  487. */
  488. private function add_field($Field, $Term) {
  489. if (isset(self::$FieldSeparators[$Field])) {
  490. $Separator = self::$FieldSeparators[$Field];
  491. } else {
  492. $Separator = self::$FieldSeparators[''];
  493. }
  494. $Words = explode($Separator, $Term);
  495. foreach ($Words as $Word) {
  496. $this->add_word($Field, $Word);
  497. }
  498. }
  499. /**
  500. * Add a keyword to the array of search terms
  501. *
  502. * @param string $Field Name of the search field
  503. * @param string $Word Keyword
  504. */
  505. private function add_word($Field, $Word) {
  506. $Word = trim($Word);
  507. // Skip isolated hyphens to enable "Artist - Title" searches
  508. if ($Word === '' || $Word === '-') {
  509. return;
  510. }
  511. if ($Word[0] === '!' && strlen($Word) >= 2 && strpos($Word, '!', 1) === false) {
  512. $this->Terms[$Field]['exclude'][] = $Word;
  513. } else {
  514. $this->Terms[$Field]['include'][] = $Word;
  515. }
  516. }
  517. /**
  518. * @return array Torrent group information for the matches from Torrents::get_groups
  519. */
  520. public function get_groups() {
  521. return $this->Groups;
  522. }
  523. /**
  524. * @param string $Type Field or attribute name
  525. * @return string Unprocessed search terms
  526. */
  527. public function get_terms($Type) {
  528. return $this->RawTerms[$Type] ?? '';
  529. }
  530. /**
  531. * @return int Result count
  532. */
  533. public function record_count() {
  534. return $this->NumResults;
  535. }
  536. /**
  537. * @return bool Whether any filters were used
  538. */
  539. public function has_filters() {
  540. return $this->Filtered;
  541. }
  542. /**
  543. * @return bool Whether any torrent-specific fulltext filters were used
  544. */
  545. public function need_torrent_ft() {
  546. return $this->GroupResults && $this->NumResults > 0 && !empty($this->UsedTorrentFields);
  547. }
  548. /**
  549. * Get torrent group info and remove any torrents that don't match
  550. */
  551. private function process_results() {
  552. if (count($this->SphResults) == 0) {
  553. return;
  554. }
  555. $this->Groups = Torrents::get_groups($this->SphResults);
  556. if ($this->need_torrent_ft()) {
  557. // Query Sphinx for torrent IDs if torrent-specific fulltext filters were used
  558. $this->filter_torrents_sph();
  559. } elseif ($this->GroupResults) {
  560. // Otherwise, let PHP discard unmatching torrents
  561. $this->filter_torrents_internal();
  562. }
  563. // Ungrouped searches don't need any additional filtering
  564. }
  565. /**
  566. * Build and run a query that gets torrent IDs from Sphinx when fulltext filters
  567. * were used to get primary results and they are grouped
  568. */
  569. private function filter_torrents_sph() {
  570. $AllTorrents = array();
  571. foreach ($this->Groups as $GroupID => $Group) {
  572. if (!empty($Group['Torrents'])) {
  573. $AllTorrents += array_fill_keys(array_keys($Group['Torrents']), $GroupID);
  574. }
  575. }
  576. $TorrentCount = count($AllTorrents);
  577. $this->SphQLTor = new SphinxqlQuery();
  578. $this->SphQLTor->select('id')->from('torrents, delta');
  579. foreach ($this->UsedTorrentFields as $Field => $Term) {
  580. $this->SphQLTor->where_match($Term, $Field, false);
  581. }
  582. $this->SphQLTor->copy_attributes_from($this->SphQL);
  583. $this->SphQLTor->where('id', array_keys($AllTorrents))->limit(0, $TorrentCount, $TorrentCount);
  584. $SphQLResultTor = $this->SphQLTor->query();
  585. $MatchingTorrentIDs = $SphQLResultTor->to_pair('id', 'id');
  586. foreach ($AllTorrents as $TorrentID => $GroupID) {
  587. if (!isset($MatchingTorrentIDs[$TorrentID])) {
  588. unset($this->Groups[$GroupID]['Torrents'][$TorrentID]);
  589. }
  590. }
  591. }
  592. /**
  593. * Non-Sphinx method of collecting IDs of torrents that match any
  594. * torrent-specific attribute filters that were used in the search query
  595. */
  596. private function filter_torrents_internal() {
  597. foreach ($this->Groups as $GroupID => $Group) {
  598. if (empty($Group['Torrents'])) {
  599. continue;
  600. }
  601. foreach ($Group['Torrents'] as $TorrentID => $Torrent) {
  602. if (!$this->filter_torrent_internal($Torrent)) {
  603. unset($this->Groups[$GroupID]['Torrents'][$TorrentID]);
  604. }
  605. }
  606. }
  607. }
  608. /**
  609. * Post-processing to determine if a torrent is a real hit or if it was
  610. * returned because another torrent in the group matched. Only used if
  611. * there are no torrent-specific fulltext conditions
  612. *
  613. * @param array $Torrent Torrent array, probably from Torrents::get_groups()
  614. * @return bool True if it's a real hit
  615. */
  616. private function filter_torrent_internal($Torrent) {
  617. if (isset($this->UsedTorrentAttrs['freetorrent'])) {
  618. $FilterValue = $this->UsedTorrentAttrs['freetorrent'];
  619. if ($FilterValue == '3' && $Torrent['FreeTorrent'] == '0') {
  620. // Either FL or NL is ok
  621. return false;
  622. } elseif ($FilterValue != '3' && $FilterValue != (int)$Torrent['FreeTorrent']) {
  623. return false;
  624. }
  625. }
  626. return true;
  627. }
  628. }