3 * Foreign repository accessible through api.php requests.
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.
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.
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
25 * A foreign repository with a remote MediaWiki with an API thingy
29 * $wgForeignFileRepos[] = array(
30 * 'class' => 'ForeignAPIRepo',
32 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
33 * 'fetchDescription' => true, // Optional
34 * 'descriptionCacheExpiry' => 3600,
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";
46 * List of iiprop values for the thumbnail fetch queries.
49 protected static $imageInfoProps = array(
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 */
61 protected $mQueryCache = array();
62 protected $mFileExists = array();
65 * @param $info array|null
67 function __construct( $info ) {
68 global $wgLocalFileRepo;
69 parent
::__construct( $info );
71 // http://commons.wikimedia.org/w/api.php
72 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
74 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
75 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
77 if ( isset( $info['fileCacheExpiry'] ) ) {
78 $this->fileCacheExpiry
= $info['fileCacheExpiry'];
80 if ( !$this->scriptDirUrl
) {
81 // hack for description fetches
82 $this->scriptDirUrl
= dirname( $this->mApiBase
);
84 // If we can cache thumbs we can guess sane defaults for these
85 if ( $this->canCacheThumbs() && !$this->url
) {
86 $this->url
= $wgLocalFileRepo['url'];
88 if ( $this->canCacheThumbs() && !$this->thumbUrl
) {
89 $this->thumbUrl
= $this->url
. '/thumb';
97 function getApiUrl() {
98 return $this->mApiBase
;
102 * Per docs in FileRepo, this needs to return false if we don't support versioned
103 * files. Well, we don't.
105 * @param $title Title
106 * @param $time string|bool
109 function newFile( $title, $time = false ) {
114 return parent
::newFile( $title, $time );
118 * @param $files array
121 function fileExistsBatch( array $files ) {
123 foreach ( $files as $k => $f ) {
124 if ( isset( $this->mFileExists
[$f] ) ) {
125 $results[$k] = $this->mFileExists
[$f];
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
131 $results[$k] = false;
133 } elseif ( FileBackend
::isStoragePath( $f ) ) {
134 $results[$k] = false;
136 wfWarn( "Got mwstore:// path '$f'." );
140 $data = $this->fetchImageQuery( array(
141 'titles' => implode( $files, '|' ),
142 'prop' => 'imageinfo' )
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'] !== '' );
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']];
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']];
163 # Finally, copy the results to the output
164 foreach ( $files as $key => $file ) {
165 $results[$key] = $this->mFileExists
[$file];
173 * @param $virtualUrl string
176 function getFileProps( $virtualUrl ) {
181 * @param $query array
184 function fetchImageQuery( $query ) {
185 global $wgLanguageCode;
187 $query = array_merge( $query,
191 'redirects' => 'true'
194 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
195 $query['uselang'] = $wgLanguageCode;
198 $data = $this->httpGetCached( 'Metadata', $query );
201 return FormatJson
::decode( $data, true );
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];
224 * @param $hash string
227 function findBySha1( $hash ) {
228 $results = $this->fetchImageQuery( array(
229 'aisha1base36' => $hash,
230 'aiprop' => ForeignAPIFile
::getProps(),
231 'list' => 'allimages',
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'] ) ) {
240 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
248 * @param $name string
251 * @param $result null
252 * @param $otherParams string
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 );
265 if ( $data && $info && isset( $info['thumburl'] ) ) {
266 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
269 return $info['thumburl'];
276 * @param $name string
279 * @param $otherParams string
280 * @return bool|MediaTransformError
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',
293 $info = $this->getImageInfo( $data );
295 if ( $data && $info && isset( $info['thumberror'] ) ) {
296 wfDebug( __METHOD__
. " got remote thumb error " . $info['thumberror'] . "\n" );
298 return new MediaTransformError(
299 'thumbnail_error_remote',
302 $this->getDisplayName(),
303 $info['thumberror'] // already parsed message from foreign repo
311 * Return the imageurl from cache if possible
313 * If the url has been requested today, get it from cache
314 * Otherwise retrieve remote thumb url, check for local file.
316 * @param string $name is a dbkey form of a title
319 * @param string $params Other rendering parameters (page number, etc)
320 * from handler's makeParamString.
321 * @return bool|string
323 function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
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
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 );
333 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
334 $sizekey = "$width:$height:$params";
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();
342 if ( isset( $knownThumbUrls[$sizekey] ) ) {
343 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
344 "{$knownThumbUrls[$sizekey]} \n" );
346 return $knownThumbUrls[$sizekey];
348 /* This size is not yet known */
352 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
354 if ( !$foreignUrl ) {
355 wfDebug( __METHOD__
. " Could not find thumburl\n" );
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" );
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 );
372 if ( $backend->fileExists( array( 'src' => $localFilename ) )
373 && isset( $metadata['timestamp'] )
375 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
376 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
377 $remoteModified = strtotime( $metadata['timestamp'] );
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
);
387 /* There is a new Commons file, or existing thumbnail older than a month */
389 $thumb = self
::httpGet( $foreignUrl );
391 wfDebug( __METHOD__
. " Could not download thumb\n" );
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" );
404 $knownThumbUrls[$sizekey] = $localUrl;
405 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
406 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
412 * @see FileRepo::getZoneUrl()
413 * @param $zone String
414 * @param string|null $ext Optional file extension
417 function getZoneUrl( $zone, $ext = null ) {
422 return $this->thumbUrl
;
424 return parent
::getZoneUrl( $zone, $ext );
429 * Get the local directory corresponding to one of the basic zones
430 * @param $zone string
431 * @return bool|null|string
433 function getZonePath( $zone ) {
434 $supported = array( 'public', 'thumb' );
435 if ( in_array( $zone, $supported ) ) {
436 return parent
::getZonePath( $zone );
443 * Are we locally caching the thumbnails?
446 public function canCacheThumbs() {
447 return ( $this->apiThumbCacheExpiry
> 0 );
451 * The user agent the ForeignAPIRepo will use.
454 public static function getUserAgent() {
455 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
459 * Get information about the repo - overrides/extends the parent
460 * class's information.
465 $info = parent
::getInfo();
466 $info['apiurl'] = $this->getApiUrl();
471 'meta' => 'siteinfo',
472 'siprop' => 'general',
475 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
478 $siteInfo = FormatJson
::decode( $data, true );
479 $general = $siteInfo['query']['general'];
481 $info['articlepath'] = $general['articlepath'];
482 $info['server'] = $general['server'];
489 * Like a Http:get request, but with custom User-Agent.
492 * @param $timeout string
493 * @param $options array
494 * @return bool|String
496 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
497 $options['timeout'] = $timeout;
499 $url = wfExpandUrl( $url, PROTO_HTTP
);
500 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
501 $options['method'] = "GET";
503 if ( !isset( $options['timeout'] ) ) {
504 $options['timeout'] = 'default';
507 $req = MWHttpRequest
::factory( $url, $options );
508 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
509 $status = $req->execute();
511 if ( $status->isOK() ) {
512 return $req->getContent();
522 protected static function getIIProps() {
523 return join( '|', self
::$imageInfoProps );
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
532 public function httpGetCached( $target, $query, $cacheTTL = 3600 ) {
533 if ( $this->mApiBase
) {
534 $url = wfAppendQuery( $this->mApiBase
, $query );
536 $url = $this->makeUrl( $query, 'api' );
539 if ( !isset( $this->mQueryCache
[$url] ) ) {
542 $key = $this->getLocalCacheKey( get_class( $this ), $target, md5( $url ) );
543 $data = $wgMemc->get( $key );
546 $data = self
::httpGet( $url );
552 $wgMemc->set( $key, $data, $cacheTTL );
555 if ( count( $this->mQueryCache
) > 100 ) {
556 // Keep the cache from growing infinitely
557 $this->mQueryCache
= array();
560 $this->mQueryCache
[$url] = $data;
563 return $this->mQueryCache
[$url];
567 * @param $callback Array|string
568 * @throws MWException
570 function enumFiles( $callback ) {
571 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
575 * @throws MWException
577 protected function assertWritableRepo() {
578 throw new MWException( get_class( $this ) . ': write operations are not supported.' );