Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 47
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
SearchExactMatchRescorer
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 5
380
0.00% covered (danger)
0.00%
0 / 1
 rescore
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
110
 getReplacedRedirect
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 redirectTargetsToRedirect
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 pullFront
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getRedirectTarget
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * Rescores results from a prefix search/opensearch to make sure the
4 * exact match is the first result.
5 *
6 * @license GPL-2.0-or-later
7 * @file
8 */
9
10namespace MediaWiki\Search;
11
12use MediaWiki\MediaWikiServices;
13use MediaWiki\Page\PageIdentity;
14use MediaWiki\Title\Title;
15
16/**
17 * An utility class to rescore search results by looking for an exact match
18 * in the db and add the page found to the first position.
19 *
20 * NOTE: extracted from TitlePrefixSearch
21 * @ingroup Search
22 */
23class SearchExactMatchRescorer {
24    /**
25     * @var ?string set when a redirect returned from the engine is replaced by the exact match
26     */
27    private ?string $replacedRedirect;
28
29    /**
30     * Default search backend does proper prefix searching, but custom backends
31     * may sort based on other algorithms that may cause the exact title match
32     * to not be in the results or be lower down the list.
33     * @param string $search the query
34     * @param int[] $namespaces
35     * @param string[] $srchres results
36     * @param int $limit the max number of results to return
37     * @return string[] munged results
38     */
39    public function rescore( $search, $namespaces, $srchres, $limit ) {
40        $this->replacedRedirect = null;
41        // Pick namespace (based on PrefixSearch::defaultSearchBackend)
42        $ns = in_array( NS_MAIN, $namespaces ) ? NS_MAIN : reset( $namespaces );
43        $t = Title::newFromText( $search, $ns );
44        if ( !$t || !$t->exists() ) {
45            // No exact match so just return the search results
46            return $srchres;
47        }
48        $string = $t->getPrefixedText();
49        $key = array_search( $string, $srchres );
50        if ( $key !== false ) {
51            // Exact match was in the results so just move it to the front
52            return $this->pullFront( $key, $srchres );
53        }
54        // Exact match not in the search results so check for some redirect handling cases
55        if ( $t->isRedirect() ) {
56            $target = $this->getRedirectTarget( $t );
57            $key = array_search( $target, $srchres );
58            if ( $key !== false ) {
59                // Exact match is a redirect to one of the returned matches so pull the
60                // returned match to the front.  This might look odd but the alternative
61                // is to put the redirect in front and drop the match.  The name of the
62                // found match is often more descriptive/better formed than the name of
63                // the redirect AND by definition they share a prefix.  Hopefully this
64                // choice is less confusing and more helpful.  But it might not be.  But
65                // it is the choice we're going with for now.
66                return $this->pullFront( $key, $srchres );
67            }
68            $redirectTargetsToRedirect = $this->redirectTargetsToRedirect( $srchres );
69            if ( isset( $redirectTargetsToRedirect[$target] ) ) {
70                // The exact match and something in the results list are both redirects
71                // to the same thing! In this case we prefer the match the user typed.
72                $this->replacedRedirect = array_splice( $srchres, $redirectTargetsToRedirect[$target], 1 )[0];
73                array_unshift( $srchres, $string );
74                return $srchres;
75            }
76        } else {
77            $redirectTargetsToRedirect = $this->redirectTargetsToRedirect( $srchres );
78            if ( isset( $redirectTargetsToRedirect[$string] ) ) {
79                // The exact match is the target of a redirect already in the results list so remove
80                // the redirect from the results list and push the exact match to the front
81                array_splice( $srchres, $redirectTargetsToRedirect[$string], 1 );
82                array_unshift( $srchres, $string );
83                return $srchres;
84            }
85        }
86
87        // Exact match is totally unique from the other results so just add it to the front
88        array_unshift( $srchres, $string );
89        // And roll one off the end if the results are too long
90        if ( count( $srchres ) > $limit ) {
91            array_pop( $srchres );
92        }
93        return $srchres;
94    }
95
96    /**
97     * Redirect initially returned by the search engine that got replaced by a better match:
98     * - exact match to a redirect to the same page
99     * - exact match to the target page
100     * @return string|null the replaced redirect or null if nothing was replaced
101     */
102    public function getReplacedRedirect(): ?string {
103        return $this->replacedRedirect;
104    }
105
106    /**
107     * @param string[] $titles
108     * @return array redirect target prefixedText to index of title in titles
109     *   that is a redirect to it.
110     */
111    private function redirectTargetsToRedirect( array $titles ) {
112        $result = [];
113        foreach ( $titles as $key => $titleText ) {
114            $title = Title::newFromText( $titleText );
115            if ( !$title || !$title->isRedirect() ) {
116                continue;
117            }
118            $target = $this->getRedirectTarget( $title );
119            if ( !$target ) {
120                continue;
121            }
122            $result[$target] = $key;
123        }
124        return $result;
125    }
126
127    /**
128     * Returns an array where the element of $array at index $key becomes
129     * the first element.
130     * @param int $key key to pull to the front
131     * @param array $array
132     * @return array $array with the item at $key pulled to the front
133     */
134    private function pullFront( $key, array $array ) {
135        $cut = array_splice( $array, $key, 1 );
136        array_unshift( $array, $cut[0] );
137        return $array;
138    }
139
140    /**
141     * Get a redirect's destination from a title
142     * @param PageIdentity $page A page to redirect. It may not redirect or even exist
143     * @return null|string If title exists and redirects, get the destination's prefixed name
144     */
145    private function getRedirectTarget( PageIdentity $page ) {
146        $redirectStore = MediaWikiServices::getInstance()->getRedirectStore();
147        $redir = $redirectStore->getRedirectTarget( $page );
148
149        // Needed to get the text needed for display.
150        $redir = Title::castFromLinkTarget( $redir );
151        return $redir ? $redir->getPrefixedText() : null;
152    }
153}
154
155/** @deprecated class alias since 1.46 */
156class_alias( SearchExactMatchRescorer::class, 'SearchExactMatchRescorer' );