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 concatenate( $fileList, $targetPath, $flags = 0 ){
104 function append( $srcPath, $toAppendPath, $flags = 0 ){
108 function appendFinish( $toAppendPath ){
112 function publishBatch( $triplets, $flags = 0 ) {
116 function deleteBatch( $sourceDestPairs ) {
120 function fileExistsBatch( $files, $flags = 0 ) {
122 foreach ( $files as $k => $f ) {
123 if ( isset( $this->mFileExists
[$k] ) ) {
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;
135 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
136 'prop' => 'imageinfo' ) );
137 if( isset( $data['query']['pages'] ) ) {
139 foreach( $files as $key => $file ) {
140 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
147 function getFileProps( $virtualUrl ) {
151 function fetchImageQuery( $query ) {
154 $query = array_merge( $query,
158 'redirects' => 'true'
160 if ( $this->mApiBase
) {
161 $url = wfAppendQuery( $this->mApiBase
, $query );
163 $url = $this->makeUrl( $query, 'api' );
166 if( !isset( $this->mQueryCache
[$url] ) ) {
167 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
168 $data = $wgMemc->get( $key );
170 $data = self
::httpGet( $url );
174 $wgMemc->set( $key, $data, 3600 );
177 if( count( $this->mQueryCache
) > 100 ) {
178 // Keep the cache from growing infinitely
179 $this->mQueryCache
= array();
181 $this->mQueryCache
[$url] = $data;
183 return FormatJson
::decode( $this->mQueryCache
[$url], true );
186 function getImageInfo( $data ) {
187 if( $data && isset( $data['query']['pages'] ) ) {
188 foreach( $data['query']['pages'] as $info ) {
189 if( isset( $info['imageinfo'][0] ) ) {
190 return $info['imageinfo'][0];
197 function findBySha1( $hash ) {
198 $results = $this->fetchImageQuery( array(
199 'aisha1base36' => $hash,
200 'aiprop' => ForeignAPIFile
::getProps(),
201 'list' => 'allimages', ) );
203 if ( isset( $results['query']['allimages'] ) ) {
204 foreach ( $results['query']['allimages'] as $img ) {
205 // 1.14 was broken, doesn't return name attribute
206 if( !isset( $img['name'] ) ) {
209 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
215 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
216 $data = $this->fetchImageQuery( array(
217 'titles' => 'File:' . $name,
218 'iiprop' => 'url|timestamp',
219 'iiurlwidth' => $width,
220 'iiurlheight' => $height,
221 'iiurlparam' => $otherParams,
222 'prop' => 'imageinfo' ) );
223 $info = $this->getImageInfo( $data );
225 if( $data && $info && isset( $info['thumburl'] ) ) {
226 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
228 return $info['thumburl'];
235 * Return the imageurl from cache if possible
237 * If the url has been requested today, get it from cache
238 * Otherwise retrieve remote thumb url, check for local file.
240 * @param $name String is a dbkey form of a title
243 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
245 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
248 if ( !$this->canCacheThumbs() ) {
249 $result = null; // can't pass "null" by reference, but it's ok as default value
250 return $this->getThumbUrl( $name, $width, $height, $result, $params );
252 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
253 $sizekey = "$width:$height:$params";
255 /* Get the array of urls that we already know */
256 $knownThumbUrls = $wgMemc->get($key);
257 if( !$knownThumbUrls ) {
258 /* No knownThumbUrls for this file */
259 $knownThumbUrls = array();
261 if( isset( $knownThumbUrls[$sizekey] ) ) {
262 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
263 "{$knownThumbUrls[$sizekey]} \n");
264 return $knownThumbUrls[$sizekey];
266 /* This size is not yet known */
270 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
273 wfDebug( __METHOD__
. " Could not find thumburl\n" );
277 // We need the same filename as the remote one :)
278 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
279 if( !$this->validateFilename( $fileName ) ) {
280 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
283 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
284 $localFilename = $localPath . "/" . $fileName;
285 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
287 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
288 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
289 $modified = filemtime( $localFilename );
290 $remoteModified = strtotime( $metadata['timestamp'] );
292 $diff = abs( $modified - $current );
293 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
294 /* Use our current and already downloaded thumbnail */
295 $knownThumbUrls[$sizekey] = $localUrl;
296 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
299 /* There is a new Commons file, or existing thumbnail older than a month */
301 $thumb = self
::httpGet( $foreignUrl );
303 wfDebug( __METHOD__
. " Could not download thumb\n" );
306 if ( !is_dir($localPath) ) {
307 if( !wfMkdirParents( $localPath, null, __METHOD__
) ) {
308 wfDebug( __METHOD__
. " could not create directory $localPath for thumb\n" );
313 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
314 wfSuppressWarnings();
315 if( !file_put_contents( $localFilename, $thumb ) ) {
317 wfDebug( __METHOD__
. " could not write to thumb path\n" );
321 $knownThumbUrls[$sizekey] = $localUrl;
322 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
323 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
328 * @see FileRepo::getZoneUrl()
330 function getZoneUrl( $zone ) {
335 return $this->thumbUrl
;
337 return parent
::getZoneUrl( $zone );
342 * Get the local directory corresponding to one of the three basic zones
344 function getZonePath( $zone ) {
347 return $this->directory
;
349 return $this->thumbDir
;
356 * Are we locally caching the thumbnails?
359 public function canCacheThumbs() {
360 return ( $this->apiThumbCacheExpiry
> 0 );
364 * The user agent the ForeignAPIRepo will use.
366 public static function getUserAgent() {
367 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
371 * Like a Http:get request, but with custom User-Agent.
374 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
375 $options['timeout'] = $timeout;
377 $url = wfExpandUrl( $url, PROTO_HTTP
);
378 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
379 $options['method'] = "GET";
381 if ( !isset( $options['timeout'] ) ) {
382 $options['timeout'] = 'default';
385 $req = MWHttpRequest
::factory( $url, $options );
386 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
387 $status = $req->execute();
389 if ( $status->isOK() ) {
390 return $req->getContent();