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.0";
30 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
31 /* Check back with Commons after a day */
32 var $apiThumbCacheExpiry = 86400;
33 /* Redownload thumbnail files after a month */
34 var $fileCacheExpiry = 2629743;
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.
79 function newFile( $title, $time = false ) {
83 return parent
::newFile( $title, $time );
89 function storeBatch( $triplets, $flags = 0 ) {
92 function storeTemp( $originalName, $srcPath ) {
95 function append( $srcPath, $toAppendPath, $flags = 0 ){
98 function publishBatch( $triplets, $flags = 0 ) {
101 function deleteBatch( $sourceDestPairs ) {
106 function fileExistsBatch( $files, $flags = 0 ) {
108 foreach ( $files as $k => $f ) {
109 if ( isset( $this->mFileExists
[$k] ) ) {
112 } elseif( self
::isVirtualUrl( $f ) ) {
113 # TODO! FIXME! We need to be able to handle virtual
114 # URLs better, at least when we know they refer to the
116 $results[$k] = false;
121 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
122 'prop' => 'imageinfo' ) );
123 if( isset( $data['query']['pages'] ) ) {
125 foreach( $files as $key => $file ) {
126 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
131 function getFileProps( $virtualUrl ) {
135 function fetchImageQuery( $query ) {
138 $query = array_merge( $query,
142 'redirects' => 'true'
144 if ( $this->mApiBase
) {
145 $url = wfAppendQuery( $this->mApiBase
, $query );
147 $url = $this->makeUrl( $query, 'api' );
150 if( !isset( $this->mQueryCache
[$url] ) ) {
151 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
152 $data = $wgMemc->get( $key );
154 $data = self
::httpGet( $url );
158 $wgMemc->set( $key, $data, 3600 );
161 if( count( $this->mQueryCache
) > 100 ) {
162 // Keep the cache from growing infinitely
163 $this->mQueryCache
= array();
165 $this->mQueryCache
[$url] = $data;
167 return FormatJson
::decode( $this->mQueryCache
[$url], true );
170 function getImageInfo( $data ) {
171 if( $data && isset( $data['query']['pages'] ) ) {
172 foreach( $data['query']['pages'] as $info ) {
173 if( isset( $info['imageinfo'][0] ) ) {
174 return $info['imageinfo'][0];
181 function findBySha1( $hash ) {
182 $results = $this->fetchImageQuery( array(
183 'aisha1base36' => $hash,
184 'aiprop' => ForeignAPIFile
::getProps(),
185 'list' => 'allimages', ) );
187 if ( isset( $results['query']['allimages'] ) ) {
188 foreach ( $results['query']['allimages'] as $img ) {
189 // 1.14 was broken, doesn't return name attribute
190 if( !isset( $img['name'] ) ) {
193 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
199 function getThumbUrl( $name, $width=-1, $height=-1, &$result=NULL ) {
200 $data = $this->fetchImageQuery( array(
201 'titles' => 'File:' . $name,
202 'iiprop' => 'url|timestamp',
203 'iiurlwidth' => $width,
204 'iiurlheight' => $height,
205 'prop' => 'imageinfo' ) );
206 $info = $this->getImageInfo( $data );
208 if( $data && $info && isset( $info['thumburl'] ) ) {
209 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
211 return $info['thumburl'];
218 * Return the imageurl from cache if possible
220 * If the url has been requested today, get it from cache
221 * Otherwise retrieve remote thumb url, check for local file.
223 * @param $name String is a dbkey form of a title
227 function getThumbUrlFromCache( $name, $width, $height ) {
230 if ( !$this->canCacheThumbs() ) {
231 return $this->getThumbUrl( $name, $width, $height );
233 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
234 $sizekey = "$width:$height";
236 /* Get the array of urls that we already know */
237 $knownThumbUrls = $wgMemc->get($key);
238 if( !$knownThumbUrls ) {
239 /* No knownThumbUrls for this file */
240 $knownThumbUrls = array();
242 if( isset( $knownThumbUrls[$sizekey] ) ) {
243 wfDebug("Got thumburl from local cache. {$knownThumbUrls[$sizekey]} \n");
244 return $knownThumbUrls[$sizekey];
246 /* This size is not yet known */
250 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata );
253 wfDebug( __METHOD__
. " Could not find thumburl\n" );
257 // We need the same filename as the remote one :)
258 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
259 if( !$this->validateFilename( $fileName ) ) {
260 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
263 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
264 $localFilename = $localPath . "/" . $fileName;
265 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
267 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
268 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
269 $modified = filemtime( $localFilename );
270 $remoteModified = strtotime( $metadata['timestamp'] );
272 $diff = abs( $modified - $current );
273 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
274 /* Use our current and already downloaded thumbnail */
275 $knownThumbUrls["$width:$height"] = $localUrl;
276 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
279 /* There is a new Commons file, or existing thumbnail older than a month */
281 $thumb = self
::httpGet( $foreignUrl );
283 wfDebug( __METHOD__
. " Could not download thumb\n" );
286 if ( !is_dir($localPath) ) {
287 if( !wfMkdirParents($localPath) ) {
288 wfDebug( __METHOD__
. " could not create directory $localPath for thumb\n" );
293 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
294 wfSuppressWarnings();
295 if( !file_put_contents( $localFilename, $thumb ) ) {
297 wfDebug( __METHOD__
. " could not write to thumb path\n" );
301 $knownThumbUrls[$sizekey] = $localUrl;
302 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
303 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
308 * @see FileRepo::getZoneUrl()
310 function getZoneUrl( $zone ) {
315 return $this->thumbUrl
;
317 return parent
::getZoneUrl( $zone );
322 * Get the local directory corresponding to one of the three basic zones
324 function getZonePath( $zone ) {
327 return $this->directory
;
329 return $this->thumbDir
;
336 * Are we locally caching the thumbnails?
339 public function canCacheThumbs() {
340 return ( $this->apiThumbCacheExpiry
> 0 );
344 * The user agent the ForeignAPIRepo will use.
346 public static function getUserAgent() {
347 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
351 * Like a Http:get request, but with custom User-Agent.
354 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
355 $options['timeout'] = $timeout;
357 $url = wfExpandUrl( $url );
358 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
359 $options['method'] = "GET";
361 if ( !isset( $options['timeout'] ) ) {
362 $options['timeout'] = 'default';
365 $req = MWHttpRequest
::factory( $url, $options );
366 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
367 $status = $req->execute();
369 if ( $status->isOK() ) {
370 return $req->getContent();