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 ) {
113 return parent
::newFile( $title, $time );
117 * @param $files array
120 function fileExistsBatch( array $files ) {
122 foreach ( $files as $k => $f ) {
123 if ( isset( $this->mFileExists
[$f] ) ) {
124 $results[$k] = $this->mFileExists
[$f];
126 } elseif ( self
::isVirtualUrl( $f ) ) {
127 # @todo FIXME: We need to be able to handle virtual
128 # URLs better, at least when we know they refer to the
130 $results[$k] = false;
132 } elseif ( FileBackend
::isStoragePath( $f ) ) {
133 $results[$k] = false;
135 wfWarn( "Got mwstore:// path '$f'." );
139 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
140 'prop' => 'imageinfo' ) );
141 if ( isset( $data['query']['pages'] ) ) {
142 # First, get results from the query. Note we only care whether the image exists,
143 # not whether it has a description page.
144 foreach ( $data['query']['pages'] as $p ) {
145 $this->mFileExists
[$p['title']] = ( $p['imagerepository'] !== '' );
147 # Second, copy the results to any redirects that were queried
148 if ( isset( $data['query']['redirects'] ) ) {
149 foreach ( $data['query']['redirects'] as $r ) {
150 $this->mFileExists
[$r['from']] = $this->mFileExists
[$r['to']];
153 # Third, copy the results to any non-normalized titles that were queried
154 if ( isset( $data['query']['normalized'] ) ) {
155 foreach ( $data['query']['normalized'] as $n ) {
156 $this->mFileExists
[$n['from']] = $this->mFileExists
[$n['to']];
159 # Finally, copy the results to the output
160 foreach ( $files as $key => $file ) {
161 $results[$key] = $this->mFileExists
[$file];
168 * @param $virtualUrl string
171 function getFileProps( $virtualUrl ) {
176 * @param $query array
179 function fetchImageQuery( $query ) {
180 global $wgMemc, $wgLanguageCode;
182 $query = array_merge( $query,
186 'redirects' => 'true'
189 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
190 $query['uselang'] = $wgLanguageCode;
193 $data = $this->httpGetCached( 'Metadata', $query );
196 return FormatJson
::decode( $data, true );
206 function getImageInfo( $data ) {
207 if ( $data && isset( $data['query']['pages'] ) ) {
208 foreach ( $data['query']['pages'] as $info ) {
209 if ( isset( $info['imageinfo'][0] ) ) {
210 return $info['imageinfo'][0];
218 * @param $hash string
221 function findBySha1( $hash ) {
222 $results = $this->fetchImageQuery( array(
223 'aisha1base36' => $hash,
224 'aiprop' => ForeignAPIFile
::getProps(),
225 'list' => 'allimages',
228 if ( isset( $results['query']['allimages'] ) ) {
229 foreach ( $results['query']['allimages'] as $img ) {
230 // 1.14 was broken, doesn't return name attribute
231 if ( !isset( $img['name'] ) ) {
234 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
241 * @param $name string
244 * @param $result null
245 * @param $otherParams string
248 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
249 $data = $this->fetchImageQuery( array(
250 'titles' => 'File:' . $name,
251 'iiprop' => self
::getIIProps(),
252 'iiurlwidth' => $width,
253 'iiurlheight' => $height,
254 'iiurlparam' => $otherParams,
255 'prop' => 'imageinfo' ) );
256 $info = $this->getImageInfo( $data );
258 if ( $data && $info && isset( $info['thumburl'] ) ) {
259 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
261 return $info['thumburl'];
268 * @param $name string
271 * @param $otherParams string
272 * @return bool|MediaTransformError
275 function getThumbError( $name, $width = -1, $height = -1, $otherParams = '', $lang = null ) {
276 $data = $this->fetchImageQuery( array(
277 'titles' => 'File:' . $name,
278 'iiprop' => self
::getIIProps(),
279 'iiurlwidth' => $width,
280 'iiurlheight' => $height,
281 'iiurlparam' => $otherParams,
282 'prop' => 'imageinfo',
285 $info = $this->getImageInfo( $data );
287 if ( $data && $info && isset( $info['thumberror'] ) ) {
288 wfDebug( __METHOD__
. " got remote thumb error " . $info['thumberror'] . "\n" );
289 return new MediaTransformError(
290 'thumbnail_error_remote',
293 $this->getDisplayName(),
294 $info['thumberror'] // already parsed message from foreign repo
302 * Return the imageurl from cache if possible
304 * If the url has been requested today, get it from cache
305 * Otherwise retrieve remote thumb url, check for local file.
307 * @param string $name is a dbkey form of a title
310 * @param string $params Other rendering parameters (page number, etc) from handler's makeParamString.
311 * @return bool|string
313 function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
315 // We can't check the local cache using FileRepo functions because
316 // we override fileExistsBatch(). We have to use the FileBackend directly.
317 $backend = $this->getBackend(); // convenience
319 if ( !$this->canCacheThumbs() ) {
320 $result = null; // can't pass "null" by reference, but it's ok as default value
321 return $this->getThumbUrl( $name, $width, $height, $result, $params );
323 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
324 $sizekey = "$width:$height:$params";
326 /* Get the array of urls that we already know */
327 $knownThumbUrls = $wgMemc->get( $key );
328 if ( !$knownThumbUrls ) {
329 /* No knownThumbUrls for this file */
330 $knownThumbUrls = array();
332 if ( isset( $knownThumbUrls[$sizekey] ) ) {
333 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
334 "{$knownThumbUrls[$sizekey]} \n" );
335 return $knownThumbUrls[$sizekey];
337 /* This size is not yet known */
341 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
343 if ( !$foreignUrl ) {
344 wfDebug( __METHOD__
. " Could not find thumburl\n" );
348 // We need the same filename as the remote one :)
349 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
350 if ( !$this->validateFilename( $fileName ) ) {
351 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
354 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
355 $localFilename = $localPath . "/" . $fileName;
356 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
358 if ( $backend->fileExists( array( 'src' => $localFilename ) )
359 && isset( $metadata['timestamp'] ) ) {
360 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
361 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
362 $remoteModified = strtotime( $metadata['timestamp'] );
364 $diff = abs( $modified - $current );
365 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
366 /* Use our current and already downloaded thumbnail */
367 $knownThumbUrls[$sizekey] = $localUrl;
368 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
371 /* There is a new Commons file, or existing thumbnail older than a month */
373 $thumb = self
::httpGet( $foreignUrl );
375 wfDebug( __METHOD__
. " Could not download thumb\n" );
379 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
380 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
381 $params = array( 'dst' => $localFilename, 'content' => $thumb );
382 if ( !$backend->quickCreate( $params )->isOK() ) {
383 wfDebug( __METHOD__
. " could not write to thumb path '$localFilename'\n" );
386 $knownThumbUrls[$sizekey] = $localUrl;
387 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
388 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
393 * @see FileRepo::getZoneUrl()
394 * @param $zone String
395 * @param string|null $ext Optional file extension
398 function getZoneUrl( $zone, $ext = null ) {
403 return $this->thumbUrl
;
405 return parent
::getZoneUrl( $zone, $ext );
410 * Get the local directory corresponding to one of the basic zones
411 * @param $zone string
412 * @return bool|null|string
414 function getZonePath( $zone ) {
415 $supported = array( 'public', 'thumb' );
416 if ( in_array( $zone, $supported ) ) {
417 return parent
::getZonePath( $zone );
423 * Are we locally caching the thumbnails?
426 public function canCacheThumbs() {
427 return ( $this->apiThumbCacheExpiry
> 0 );
431 * The user agent the ForeignAPIRepo will use.
434 public static function getUserAgent() {
435 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
439 * Get information about the repo - overrides/extends the parent
440 * class's information.
445 $info = parent
::getInfo();
446 $info['apiurl'] = $this->getApiUrl();
451 'meta' => 'siteinfo',
452 'siprop' => 'general',
455 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
458 $siteInfo = FormatJson
::decode( $data, true );
459 $general = $siteInfo['query']['general'];
461 $info['articlepath'] = $general['articlepath'];
462 $info['server'] = $general['server'];
469 * Like a Http:get request, but with custom User-Agent.
472 * @param $timeout string
473 * @param $options array
474 * @return bool|String
476 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
477 $options['timeout'] = $timeout;
479 $url = wfExpandUrl( $url, PROTO_HTTP
);
480 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
481 $options['method'] = "GET";
483 if ( !isset( $options['timeout'] ) ) {
484 $options['timeout'] = 'default';
487 $req = MWHttpRequest
::factory( $url, $options );
488 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
489 $status = $req->execute();
491 if ( $status->isOK() ) {
492 return $req->getContent();
502 protected static function getIIProps() {
503 return join( '|', self
::$imageInfoProps );
507 * HTTP GET request to a mediawiki API (with caching)
508 * @param $target string Used in cache key creation, mostly
509 * @param $query array The query parameters for the API request
510 * @param $cacheTTL int Time to live for the memcached caching
512 public function httpGetCached( $target, $query, $cacheTTL = 3600 ) {
513 if ( $this->mApiBase
) {
514 $url = wfAppendQuery( $this->mApiBase
, $query );
516 $url = $this->makeUrl( $query, 'api' );
519 if ( !isset( $this->mQueryCache
[$url] ) ) {
522 $key = $this->getLocalCacheKey( get_class( $this ), $target, md5( $url ) );
523 $data = $wgMemc->get( $key );
526 $data = self
::httpGet( $url );
532 $wgMemc->set( $key, $data, $cacheTTL );
535 if ( count( $this->mQueryCache
) > 100 ) {
536 // Keep the cache from growing infinitely
537 $this->mQueryCache
= array();
540 $this->mQueryCache
[$url] = $data;
543 return $this->mQueryCache
[$url];
547 * @param $callback Array|string
548 * @throws MWException
550 function enumFiles( $callback ) {
551 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
555 * @throws MWException
557 protected function assertWritableRepo() {
558 throw new MWException( get_class( $this ) . ': write operations are not supported.' );