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

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