3 * Foreign repository accessible through api.php requests.
10 * A foreign repository with a remote MediaWiki with an API thingy
14 * $wgForeignFileRepos[] = array(
15 * 'class' => 'ForeignAPIRepo',
17 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
18 * 'fetchDescription' => true, // Optional
19 * 'descriptionCacheExpiry' => 3600,
24 class ForeignAPIRepo
extends FileRepo
{
25 /* This version string is used in the user agent for requests and will help
26 * server maintainers in identify ForeignAPI usage.
27 * Update the version every time you make breaking or significant changes. */
28 const VERSION
= "2.1";
30 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
31 /* Check back with Commons after a day */
32 var $apiThumbCacheExpiry = 86400; /* 24*60*60 */
33 /* Redownload thumbnail files after a month */
34 var $fileCacheExpiry = 2592000; /* 86400*30 */
35 /* Local image directory */
39 protected $mQueryCache = array();
40 protected $mFileExists = array();
42 function __construct( $info ) {
43 parent
::__construct( $info );
44 global $wgUploadDirectory;
46 // http://commons.wikimedia.org/w/api.php
47 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
48 $this->directory
= isset( $info['directory'] ) ?
$info['directory'] : $wgUploadDirectory;
50 if( isset( $info['apiThumbCacheExpiry'] ) ) {
51 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
53 if( isset( $info['fileCacheExpiry'] ) ) {
54 $this->fileCacheExpiry
= $info['fileCacheExpiry'];
56 if( !$this->scriptDirUrl
) {
57 // hack for description fetches
58 $this->scriptDirUrl
= dirname( $this->mApiBase
);
60 // If we can cache thumbs we can guess sane defaults for these
61 if( $this->canCacheThumbs() && !$this->url
) {
62 global $wgLocalFileRepo;
63 $this->url
= $wgLocalFileRepo['url'];
65 if( $this->canCacheThumbs() && !$this->thumbUrl
) {
66 $this->thumbUrl
= $this->url
. '/thumb';
68 if ( isset( $info['thumbDir'] ) ) {
69 $this->thumbDir
= $info['thumbDir'];
71 $this->thumbDir
= "{$this->directory}/thumb";
76 * Per docs in FileRepo, this needs to return false if we don't support versioned
77 * files. Well, we don't.
81 function newFile( $title, $time = false ) {
85 return parent
::newFile( $title, $time );
92 function storeBatch( $triplets, $flags = 0 ) {
96 function storeTemp( $originalName, $srcPath ) {
100 function append( $srcPath, $toAppendPath, $flags = 0 ){
104 function appendFinish( $toAppendPath ){
108 function publishBatch( $triplets, $flags = 0 ) {
112 function deleteBatch( $sourceDestPairs ) {
116 function fileExistsBatch( $files, $flags = 0 ) {
118 foreach ( $files as $k => $f ) {
119 if ( isset( $this->mFileExists
[$k] ) ) {
122 } elseif( self
::isVirtualUrl( $f ) ) {
123 # @todo FIXME: We need to be able to handle virtual
124 # URLs better, at least when we know they refer to the
126 $results[$k] = false;
131 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
132 'prop' => 'imageinfo' ) );
133 if( isset( $data['query']['pages'] ) ) {
135 foreach( $files as $key => $file ) {
136 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
143 function getFileProps( $virtualUrl ) {
147 function fetchImageQuery( $query ) {
150 $query = array_merge( $query,
154 'redirects' => 'true'
156 if ( $this->mApiBase
) {
157 $url = wfAppendQuery( $this->mApiBase
, $query );
159 $url = $this->makeUrl( $query, 'api' );
162 if( !isset( $this->mQueryCache
[$url] ) ) {
163 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
164 $data = $wgMemc->get( $key );
166 $data = self
::httpGet( $url );
170 $wgMemc->set( $key, $data, 3600 );
173 if( count( $this->mQueryCache
) > 100 ) {
174 // Keep the cache from growing infinitely
175 $this->mQueryCache
= array();
177 $this->mQueryCache
[$url] = $data;
179 return FormatJson
::decode( $this->mQueryCache
[$url], true );
182 function getImageInfo( $data ) {
183 if( $data && isset( $data['query']['pages'] ) ) {
184 foreach( $data['query']['pages'] as $info ) {
185 if( isset( $info['imageinfo'][0] ) ) {
186 return $info['imageinfo'][0];
193 function findBySha1( $hash ) {
194 $results = $this->fetchImageQuery( array(
195 'aisha1base36' => $hash,
196 'aiprop' => ForeignAPIFile
::getProps(),
197 'list' => 'allimages', ) );
199 if ( isset( $results['query']['allimages'] ) ) {
200 foreach ( $results['query']['allimages'] as $img ) {
201 // 1.14 was broken, doesn't return name attribute
202 if( !isset( $img['name'] ) ) {
205 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
211 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
212 $data = $this->fetchImageQuery( array(
213 'titles' => 'File:' . $name,
214 'iiprop' => 'url|timestamp',
215 'iiurlwidth' => $width,
216 'iiurlheight' => $height,
217 'iiurlparam' => $otherParams,
218 'prop' => 'imageinfo' ) );
219 $info = $this->getImageInfo( $data );
221 if( $data && $info && isset( $info['thumburl'] ) ) {
222 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
224 return $info['thumburl'];
231 * Return the imageurl from cache if possible
233 * If the url has been requested today, get it from cache
234 * Otherwise retrieve remote thumb url, check for local file.
236 * @param $name String is a dbkey form of a title
239 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
241 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
244 if ( !$this->canCacheThumbs() ) {
245 $result = null; // can't pass "null" by reference, but it's ok as default value
246 return $this->getThumbUrl( $name, $width, $height, $result, $params );
248 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
249 $sizekey = "$width:$height:$params";
251 /* Get the array of urls that we already know */
252 $knownThumbUrls = $wgMemc->get($key);
253 if( !$knownThumbUrls ) {
254 /* No knownThumbUrls for this file */
255 $knownThumbUrls = array();
257 if( isset( $knownThumbUrls[$sizekey] ) ) {
258 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
259 "{$knownThumbUrls[$sizekey]} \n");
260 return $knownThumbUrls[$sizekey];
262 /* This size is not yet known */
266 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
269 wfDebug( __METHOD__
. " Could not find thumburl\n" );
273 // We need the same filename as the remote one :)
274 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
275 if( !$this->validateFilename( $fileName ) ) {
276 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
279 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
280 $localFilename = $localPath . "/" . $fileName;
281 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
283 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
284 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
285 $modified = filemtime( $localFilename );
286 $remoteModified = strtotime( $metadata['timestamp'] );
288 $diff = abs( $modified - $current );
289 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
290 /* Use our current and already downloaded thumbnail */
291 $knownThumbUrls[$sizekey] = $localUrl;
292 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
295 /* There is a new Commons file, or existing thumbnail older than a month */
297 $thumb = self
::httpGet( $foreignUrl );
299 wfDebug( __METHOD__
. " Could not download thumb\n" );
302 if ( !is_dir($localPath) ) {
303 if( !wfMkdirParents( $localPath, null, __METHOD__
) ) {
304 wfDebug( __METHOD__
. " could not create directory $localPath for thumb\n" );
309 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
310 wfSuppressWarnings();
311 if( !file_put_contents( $localFilename, $thumb ) ) {
313 wfDebug( __METHOD__
. " could not write to thumb path\n" );
317 $knownThumbUrls[$sizekey] = $localUrl;
318 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
319 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
324 * @see FileRepo::getZoneUrl()
326 function getZoneUrl( $zone ) {
331 return $this->thumbUrl
;
333 return parent
::getZoneUrl( $zone );
338 * Get the local directory corresponding to one of the three basic zones
340 function getZonePath( $zone ) {
343 return $this->directory
;
345 return $this->thumbDir
;
352 * Are we locally caching the thumbnails?
355 public function canCacheThumbs() {
356 return ( $this->apiThumbCacheExpiry
> 0 );
360 * The user agent the ForeignAPIRepo will use.
362 public static function getUserAgent() {
363 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
367 * Like a Http:get request, but with custom User-Agent.
370 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
371 $options['timeout'] = $timeout;
373 $url = wfExpandUrl( $url, PROTO_HTTP
);
374 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
375 $options['method'] = "GET";
377 if ( !isset( $options['timeout'] ) ) {
378 $options['timeout'] = 'default';
381 $req = MWHttpRequest
::factory( $url, $options );
382 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
383 $status = $req->execute();
385 if ( $status->isOK() ) {
386 return $req->getContent();