PrefixSearch.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. /**
  3. * Prefix search of page names.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. /**
  23. * Handles searching prefixes of titles and finding any page
  24. * names that match. Used largely by the OpenSearch implementation.
  25. * @deprecated Since 1.27, Use SearchEngine::defaultPrefixSearch or SearchEngine::completionSearch
  26. *
  27. * @ingroup Search
  28. */
  29. abstract class PrefixSearch {
  30. /**
  31. * Do a prefix search of titles and return a list of matching page names.
  32. * @deprecated Since 1.23, use TitlePrefixSearch or StringPrefixSearch classes
  33. *
  34. * @param string $search
  35. * @param int $limit
  36. * @param array $namespaces Used if query is not explicitly prefixed
  37. * @param int $offset How many results to offset from the beginning
  38. * @return array Array of strings
  39. */
  40. public static function titleSearch( $search, $limit, $namespaces = [], $offset = 0 ) {
  41. $prefixSearch = new StringPrefixSearch;
  42. return $prefixSearch->search( $search, $limit, $namespaces, $offset );
  43. }
  44. /**
  45. * Do a prefix search of titles and return a list of matching page names.
  46. *
  47. * @param string $search
  48. * @param int $limit
  49. * @param array $namespaces Used if query is not explicitly prefixed
  50. * @param int $offset How many results to offset from the beginning
  51. * @return array Array of strings or Title objects
  52. */
  53. public function search( $search, $limit, $namespaces = [], $offset = 0 ) {
  54. $search = trim( $search );
  55. if ( $search == '' ) {
  56. return []; // Return empty result
  57. }
  58. $hasNamespace = $this->extractNamespace( $search );
  59. if ( $hasNamespace ) {
  60. list( $namespace, $search ) = $hasNamespace;
  61. $namespaces = [ $namespace ];
  62. } else {
  63. $namespaces = $this->validateNamespaces( $namespaces );
  64. Hooks::run( 'PrefixSearchExtractNamespace', [ &$namespaces, &$search ] );
  65. }
  66. return $this->searchBackend( $namespaces, $search, $limit, $offset );
  67. }
  68. /**
  69. * Figure out if given input contains an explicit namespace.
  70. *
  71. * @param string $input
  72. * @return false|array Array of namespace and remaining text, or false if no namespace given.
  73. */
  74. protected function extractNamespace( $input ) {
  75. if ( strpos( $input, ':' ) === false ) {
  76. return false;
  77. }
  78. // Namespace prefix only
  79. $title = Title::newFromText( $input . 'Dummy' );
  80. if (
  81. $title &&
  82. $title->getText() === 'Dummy' &&
  83. !$title->inNamespace( NS_MAIN ) &&
  84. !$title->isExternal()
  85. ) {
  86. return [ $title->getNamespace(), '' ];
  87. }
  88. // Namespace prefix with additional input
  89. $title = Title::newFromText( $input );
  90. if (
  91. $title &&
  92. !$title->inNamespace( NS_MAIN ) &&
  93. !$title->isExternal()
  94. ) {
  95. // getText provides correct capitalization
  96. return [ $title->getNamespace(), $title->getText() ];
  97. }
  98. return false;
  99. }
  100. /**
  101. * Do a prefix search for all possible variants of the prefix
  102. * @param string $search
  103. * @param int $limit
  104. * @param array $namespaces
  105. * @param int $offset How many results to offset from the beginning
  106. *
  107. * @return array
  108. */
  109. public function searchWithVariants( $search, $limit, array $namespaces, $offset = 0 ) {
  110. $searches = $this->search( $search, $limit, $namespaces, $offset );
  111. // if the content language has variants, try to retrieve fallback results
  112. $fallbackLimit = $limit - count( $searches );
  113. if ( $fallbackLimit > 0 ) {
  114. global $wgContLang;
  115. $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
  116. $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
  117. foreach ( $fallbackSearches as $fbs ) {
  118. $fallbackSearchResult = $this->search( $fbs, $fallbackLimit, $namespaces );
  119. $searches = array_merge( $searches, $fallbackSearchResult );
  120. $fallbackLimit -= count( $fallbackSearchResult );
  121. if ( $fallbackLimit == 0 ) {
  122. break;
  123. }
  124. }
  125. }
  126. return $searches;
  127. }
  128. /**
  129. * When implemented in a descendant class, receives an array of Title objects and returns
  130. * either an unmodified array or an array of strings corresponding to titles passed to it.
  131. *
  132. * @param array $titles
  133. * @return array
  134. */
  135. abstract protected function titles( array $titles );
  136. /**
  137. * When implemented in a descendant class, receives an array of titles as strings and returns
  138. * either an unmodified array or an array of Title objects corresponding to strings received.
  139. *
  140. * @param array $strings
  141. *
  142. * @return array
  143. */
  144. abstract protected function strings( array $strings );
  145. /**
  146. * Do a prefix search of titles and return a list of matching page names.
  147. * @param array $namespaces
  148. * @param string $search
  149. * @param int $limit
  150. * @param int $offset How many results to offset from the beginning
  151. * @return array Array of strings
  152. */
  153. protected function searchBackend( $namespaces, $search, $limit, $offset ) {
  154. if ( count( $namespaces ) == 1 ) {
  155. $ns = $namespaces[0];
  156. if ( $ns == NS_MEDIA ) {
  157. $namespaces = [ NS_FILE ];
  158. } elseif ( $ns == NS_SPECIAL ) {
  159. return $this->titles( $this->specialSearch( $search, $limit, $offset ) );
  160. }
  161. }
  162. $srchres = [];
  163. if ( Hooks::run(
  164. 'PrefixSearchBackend',
  165. [ $namespaces, $search, $limit, &$srchres, $offset ]
  166. ) ) {
  167. return $this->titles( $this->defaultSearchBackend( $namespaces, $search, $limit, $offset ) );
  168. }
  169. return $this->strings(
  170. $this->handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) );
  171. }
  172. private function handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) {
  173. if ( $offset === 0 ) {
  174. // Only perform exact db match if offset === 0
  175. // This is still far from perfect but at least we avoid returning the
  176. // same title afain and again when the user is scrolling with a query
  177. // that matches a title in the db.
  178. $rescorer = new SearchExactMatchRescorer();
  179. $srchres = $rescorer->rescore( $search, $namespaces, $srchres, $limit );
  180. }
  181. return $srchres;
  182. }
  183. /**
  184. * Prefix search special-case for Special: namespace.
  185. *
  186. * @param string $search Term
  187. * @param int $limit Max number of items to return
  188. * @param int $offset Number of items to offset
  189. * @return array
  190. */
  191. protected function specialSearch( $search, $limit, $offset ) {
  192. global $wgContLang;
  193. $searchParts = explode( '/', $search, 2 );
  194. $searchKey = $searchParts[0];
  195. $subpageSearch = isset( $searchParts[1] ) ? $searchParts[1] : null;
  196. // Handle subpage search separately.
  197. if ( $subpageSearch !== null ) {
  198. // Try matching the full search string as a page name
  199. $specialTitle = Title::makeTitleSafe( NS_SPECIAL, $searchKey );
  200. if ( !$specialTitle ) {
  201. return [];
  202. }
  203. $special = SpecialPageFactory::getPage( $specialTitle->getText() );
  204. if ( $special ) {
  205. $subpages = $special->prefixSearchSubpages( $subpageSearch, $limit, $offset );
  206. return array_map( function ( $sub ) use ( $specialTitle ) {
  207. return $specialTitle->getSubpage( $sub );
  208. }, $subpages );
  209. } else {
  210. return [];
  211. }
  212. }
  213. # normalize searchKey, so aliases with spaces can be found - T27675
  214. $searchKey = str_replace( ' ', '_', $searchKey );
  215. $searchKey = $wgContLang->caseFold( $searchKey );
  216. // Unlike SpecialPage itself, we want the canonical forms of both
  217. // canonical and alias title forms...
  218. $keys = [];
  219. foreach ( SpecialPageFactory::getNames() as $page ) {
  220. $keys[$wgContLang->caseFold( $page )] = [ 'page' => $page, 'rank' => 0 ];
  221. }
  222. foreach ( $wgContLang->getSpecialPageAliases() as $page => $aliases ) {
  223. if ( !in_array( $page, SpecialPageFactory::getNames() ) ) {# T22885
  224. continue;
  225. }
  226. foreach ( $aliases as $key => $alias ) {
  227. $keys[$wgContLang->caseFold( $alias )] = [ 'page' => $alias, 'rank' => $key ];
  228. }
  229. }
  230. ksort( $keys );
  231. $matches = [];
  232. foreach ( $keys as $pageKey => $page ) {
  233. if ( $searchKey === '' || strpos( $pageKey, $searchKey ) === 0 ) {
  234. // T29671: Don't use SpecialPage::getTitleFor() here because it
  235. // localizes its input leading to searches for e.g. Special:All
  236. // returning Spezial:MediaWiki-Systemnachrichten and returning
  237. // Spezial:Alle_Seiten twice when $wgLanguageCode == 'de'
  238. $matches[$page['rank']][] = Title::makeTitleSafe( NS_SPECIAL, $page['page'] );
  239. if ( isset( $matches[0] ) && count( $matches[0] ) >= $limit + $offset ) {
  240. // We have enough items in primary rank, no use to continue
  241. break;
  242. }
  243. }
  244. }
  245. // Ensure keys are in order
  246. ksort( $matches );
  247. // Flatten the array
  248. $matches = array_reduce( $matches, 'array_merge', [] );
  249. return array_slice( $matches, $offset, $limit );
  250. }
  251. /**
  252. * Unless overridden by PrefixSearchBackend hook...
  253. * This is case-sensitive (First character may
  254. * be automatically capitalized by Title::secureAndSpit()
  255. * later on depending on $wgCapitalLinks)
  256. *
  257. * @param array|null $namespaces Namespaces to search in
  258. * @param string $search Term
  259. * @param int $limit Max number of items to return
  260. * @param int $offset Number of items to skip
  261. * @return Title[] Array of Title objects
  262. */
  263. public function defaultSearchBackend( $namespaces, $search, $limit, $offset ) {
  264. // Backwards compatability with old code. Default to NS_MAIN if no namespaces provided.
  265. if ( $namespaces === null ) {
  266. $namespaces = [];
  267. }
  268. if ( !$namespaces ) {
  269. $namespaces[] = NS_MAIN;
  270. }
  271. // Construct suitable prefix for each namespace. They differ in cases where
  272. // some namespaces always capitalize and some don't.
  273. $prefixes = [];
  274. foreach ( $namespaces as $namespace ) {
  275. // For now, if special is included, ignore the other namespaces
  276. if ( $namespace == NS_SPECIAL ) {
  277. return $this->specialSearch( $search, $limit, $offset );
  278. }
  279. $title = Title::makeTitleSafe( $namespace, $search );
  280. // Why does the prefix default to empty?
  281. $prefix = $title ? $title->getDBkey() : '';
  282. $prefixes[$prefix][] = $namespace;
  283. }
  284. $dbr = wfGetDB( DB_REPLICA );
  285. // Often there is only one prefix that applies to all requested namespaces,
  286. // but sometimes there are two if some namespaces do not always capitalize.
  287. $conds = [];
  288. foreach ( $prefixes as $prefix => $namespaces ) {
  289. $condition = [
  290. 'page_namespace' => $namespaces,
  291. 'page_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
  292. ];
  293. $conds[] = $dbr->makeList( $condition, LIST_AND );
  294. }
  295. $table = 'page';
  296. $fields = [ 'page_id', 'page_namespace', 'page_title' ];
  297. $conds = $dbr->makeList( $conds, LIST_OR );
  298. $options = [
  299. 'LIMIT' => $limit,
  300. 'ORDER BY' => [ 'page_title', 'page_namespace' ],
  301. 'OFFSET' => $offset
  302. ];
  303. $res = $dbr->select( $table, $fields, $conds, __METHOD__, $options );
  304. return iterator_to_array( TitleArray::newFromResult( $res ) );
  305. }
  306. /**
  307. * Validate an array of numerical namespace indexes
  308. *
  309. * @param array $namespaces
  310. * @return array (default: contains only NS_MAIN)
  311. */
  312. protected function validateNamespaces( $namespaces ) {
  313. global $wgContLang;
  314. // We will look at each given namespace against wgContLang namespaces
  315. $validNamespaces = $wgContLang->getNamespaces();
  316. if ( is_array( $namespaces ) && count( $namespaces ) > 0 ) {
  317. $valid = [];
  318. foreach ( $namespaces as $ns ) {
  319. if ( is_numeric( $ns ) && array_key_exists( $ns, $validNamespaces ) ) {
  320. $valid[] = $ns;
  321. }
  322. }
  323. if ( count( $valid ) > 0 ) {
  324. return $valid;
  325. }
  326. }
  327. return [ NS_MAIN ];
  328. }
  329. }
  330. /**
  331. * Performs prefix search, returning Title objects
  332. * @deprecated Since 1.27, Use SearchEngine::defaultPrefixSearch or SearchEngine::completionSearch
  333. * @ingroup Search
  334. */
  335. class TitlePrefixSearch extends PrefixSearch {
  336. protected function titles( array $titles ) {
  337. return $titles;
  338. }
  339. protected function strings( array $strings ) {
  340. $titles = array_map( 'Title::newFromText', $strings );
  341. $lb = new LinkBatch( $titles );
  342. $lb->setCaller( __METHOD__ );
  343. $lb->execute();
  344. return $titles;
  345. }
  346. }
  347. /**
  348. * Performs prefix search, returning strings
  349. * @deprecated Since 1.27, Use SearchEngine::prefixSearchSubpages or SearchEngine::completionSearch
  350. * @ingroup Search
  351. */
  352. class StringPrefixSearch extends PrefixSearch {
  353. protected function titles( array $titles ) {
  354. return array_map( function ( Title $t ) {
  355. return $t->getPrefixedText();
  356. }, $titles );
  357. }
  358. protected function strings( array $strings ) {
  359. return $strings;
  360. }
  361. }