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