Merge "Don't check namespace in SpecialWantedtemplates"
[lhc/web/wiklou.git] / includes / filerepo / ForeignAPIRepo.php
1 <?php
2 /**
3 * Foreign repository accessible through api.php requests.
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 * @ingroup FileRepo
22 */
23
24 use MediaWiki\Logger\LoggerFactory;
25
26 /**
27 * A foreign repository with a remote MediaWiki with an API thingy
28 *
29 * Example config:
30 *
31 * $wgForeignFileRepos[] = array(
32 * 'class' => 'ForeignAPIRepo',
33 * 'name' => 'shared',
34 * 'apibase' => 'https://en.wikipedia.org/w/api.php',
35 * 'fetchDescription' => true, // Optional
36 * 'descriptionCacheExpiry' => 3600,
37 * );
38 *
39 * @ingroup FileRepo
40 */
41 class ForeignAPIRepo extends FileRepo {
42 /* This version string is used in the user agent for requests and will help
43 * server maintainers in identify ForeignAPI usage.
44 * Update the version every time you make breaking or significant changes. */
45 const VERSION = "2.1";
46
47 /**
48 * List of iiprop values for the thumbnail fetch queries.
49 * @since 1.23
50 */
51 protected static $imageInfoProps = array(
52 'url',
53 'thumbnail',
54 'timestamp',
55 );
56
57 protected $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
58 /** @var int Check back with Commons after a day (24*60*60) */
59 protected $apiThumbCacheExpiry = 86400;
60
61 /** @var int Redownload thumbnail files after a month (86400*30) */
62 protected $fileCacheExpiry = 2592000;
63
64 /** @var array */
65 protected $mFileExists = array();
66
67 /** @var array */
68 private $mQueryCache = array();
69
70 /**
71 * @param array|null $info
72 */
73 function __construct( $info ) {
74 global $wgLocalFileRepo;
75 parent::__construct( $info );
76
77 // https://commons.wikimedia.org/w/api.php
78 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
79
80 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
81 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
82 }
83 if ( isset( $info['fileCacheExpiry'] ) ) {
84 $this->fileCacheExpiry = $info['fileCacheExpiry'];
85 }
86 if ( !$this->scriptDirUrl ) {
87 // hack for description fetches
88 $this->scriptDirUrl = dirname( $this->mApiBase );
89 }
90 // If we can cache thumbs we can guess sane defaults for these
91 if ( $this->canCacheThumbs() && !$this->url ) {
92 $this->url = $wgLocalFileRepo['url'];
93 }
94 if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
95 $this->thumbUrl = $this->url . '/thumb';
96 }
97 }
98
99 /**
100 * @return string
101 * @since 1.22
102 */
103 function getApiUrl() {
104 return $this->mApiBase;
105 }
106
107 /**
108 * Per docs in FileRepo, this needs to return false if we don't support versioned
109 * files. Well, we don't.
110 *
111 * @param Title $title
112 * @param string|bool $time
113 * @return File
114 */
115 function newFile( $title, $time = false ) {
116 if ( $time ) {
117 return false;
118 }
119
120 return parent::newFile( $title, $time );
121 }
122
123 /**
124 * @param array $files
125 * @return array
126 */
127 function fileExistsBatch( array $files ) {
128 $results = array();
129 foreach ( $files as $k => $f ) {
130 if ( isset( $this->mFileExists[$f] ) ) {
131 $results[$k] = $this->mFileExists[$f];
132 unset( $files[$k] );
133 } elseif ( self::isVirtualUrl( $f ) ) {
134 # @todo FIXME: We need to be able to handle virtual
135 # URLs better, at least when we know they refer to the
136 # same repo.
137 $results[$k] = false;
138 unset( $files[$k] );
139 } elseif ( FileBackend::isStoragePath( $f ) ) {
140 $results[$k] = false;
141 unset( $files[$k] );
142 wfWarn( "Got mwstore:// path '$f'." );
143 }
144 }
145
146 $data = $this->fetchImageQuery( array(
147 'titles' => implode( $files, '|' ),
148 'prop' => 'imageinfo' )
149 );
150
151 if ( isset( $data['query']['pages'] ) ) {
152 # First, get results from the query. Note we only care whether the image exists,
153 # not whether it has a description page.
154 foreach ( $data['query']['pages'] as $p ) {
155 $this->mFileExists[$p['title']] = ( $p['imagerepository'] !== '' );
156 }
157 # Second, copy the results to any redirects that were queried
158 if ( isset( $data['query']['redirects'] ) ) {
159 foreach ( $data['query']['redirects'] as $r ) {
160 $this->mFileExists[$r['from']] = $this->mFileExists[$r['to']];
161 }
162 }
163 # Third, copy the results to any non-normalized titles that were queried
164 if ( isset( $data['query']['normalized'] ) ) {
165 foreach ( $data['query']['normalized'] as $n ) {
166 $this->mFileExists[$n['from']] = $this->mFileExists[$n['to']];
167 }
168 }
169 # Finally, copy the results to the output
170 foreach ( $files as $key => $file ) {
171 $results[$key] = $this->mFileExists[$file];
172 }
173 }
174
175 return $results;
176 }
177
178 /**
179 * @param string $virtualUrl
180 * @return bool
181 */
182 function getFileProps( $virtualUrl ) {
183 return false;
184 }
185
186 /**
187 * @param array $query
188 * @return string
189 */
190 function fetchImageQuery( $query ) {
191 global $wgLanguageCode;
192
193 $query = array_merge( $query,
194 array(
195 'format' => 'json',
196 'action' => 'query',
197 'redirects' => 'true'
198 ) );
199
200 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
201 $query['uselang'] = $wgLanguageCode;
202 }
203
204 $data = $this->httpGetCached( 'Metadata', $query );
205
206 if ( $data ) {
207 return FormatJson::decode( $data, true );
208 } else {
209 return null;
210 }
211 }
212
213 /**
214 * @param array $data
215 * @return bool|array
216 */
217 function getImageInfo( $data ) {
218 if ( $data && isset( $data['query']['pages'] ) ) {
219 foreach ( $data['query']['pages'] as $info ) {
220 if ( isset( $info['imageinfo'][0] ) ) {
221 return $info['imageinfo'][0];
222 }
223 }
224 }
225
226 return false;
227 }
228
229 /**
230 * @param string $hash
231 * @return array
232 */
233 function findBySha1( $hash ) {
234 $results = $this->fetchImageQuery( array(
235 'aisha1base36' => $hash,
236 'aiprop' => ForeignAPIFile::getProps(),
237 'list' => 'allimages',
238 ) );
239 $ret = array();
240 if ( isset( $results['query']['allimages'] ) ) {
241 foreach ( $results['query']['allimages'] as $img ) {
242 // 1.14 was broken, doesn't return name attribute
243 if ( !isset( $img['name'] ) ) {
244 continue;
245 }
246 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
247 }
248 }
249
250 return $ret;
251 }
252
253 /**
254 * @param string $name
255 * @param int $width
256 * @param int $height
257 * @param array $result Out parameter that will be changed by the function.
258 * @param string $otherParams
259 *
260 * @return bool
261 */
262 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
263 $data = $this->fetchImageQuery( array(
264 'titles' => 'File:' . $name,
265 'iiprop' => self::getIIProps(),
266 'iiurlwidth' => $width,
267 'iiurlheight' => $height,
268 'iiurlparam' => $otherParams,
269 'prop' => 'imageinfo' ) );
270 $info = $this->getImageInfo( $data );
271
272 if ( $data && $info && isset( $info['thumburl'] ) ) {
273 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
274 $result = $info;
275
276 return $info['thumburl'];
277 } else {
278 return false;
279 }
280 }
281
282 /**
283 * @param string $name
284 * @param int $width
285 * @param int $height
286 * @param string $otherParams
287 * @param string $lang Language code for language of error
288 * @return bool|MediaTransformError
289 * @since 1.22
290 */
291 function getThumbError( $name, $width = -1, $height = -1, $otherParams = '', $lang = null ) {
292 $data = $this->fetchImageQuery( array(
293 'titles' => 'File:' . $name,
294 'iiprop' => self::getIIProps(),
295 'iiurlwidth' => $width,
296 'iiurlheight' => $height,
297 'iiurlparam' => $otherParams,
298 'prop' => 'imageinfo',
299 'uselang' => $lang,
300 ) );
301 $info = $this->getImageInfo( $data );
302
303 if ( $data && $info && isset( $info['thumberror'] ) ) {
304 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] . "\n" );
305
306 return new MediaTransformError(
307 'thumbnail_error_remote',
308 $width,
309 $height,
310 $this->getDisplayName(),
311 $info['thumberror'] // already parsed message from foreign repo
312 );
313 } else {
314 return false;
315 }
316 }
317
318 /**
319 * Return the imageurl from cache if possible
320 *
321 * If the url has been requested today, get it from cache
322 * Otherwise retrieve remote thumb url, check for local file.
323 *
324 * @param string $name Is a dbkey form of a title
325 * @param int $width
326 * @param int $height
327 * @param string $params Other rendering parameters (page number, etc)
328 * from handler's makeParamString.
329 * @return bool|string
330 */
331 function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
332 global $wgMemc;
333 // We can't check the local cache using FileRepo functions because
334 // we override fileExistsBatch(). We have to use the FileBackend directly.
335 $backend = $this->getBackend(); // convenience
336
337 if ( !$this->canCacheThumbs() ) {
338 $result = null; // can't pass "null" by reference, but it's ok as default value
339 return $this->getThumbUrl( $name, $width, $height, $result, $params );
340 }
341 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
342 $sizekey = "$width:$height:$params";
343
344 /* Get the array of urls that we already know */
345 $knownThumbUrls = $wgMemc->get( $key );
346 if ( !$knownThumbUrls ) {
347 /* No knownThumbUrls for this file */
348 $knownThumbUrls = array();
349 } else {
350 if ( isset( $knownThumbUrls[$sizekey] ) ) {
351 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
352 "{$knownThumbUrls[$sizekey]} \n" );
353
354 return $knownThumbUrls[$sizekey];
355 }
356 /* This size is not yet known */
357 }
358
359 $metadata = null;
360 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
361
362 if ( !$foreignUrl ) {
363 wfDebug( __METHOD__ . " Could not find thumburl\n" );
364
365 return false;
366 }
367
368 // We need the same filename as the remote one :)
369 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
370 if ( !$this->validateFilename( $fileName ) ) {
371 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
372
373 return false;
374 }
375 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
376 $localFilename = $localPath . "/" . $fileName;
377 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
378 rawurlencode( $name ) . "/" . rawurlencode( $fileName );
379
380 if ( $backend->fileExists( array( 'src' => $localFilename ) )
381 && isset( $metadata['timestamp'] )
382 ) {
383 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
384 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
385 $remoteModified = strtotime( $metadata['timestamp'] );
386 $current = time();
387 $diff = abs( $modified - $current );
388 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
389 /* Use our current and already downloaded thumbnail */
390 $knownThumbUrls[$sizekey] = $localUrl;
391 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
392
393 return $localUrl;
394 }
395 /* There is a new Commons file, or existing thumbnail older than a month */
396 }
397 $thumb = self::httpGet( $foreignUrl );
398 if ( !$thumb ) {
399 wfDebug( __METHOD__ . " Could not download thumb\n" );
400
401 return false;
402 }
403
404 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
405 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
406 $params = array( 'dst' => $localFilename, 'content' => $thumb );
407 if ( !$backend->quickCreate( $params )->isOK() ) {
408 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'\n" );
409
410 return $foreignUrl;
411 }
412 $knownThumbUrls[$sizekey] = $localUrl;
413 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
414 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
415
416 return $localUrl;
417 }
418
419 /**
420 * @see FileRepo::getZoneUrl()
421 * @param string $zone
422 * @param string|null $ext Optional file extension
423 * @return string
424 */
425 function getZoneUrl( $zone, $ext = null ) {
426 switch ( $zone ) {
427 case 'public':
428 return $this->url;
429 case 'thumb':
430 return $this->thumbUrl;
431 default:
432 return parent::getZoneUrl( $zone, $ext );
433 }
434 }
435
436 /**
437 * Get the local directory corresponding to one of the basic zones
438 * @param string $zone
439 * @return bool|null|string
440 */
441 function getZonePath( $zone ) {
442 $supported = array( 'public', 'thumb' );
443 if ( in_array( $zone, $supported ) ) {
444 return parent::getZonePath( $zone );
445 }
446
447 return false;
448 }
449
450 /**
451 * Are we locally caching the thumbnails?
452 * @return bool
453 */
454 public function canCacheThumbs() {
455 return ( $this->apiThumbCacheExpiry > 0 );
456 }
457
458 /**
459 * The user agent the ForeignAPIRepo will use.
460 * @return string
461 */
462 public static function getUserAgent() {
463 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
464 }
465
466 /**
467 * Get information about the repo - overrides/extends the parent
468 * class's information.
469 * @return array
470 * @since 1.22
471 */
472 function getInfo() {
473 $info = parent::getInfo();
474 $info['apiurl'] = $this->getApiUrl();
475
476 $query = array(
477 'format' => 'json',
478 'action' => 'query',
479 'meta' => 'siteinfo',
480 'siprop' => 'general',
481 );
482
483 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
484
485 if ( $data ) {
486 $siteInfo = FormatJson::decode( $data, true );
487 $general = $siteInfo['query']['general'];
488
489 $info['articlepath'] = $general['articlepath'];
490 $info['server'] = $general['server'];
491
492 if ( isset( $general['favicon'] ) ) {
493 $info['favicon'] = $general['favicon'];
494 }
495 }
496
497 return $info;
498 }
499
500 /**
501 * Like a Http:get request, but with custom User-Agent.
502 * @see Http:get
503 * @param string $url
504 * @param string $timeout
505 * @param array $options
506 * @return bool|string
507 */
508 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
509 $options['timeout'] = $timeout;
510 /* Http::get */
511 $url = wfExpandUrl( $url, PROTO_HTTP );
512 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
513 $options['method'] = "GET";
514
515 if ( !isset( $options['timeout'] ) ) {
516 $options['timeout'] = 'default';
517 }
518
519 $req = MWHttpRequest::factory( $url, $options, __METHOD__ );
520 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
521 $status = $req->execute();
522
523 if ( $status->isOK() ) {
524 return $req->getContent();
525 } else {
526 $logger = LoggerFactory::getInstance( 'http' );
527 $logger->warning( $status->getWikiText(), array( 'caller' => 'ForeignAPIRepo::httpGet' ) );
528 return false;
529 }
530 }
531
532 /**
533 * @return string
534 * @since 1.23
535 */
536 protected static function getIIProps() {
537 return join( '|', self::$imageInfoProps );
538 }
539
540 /**
541 * HTTP GET request to a mediawiki API (with caching)
542 * @param string $target Used in cache key creation, mostly
543 * @param array $query The query parameters for the API request
544 * @param int $cacheTTL Time to live for the memcached caching
545 * @return null
546 */
547 public function httpGetCached( $target, $query, $cacheTTL = 3600 ) {
548 if ( $this->mApiBase ) {
549 $url = wfAppendQuery( $this->mApiBase, $query );
550 } else {
551 $url = $this->makeUrl( $query, 'api' );
552 }
553
554 if ( !isset( $this->mQueryCache[$url] ) ) {
555 global $wgMemc;
556
557 $key = $this->getLocalCacheKey( get_class( $this ), $target, md5( $url ) );
558 $data = $wgMemc->get( $key );
559
560 if ( !$data ) {
561 $data = self::httpGet( $url );
562
563 if ( !$data ) {
564 return null;
565 }
566
567 $wgMemc->set( $key, $data, $cacheTTL );
568 }
569
570 if ( count( $this->mQueryCache ) > 100 ) {
571 // Keep the cache from growing infinitely
572 $this->mQueryCache = array();
573 }
574
575 $this->mQueryCache[$url] = $data;
576 }
577
578 return $this->mQueryCache[$url];
579 }
580
581 /**
582 * @param callable $callback
583 * @throws MWException
584 */
585 function enumFiles( $callback ) {
586 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
587 }
588
589 /**
590 * @throws MWException
591 */
592 protected function assertWritableRepo() {
593 throw new MWException( get_class( $this ) . ': write operations are not supported.' );
594 }
595 }