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

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