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 25KB

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