Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.95% covered (success)
95.95%
71 / 74
85.71% covered (warning)
85.71%
12 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
DeepcatFeature
95.95% covered (success)
95.95%
71 / 74
85.71% covered (warning)
85.71%
12 / 14
26
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 getCrossSearchStrategy
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getKeywords
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFeatureName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doApply
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 expand
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doExpand
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 decideUiWarning
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getCategoryPrefix
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 logRequest
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 fetchCategories
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
3.00
 buildPropertyPathClauses
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getFilterQuery
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doGetFilterQuery
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace CirrusSearch\Query;
4
5use CirrusSearch\CachedSparqlClient;
6use CirrusSearch\CirrusConfigNames;
7use CirrusSearch\CrossSearchStrategy;
8use CirrusSearch\LogChannel;
9use CirrusSearch\Parser\AST\KeywordFeatureNode;
10use CirrusSearch\Query\Builder\QueryBuildingContext;
11use CirrusSearch\Search\SearchContext;
12use CirrusSearch\SearchConfig;
13use CirrusSearch\Util;
14use CirrusSearch\WarningCollector;
15use Elastica\Query\AbstractQuery;
16use Elastica\Query\Terms;
17use MediaWiki\Config\Config;
18use MediaWiki\Logger\LoggerFactory;
19use MediaWiki\MediaWikiServices;
20use MediaWiki\Sparql\SparqlException;
21use MediaWiki\Title\Title;
22
23/**
24 * Filters by category or its subcategories. E.g. if category Vehicles includes Cars
25 * and Boats, then search for Vehicles would match pages in Vehicles, Cars and Boats.
26 *
27 * Syntax:
28 *  deepcat:Vehicles
29 */
30class DeepcatFeature extends SimpleKeywordFeature implements FilterQueryFeature {
31    /**
32     * Max lookup depth
33     * @var int
34     */
35    private $depth;
36    /**
37     * Max number of categories
38     * @var int
39     */
40    private $limit;
41    /**
42     * Category URL prefix for this wiki
43     * @var string|null (lazy loaded)
44     */
45    private $prefix;
46    /**
47     * @var CachedSparqlClient
48     */
49    private $sparql;
50
51    /**
52     * User agent to use for SPARQL queries
53     */
54    public const USER_AGENT = 'CirrusSearch deepcat feature';
55    /**
56     * Timeout (in seconds) for SPARQL query.
57     * TODO: make configurable?
58     */
59    public const TIMEOUT = 3;
60
61    /**
62     * @param Config $config
63     * @param ?CachedSparqlClient $sparql
64     */
65    public function __construct( Config $config, ?CachedSparqlClient $sparql = null ) {
66        $this->depth = (int)$config->get( CirrusConfigNames::CategoryDepth );
67        $this->limit = (int)$config->get( CirrusConfigNames::CategoryMax );
68        $endpoint = $config->get( CirrusConfigNames::CategoryEndpoint );
69        if ( $endpoint !== null && $endpoint !== '' ) {
70            $this->sparql = $sparql ?? MediaWikiServices::getInstance()->getService( CachedSparqlClient::SERVICE );
71        }
72    }
73
74    /**
75     * @param KeywordFeatureNode $node
76     * @return CrossSearchStrategy
77     */
78    public function getCrossSearchStrategy( KeywordFeatureNode $node ) {
79        // the category tree is wiki specific
80        return CrossSearchStrategy::hostWikiOnlyStrategy();
81    }
82
83    /**
84     * @return string[] The list of keywords this feature is supposed to match
85     */
86    protected function getKeywords() {
87        return [ 'deepcat', 'deepcategory' ];
88    }
89
90    /**
91     * @param string $key
92     * @param string $valueDelimiter
93     * @return string
94     */
95    public function getFeatureName( $key, $valueDelimiter ) {
96        return 'deepcategory';
97    }
98
99    /**
100     * Applies the detected keyword from the search term. May apply changes
101     * either to $context directly, or return a filter to be added.
102     *
103     * @param SearchContext $context
104     * @param string $key The keyword
105     * @param string $value The value attached to the keyword with quotes stripped and escaped
106     *  quotes un-escaped.
107     * @param string $quotedValue The original value in the search string, including quotes if used
108     * @param bool $negated Is the search negated? Not used to generate the returned AbstractQuery,
109     *  that will be negated as necessary. Used for any other building/context necessary.
110     * @return array Two element array, first an AbstractQuery or null to apply to the
111     *  query. Second a boolean indicating if the quotedValue should be kept in the search
112     *  string.
113     */
114    protected function doApply( SearchContext $context, $key, $value, $quotedValue, $negated ) {
115        $filter = $this->doGetFilterQuery( $this->doExpand( $value, $context ) );
116        if ( $filter === null ) {
117            $context->setResultsPossible( false );
118        }
119
120        return [ $filter, false ];
121    }
122
123    /**
124     * @param KeywordFeatureNode $node
125     * @param SearchConfig $config
126     * @param WarningCollector $warningCollector
127     * @return array
128     */
129    public function expand( KeywordFeatureNode $node, SearchConfig $config, WarningCollector $warningCollector ) {
130        return $this->doExpand( $node->getValue(), $warningCollector );
131    }
132
133    /**
134     * @param string $value
135     * @param WarningCollector $warningCollector
136     * @return array
137     */
138    private function doExpand( $value, WarningCollector $warningCollector ) {
139        if ( !$this->sparql ) {
140            $warningCollector->addWarning( 'cirrussearch-feature-deepcat-endpoint' );
141            return [];
142        }
143
144        $startQueryTime = microtime( true );
145        try {
146            $categories = $this->fetchCategories( $value, $warningCollector );
147        } catch ( SparqlException $e ) {
148            // Not publishing exception here because it can contain too many details including IPs, etc.
149            $warningCollector->addWarning( $this->decideUiWarning( $e ) );
150            LoggerFactory::getInstance( LogChannel::DEFAULT )
151                ->warning( 'Deepcat SPARQL Exception: ' . $e->getMessage() );
152            $categories = [ $value ];
153        }
154        $this->logRequest( $startQueryTime );
155        return $categories;
156    }
157
158    private function decideUiWarning( SparqlException $e ): string {
159        $message = $e->getMessage();
160        // This could alternatively be a 500 error if blazegraph timed out
161        // prior to the http client timing out, but that doesn't happen due
162        // to http and blazegraph timeouts being set to the same value.
163        if ( strpos( $message, 'HTTP request timed out.' ) !== false ) {
164            return 'cirrussearch-feature-deepcat-timeout';
165        } else {
166            return 'cirrussearch-feature-deepcat-exception';
167        }
168    }
169
170    /**
171     * Get URL prefix for full category URL for this wiki.
172     * @return bool|string
173     */
174    private function getCategoryPrefix() {
175        if ( $this->prefix === null ) {
176            $title = Title::makeTitle( NS_CATEGORY, 'ZZ' );
177            $fullName = $title->getFullURL( '', false, PROTO_CANONICAL );
178            $this->prefix = substr( $fullName, 0, -2 );
179        }
180        return $this->prefix;
181    }
182
183    /**
184     * Record stats data for the request.
185     * @param float $startQueryTime
186     */
187    private function logRequest( $startQueryTime ) {
188        $timeTaken = intval( 1000 * ( microtime( true ) - $startQueryTime ) );
189        Util::getStatsFactory()
190            ->getTiming( 'deepcat_sparql_query_seconds' )
191            ->observe( $timeTaken );
192    }
193
194    /**
195     * Get child categories using SPARQL service.
196     * @param string $rootCategory Category to start looking from
197     * @param WarningCollector $warningCollector
198     * @return string[] List of subcategories.
199     * Note that the list may be incomplete due to limitations of the service.
200     * @throws SparqlException
201     */
202    private function fetchCategories( $rootCategory, WarningCollector $warningCollector ) {
203        $title = Title::makeTitleSafe( NS_CATEGORY, $rootCategory );
204        if ( $title === null ) {
205            $warningCollector->addWarning( 'cirrussearch-feature-deepcat-invalid-title' );
206            return [];
207        }
208        $fullName = $title->getFullURL( '', false, PROTO_CANONICAL );
209        $limit1 = $this->limit + 1;
210        $propertyPathClauses = $this->buildPropertyPathClauses( $this->depth );
211        $query = <<<SPARQL
212SELECT ?out (MIN(?d) AS ?depth) WHERE {
213 BIND (<$fullName> AS ?in)
214 { BIND (<$fullName> AS ?out) . BIND(0 AS ?d) }
215$propertyPathClauses
216} GROUP BY ?out ORDER BY ASC(?depth) LIMIT $limit1
217SPARQL;
218        $result = $this->sparql->query( $query );
219
220        if ( count( $result ) > $this->limit ) {
221            // We went over the limit.
222            $warningCollector->addWarning( 'cirrussearch-feature-deepcat-toomany' );
223            Util::getStatsFactory()
224                ->getCounter( 'deepcat_too_many_total' )
225                ->increment();
226            $result = array_slice( $result, 0, $this->limit );
227        }
228
229        $prefixLen = strlen( $this->getCategoryPrefix() );
230        return array_map( static function ( $row ) use ( $prefixLen ) {
231            // TODO: maybe we want to check the prefix is indeed the same?
232            // It should be but who knows...
233            return rawurldecode( substr( $row['out'], $prefixLen ) );
234        }, $result );
235    }
236
237    /**
238     * Builds a set of UNION clauses relying on explicit property paths to traverse each depth
239     * independently. The output form is:
240     * <pre>
241     * UNION { ?out mediawiki:isInCategory ?in . BIND(1 AS ?d) }
242     * UNION { ?out mediawiki:isInCategory/mediawiki:isInCategory ?in . BIND(2 AS ?d) }
243     * ...
244     * </pre>
245     * @param int $depth max depth to traverse
246     * @return string
247     */
248    private function buildPropertyPathClauses( int $depth ): string {
249        $clauses = "";
250        for ( $i = 1; $i <= $depth; $i++ ) {
251            $path = implode( "/", array_fill( 0, $i, "mediawiki:isInCategory" ) );
252            // expected line is (for a depth of 2):
253            // UNION { ?out mediawiki:isInCategory/mediawiki:isInCategory ?in . BIND(2 AS ?d) }
254            $clauses .= " UNION { ?out $path ?in . BIND($i AS ?d) }\n";
255        }
256        return $clauses;
257    }
258
259    /**
260     * @param KeywordFeatureNode $node
261     * @param QueryBuildingContext $context
262     * @return AbstractQuery|null
263     */
264    public function getFilterQuery( KeywordFeatureNode $node, QueryBuildingContext $context ) {
265        return $this->doGetFilterQuery( $context->getKeywordExpandedData( $node ) );
266    }
267
268    /**
269     * @param array $categories
270     * @return \Elastica\Query\AbstractQuery|null
271     */
272    protected function doGetFilterQuery( array $categories ) {
273        if ( $categories == [] ) {
274            return null;
275        }
276
277        // Categories are stored in search with spaces, but deepcat has the underscored variant
278        foreach ( $categories as &$cat ) {
279            $cat = strtr( $cat, '_', ' ' );
280        }
281
282        return new Terms( 'category.lowercase_keyword', $categories );
283    }
284}