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

torrentsearch.class.php 25KB

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