API: Don't use an empty LinkBatch in ApiOpenSearch
[lhc/web/wiklou.git] / includes / api / ApiOpenSearch.php
1 <?php
2 /**
3 * Created on Oct 13, 2006
4 *
5 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
6 * Copyright © 2008 Brion Vibber <brion@wikimedia.org>
7 * Copyright © 2014 Brad Jorsch <bjorsch@wikimedia.org>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * @ingroup API
29 */
30 class ApiOpenSearch extends ApiBase {
31
32 private $format = null;
33 private $fm = null;
34
35 /**
36 * Get the output format
37 *
38 * @return string
39 */
40 protected function getFormat() {
41 if ( $this->format === null ) {
42 $params = $this->extractRequestParams();
43 $format = $params['format'];
44
45 $allowedParams = $this->getAllowedParams();
46 if ( !in_array( $format, $allowedParams['format'][ApiBase::PARAM_TYPE] ) ) {
47 $format = $allowedParams['format'][ApiBase::PARAM_DFLT];
48 }
49
50 if ( substr( $format, -2 ) === 'fm' ) {
51 $this->format = substr( $format, 0, -2 );
52 $this->fm = 'fm';
53 } else {
54 $this->format = $format;
55 $this->fm = '';
56 }
57 }
58 return $this->format;
59 }
60
61 public function getCustomPrinter() {
62 switch ( $this->getFormat() ) {
63 case 'json':
64 return $this->getMain()->createPrinterByName( 'json' . $this->fm );
65
66 case 'xml':
67 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm );
68 $printer->setRootElement( 'SearchSuggestion' );
69 return $printer;
70
71 default:
72 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
73 }
74 }
75
76 public function execute() {
77 $params = $this->extractRequestParams();
78 $search = $params['search'];
79 $limit = $params['limit'];
80 $namespaces = $params['namespace'];
81 $suggest = $params['suggest'];
82
83 if ( $params['redirects'] === null ) {
84 // Backwards compatibility, don't resolve for JSON.
85 $resolveRedir = $this->getFormat() !== 'json';
86 } else {
87 $resolveRedir = $params['redirects'] === 'resolve';
88 }
89
90 $results = array();
91
92 if ( !$suggest || $this->getConfig()->get( 'EnableOpenSearchSuggest' ) ) {
93 // Open search results may be stored for a very long time
94 $this->getMain()->setCacheMaxAge( $this->getConfig()->get( 'SearchSuggestCacheExpiry' ) );
95 $this->getMain()->setCacheMode( 'public' );
96 $this->search( $search, $limit, $namespaces, $resolveRedir, $results );
97
98 // Allow hooks to populate extracts and images
99 wfRunHooks( 'ApiOpenSearchSuggest', array( &$results ) );
100
101 // Trim extracts, if necessary
102 $length = $this->getConfig()->get( 'OpenSearchDescriptionLength' );
103 foreach ( $results as &$r ) {
104 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
105 $r['extract'] = self::trimExtract( $r['extract'], $length );
106 }
107 }
108 }
109
110 // Populate result object
111 $this->populateResult( $search, $results );
112 }
113
114 /**
115 * Perform the search
116 *
117 * @param string $search Text to search
118 * @param int $limit Maximum items to return
119 * @param array $namespaces Namespaces to search
120 * @param bool $resolveRedir Whether to resolve redirects
121 * @param array &$results Put results here
122 */
123 protected function search( $search, $limit, $namespaces, $resolveRedir, &$results ) {
124 // Find matching titles as Title objects
125 $searcher = new TitlePrefixSearch;
126 $titles = $searcher->searchWithVariants( $search, $limit, $namespaces );
127 if ( !$titles ) {
128 return;
129 }
130
131 if ( $resolveRedir ) {
132 // Query for redirects
133 $db = $this->getDb();
134 $lb = new LinkBatch( $titles );
135 $res = $db->select(
136 array( 'page', 'redirect' ),
137 array( 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ),
138 array(
139 'rd_from = page_id',
140 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
141 $lb->constructSet( 'page', $db ),
142 ),
143 __METHOD__
144 );
145 $redirects = array();
146 foreach ( $res as $row ) {
147 $redirects[$row->page_namespace][$row->page_title] =
148 array( $row->rd_namespace, $row->rd_title );
149 }
150
151 // Bypass any redirects
152 $seen = array();
153 foreach ( $titles as $title ) {
154 $ns = $title->getNamespace();
155 $dbkey = $title->getDBkey();
156 $from = null;
157 if ( isset( $redirects[$ns][$dbkey] ) ) {
158 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
159 $from = $title;
160 $title = Title::makeTitle( $ns, $dbkey );
161 }
162 if ( !isset( $seen[$ns][$dbkey] ) ) {
163 $seen[$ns][$dbkey] = true;
164 $results[$title->getArticleId()] = array(
165 'title' => $title,
166 'redirect from' => $from,
167 'extract' => false,
168 'extract trimmed' => false,
169 'image' => false,
170 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT ),
171 );
172 }
173 }
174 } else {
175 foreach ( $titles as $title ) {
176 $results[$title->getArticleId()] = array(
177 'title' => $title,
178 'redirect from' => null,
179 'extract' => false,
180 'extract trimmed' => false,
181 'image' => false,
182 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT ),
183 );
184 }
185 }
186 }
187
188 /**
189 * @param string $search
190 * @param array &$results
191 */
192 protected function populateResult( $search, &$results ) {
193 $result = $this->getResult();
194
195 switch ( $this->getFormat() ) {
196 case 'json':
197 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
198 $result->addValue( null, 0, strval( $search ) );
199 $terms = array();
200 $descriptions = array();
201 $urls = array();
202 foreach ( $results as $r ) {
203 $terms[] = $r['title']->getPrefixedText();
204 $descriptions[] = strval( $r['extract'] );
205 $urls[] = $r['url'];
206 }
207 $result->addValue( null, 1, $terms );
208 $result->addValue( null, 2, $descriptions );
209 $result->addValue( null, 3, $urls );
210 break;
211
212 case 'xml':
213 // http://msdn.microsoft.com/en-us/library/cc891508%28v=vs.85%29.aspx
214 $imageKeys = array(
215 'source' => true,
216 'alt' => true,
217 'width' => true,
218 'height' => true,
219 'align' => true,
220 );
221 $items = array();
222 foreach ( $results as $r ) {
223 $item = array();
224 $result->setContent( $item, $r['title']->getPrefixedText(), 'Text' );
225 $result->setContent( $item, $r['url'], 'Url' );
226 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
227 $result->setContent( $item, $r['extract'], 'Description' );
228 }
229 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
230 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
231 }
232 $items[] = $item;
233 }
234 $result->setIndexedTagName( $items, 'Item' );
235 $result->addValue( null, 'version', '2.0' );
236 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
237 $query = array();
238 $result->setContent( $query, strval( $search ) );
239 $result->addValue( null, 'Query', $query );
240 $result->addValue( null, 'Section', $items );
241 break;
242
243 default:
244 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
245 }
246 }
247
248 public function getAllowedParams() {
249 return array(
250 'search' => null,
251 'limit' => array(
252 ApiBase::PARAM_DFLT => $this->getConfig()->get( 'OpenSearchDefaultLimit' ),
253 ApiBase::PARAM_TYPE => 'limit',
254 ApiBase::PARAM_MIN => 1,
255 ApiBase::PARAM_MAX => 100,
256 ApiBase::PARAM_MAX2 => 100
257 ),
258 'namespace' => array(
259 ApiBase::PARAM_DFLT => NS_MAIN,
260 ApiBase::PARAM_TYPE => 'namespace',
261 ApiBase::PARAM_ISMULTI => true
262 ),
263 'suggest' => false,
264 'redirects' => array(
265 ApiBase::PARAM_TYPE => array( 'return', 'resolve' ),
266 ),
267 'format' => array(
268 ApiBase::PARAM_DFLT => 'json',
269 ApiBase::PARAM_TYPE => array( 'json', 'jsonfm', 'xml', 'xmlfm' ),
270 )
271 );
272 }
273
274 protected function getExamplesMessages() {
275 return array(
276 'action=opensearch&search=Te'
277 => 'apihelp-opensearch-example-te',
278 );
279 }
280
281 public function getHelpUrls() {
282 return 'https://www.mediawiki.org/wiki/API:Opensearch';
283 }
284
285 /**
286 * Trim an extract to a sensible length.
287 *
288 * Adapted from Extension:OpenSearchXml, which adapted it from
289 * Extension:ActiveAbstract.
290 *
291 * @param string $text
292 * @param int $len Target length; actual result will continue to the end of a sentence.
293 * @return string
294 */
295 public static function trimExtract( $text, $length ) {
296 static $regex = null;
297
298 if ( $regex === null ) {
299 $endchars = array(
300 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
301 '。', // full-width ideographic full-stop
302 '.', '!', '?', // double-width roman forms
303 '。', // half-width ideographic full stop
304 );
305 $endgroup = implode( '|', $endchars );
306 $end = "(?:$endgroup)";
307 $sentence = ".{{$length},}?$end+";
308 $regex = "/^($sentence)/u";
309 }
310
311 $matches = array();
312 if ( preg_match( $regex, $text, $matches ) ) {
313 return trim( $matches[1] );
314 } else {
315 // Just return the first line
316 $lines = explode( "\n", $text );
317 return trim( $lines[0] );
318 }
319 }
320
321 /**
322 * Fetch the template for a type.
323 *
324 * @param string $type MIME type
325 * @return string
326 */
327 public static function getOpenSearchTemplate( $type ) {
328 global $wgOpenSearchTemplate, $wgCanonicalServer;
329
330 if ( $wgOpenSearchTemplate && $type === 'application/x-suggestions+json' ) {
331 return $wgOpenSearchTemplate;
332 }
333
334 $ns = implode( '|', SearchEngine::defaultNamespaces() );
335 if ( !$ns ) {
336 $ns = "0";
337 }
338
339 switch ( $type ) {
340 case 'application/x-suggestions+json':
341 return $wgCanonicalServer . wfScript( 'api' )
342 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
343
344 case 'application/x-suggestions+xml':
345 return $wgCanonicalServer . wfScript( 'api' )
346 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
347
348 default:
349 throw new MWException( __METHOD__ . ": Unknown type '$type'" );
350 }
351 }
352 }