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

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