5eec9a500bc92051d6a92fb93f133f8deae038ff
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";
45 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
46 /* Check back with Commons after a day */
47 var $apiThumbCacheExpiry = 86400; /* 24*60*60 */
48 /* Redownload thumbnail files after a month */
49 var $fileCacheExpiry = 2592000; /* 86400*30 */
51 protected $mQueryCache = array();
52 protected $mFileExists = array();
55 * @param $info array|null
57 function __construct( $info ) {
58 global $wgLocalFileRepo;
59 parent
::__construct( $info );
61 // http://commons.wikimedia.org/w/api.php
62 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
64 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
65 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
67 if ( isset( $info['fileCacheExpiry'] ) ) {
68 $this->fileCacheExpiry
= $info['fileCacheExpiry'];
70 if ( !$this->scriptDirUrl
) {
71 // hack for description fetches
72 $this->scriptDirUrl
= dirname( $this->mApiBase
);
74 // If we can cache thumbs we can guess sane defaults for these
75 if ( $this->canCacheThumbs() && !$this->url
) {
76 $this->url
= $wgLocalFileRepo['url'];
78 if ( $this->canCacheThumbs() && !$this->thumbUrl
) {
79 $this->thumbUrl
= $this->url
. '/thumb';
87 function getApiUrl() {
88 return $this->mApiBase
;
92 * Per docs in FileRepo, this needs to return false if we don't support versioned
93 * files. Well, we don't.
96 * @param $time string|bool
99 function newFile( $title, $time = false ) {
103 return parent
::newFile( $title, $time );
107 * @param $files array
110 function fileExistsBatch( array $files ) {
112 foreach ( $files as $k => $f ) {
113 if ( isset( $this->mFileExists
[$f] ) ) {
114 $results[$k] = $this->mFileExists
[$f];
116 } elseif ( self
::isVirtualUrl( $f ) ) {
117 # @todo FIXME: We need to be able to handle virtual
118 # URLs better, at least when we know they refer to the
120 $results[$k] = false;
122 } elseif ( FileBackend
::isStoragePath( $f ) ) {
123 $results[$k] = false;
125 wfWarn( "Got mwstore:// path '$f'." );
129 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
130 'prop' => 'imageinfo' ) );
131 if ( isset( $data['query']['pages'] ) ) {
132 # First, get results from the query. Note we only care whether the image exists,
133 # not whether it has a description page.
134 foreach ( $data['query']['pages'] as $p ) {
135 $this->mFileExists
[$p['title']] = ( $p['imagerepository'] !== '' );
137 # Second, copy the results to any redirects that were queried
138 if ( isset( $data['query']['redirects'] ) ) {
139 foreach ( $data['query']['redirects'] as $r ) {
140 $this->mFileExists
[$r['from']] = $this->mFileExists
[$r['to']];
143 # Third, copy the results to any non-normalized titles that were queried
144 if ( isset( $data['query']['normalized'] ) ) {
145 foreach ( $data['query']['normalized'] as $n ) {
146 $this->mFileExists
[$n['from']] = $this->mFileExists
[$n['to']];
149 # Finally, copy the results to the output
150 foreach ( $files as $key => $file ) {
151 $results[$key] = $this->mFileExists
[$file];
158 * @param $virtualUrl string
161 function getFileProps( $virtualUrl ) {
166 * @param $query array
169 function fetchImageQuery( $query ) {
170 global $wgMemc, $wgLanguageCode;
172 $query = array_merge( $query,
176 'redirects' => 'true'
179 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
180 $query['uselang'] = $wgLanguageCode;
183 $data = $this->httpGetCached( 'Metadata', $query );
186 return FormatJson
::decode( $data, true );
196 function getImageInfo( $data ) {
197 if ( $data && isset( $data['query']['pages'] ) ) {
198 foreach ( $data['query']['pages'] as $info ) {
199 if ( isset( $info['imageinfo'][0] ) ) {
200 return $info['imageinfo'][0];
208 * @param $hash string
211 function findBySha1( $hash ) {
212 $results = $this->fetchImageQuery( array(
213 'aisha1base36' => $hash,
214 'aiprop' => ForeignAPIFile
::getProps(),
215 'list' => 'allimages',
218 if ( isset( $results['query']['allimages'] ) ) {
219 foreach ( $results['query']['allimages'] as $img ) {
220 // 1.14 was broken, doesn't return name attribute
221 if ( !isset( $img['name'] ) ) {
224 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
231 * @param $name string
234 * @param $result null
235 * @param $otherParams string
238 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
239 $data = $this->fetchImageQuery( array(
240 'titles' => 'File:' . $name,
241 'iiprop' => 'url|timestamp',
242 'iiurlwidth' => $width,
243 'iiurlheight' => $height,
244 'iiurlparam' => $otherParams,
245 'prop' => 'imageinfo' ) );
246 $info = $this->getImageInfo( $data );
248 if ( $data && $info && isset( $info['thumburl'] ) ) {
249 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
251 return $info['thumburl'];
258 * @param $name string
261 * @param $otherParams string
262 * @return bool|MediaTransformError
265 function getThumbError( $name, $width = -1, $height = -1, $otherParams = '', $lang = null ) {
266 $data = $this->fetchImageQuery( array(
267 'titles' => 'File:' . $name,
268 'iiprop' => 'url|timestamp',
269 'iiurlwidth' => $width,
270 'iiurlheight' => $height,
271 'iiurlparam' => $otherParams,
272 'prop' => 'imageinfo',
275 $info = $this->getImageInfo( $data );
277 if ( $data && $info && isset( $info['thumberror'] ) ) {
278 wfDebug( __METHOD__
. " got remote thumb error " . $info['thumberror'] . "\n" );
279 return new MediaTransformError(
280 'thumbnail_error_remote',
283 $this->getDisplayName(),
284 $info['thumberror'] // already parsed message from foreign repo
292 * Return the imageurl from cache if possible
294 * If the url has been requested today, get it from cache
295 * Otherwise retrieve remote thumb url, check for local file.
297 * @param string $name is a dbkey form of a title
300 * @param string $params Other rendering parameters (page number, etc) from handler's makeParamString.
301 * @return bool|string
303 function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
305 // We can't check the local cache using FileRepo functions because
306 // we override fileExistsBatch(). We have to use the FileBackend directly.
307 $backend = $this->getBackend(); // convenience
309 if ( !$this->canCacheThumbs() ) {
310 $result = null; // can't pass "null" by reference, but it's ok as default value
311 return $this->getThumbUrl( $name, $width, $height, $result, $params );
313 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
314 $sizekey = "$width:$height:$params";
316 /* Get the array of urls that we already know */
317 $knownThumbUrls = $wgMemc->get( $key );
318 if ( !$knownThumbUrls ) {
319 /* No knownThumbUrls for this file */
320 $knownThumbUrls = array();
322 if ( isset( $knownThumbUrls[$sizekey] ) ) {
323 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
324 "{$knownThumbUrls[$sizekey]} \n" );
325 return $knownThumbUrls[$sizekey];
327 /* This size is not yet known */
331 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
333 if ( !$foreignUrl ) {
334 wfDebug( __METHOD__
. " Could not find thumburl\n" );
338 // We need the same filename as the remote one :)
339 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
340 if ( !$this->validateFilename( $fileName ) ) {
341 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
344 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
345 $localFilename = $localPath . "/" . $fileName;
346 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
348 if ( $backend->fileExists( array( 'src' => $localFilename ) )
349 && isset( $metadata['timestamp'] ) ) {
350 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
351 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
352 $remoteModified = strtotime( $metadata['timestamp'] );
354 $diff = abs( $modified - $current );
355 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
356 /* Use our current and already downloaded thumbnail */
357 $knownThumbUrls[$sizekey] = $localUrl;
358 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
361 /* There is a new Commons file, or existing thumbnail older than a month */
363 $thumb = self
::httpGet( $foreignUrl );
365 wfDebug( __METHOD__
. " Could not download thumb\n" );
369 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
370 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
371 $params = array( 'dst' => $localFilename, 'content' => $thumb );
372 if ( !$backend->quickCreate( $params )->isOK() ) {
373 wfDebug( __METHOD__
. " could not write to thumb path '$localFilename'\n" );
376 $knownThumbUrls[$sizekey] = $localUrl;
377 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
378 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
383 * @see FileRepo::getZoneUrl()
384 * @param $zone String
385 * @param string|null $ext Optional file extension
388 function getZoneUrl( $zone, $ext = null ) {
393 return $this->thumbUrl
;
395 return parent
::getZoneUrl( $zone, $ext );
400 * Get the local directory corresponding to one of the basic zones
401 * @param $zone string
402 * @return bool|null|string
404 function getZonePath( $zone ) {
405 $supported = array( 'public', 'thumb' );
406 if ( in_array( $zone, $supported ) ) {
407 return parent
::getZonePath( $zone );
413 * Are we locally caching the thumbnails?
416 public function canCacheThumbs() {
417 return ( $this->apiThumbCacheExpiry
> 0 );
421 * The user agent the ForeignAPIRepo will use.
424 public static function getUserAgent() {
425 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
429 * Get information about the repo - overrides/extends the parent
430 * class's information.
435 $info = parent
::getInfo();
436 $info['apiurl'] = $this->getApiUrl();
441 'meta' => 'siteinfo',
442 'siprop' => 'general',
445 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
448 $siteInfo = FormatJson
::decode( $data, true );
449 $general = $siteInfo['query']['general'];
451 $info['articlepath'] = $general['articlepath'];
452 $info['server'] = $general['server'];
459 * Like a Http:get request, but with custom User-Agent.
462 * @param $timeout string
463 * @param $options array
464 * @return bool|String
466 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
467 $options['timeout'] = $timeout;
469 $url = wfExpandUrl( $url, PROTO_HTTP
);
470 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
471 $options['method'] = "GET";
473 if ( !isset( $options['timeout'] ) ) {
474 $options['timeout'] = 'default';
477 $req = MWHttpRequest
::factory( $url, $options );
478 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
479 $status = $req->execute();
481 if ( $status->isOK() ) {
482 return $req->getContent();
489 * HTTP GET request to a mediawiki API (with caching)
490 * @param $target string Used in cache key creation, mostly
491 * @param $query array The query parameters for the API request
492 * @param $cacheTTL int Time to live for the memcached caching
494 public function httpGetCached( $target, $query, $cacheTTL = 3600 ) {
495 if ( $this->mApiBase
) {
496 $url = wfAppendQuery( $this->mApiBase
, $query );
498 $url = $this->makeUrl( $query, 'api' );
501 if ( !isset( $this->mQueryCache
[$url] ) ) {
504 $key = $this->getLocalCacheKey( get_class( $this ), $target, md5( $url ) );
505 $data = $wgMemc->get( $key );
508 $data = self
::httpGet( $url );
514 $wgMemc->set( $key, $data, $cacheTTL );
517 if ( count( $this->mQueryCache
) > 100 ) {
518 // Keep the cache from growing infinitely
519 $this->mQueryCache
= array();
522 $this->mQueryCache
[$url] = $data;
525 return $this->mQueryCache
[$url];
529 * @param $callback Array|string
530 * @throws MWException
532 function enumFiles( $callback ) {
533 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
537 * @throws MWException
539 protected function assertWritableRepo() {
540 throw new MWException( get_class( $this ) . ': write operations are not supported.' );