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