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.
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 ) {
105 function fileExistsBatch( $files, $flags = 0 ) {
107 foreach ( $files as $k => $f ) {
108 if ( isset( $this->mFileExists
[$k] ) ) {
111 } elseif( self
::isVirtualUrl( $f ) ) {
112 # TODO! FIXME! We need to be able to handle virtual
113 # URLs better, at least when we know they refer to the
115 $results[$k] = false;
120 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
121 'prop' => 'imageinfo' ) );
122 if( isset( $data['query']['pages'] ) ) {
124 foreach( $files as $key => $file ) {
125 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
132 function getFileProps( $virtualUrl ) {
136 function fetchImageQuery( $query ) {
139 $query = array_merge( $query,
143 'redirects' => 'true'
145 if ( $this->mApiBase
) {
146 $url = wfAppendQuery( $this->mApiBase
, $query );
148 $url = $this->makeUrl( $query, 'api' );
151 if( !isset( $this->mQueryCache
[$url] ) ) {
152 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
153 $data = $wgMemc->get( $key );
155 $data = self
::httpGet( $url );
159 $wgMemc->set( $key, $data, 3600 );
162 if( count( $this->mQueryCache
) > 100 ) {
163 // Keep the cache from growing infinitely
164 $this->mQueryCache
= array();
166 $this->mQueryCache
[$url] = $data;
168 return FormatJson
::decode( $this->mQueryCache
[$url], true );
171 function getImageInfo( $data ) {
172 if( $data && isset( $data['query']['pages'] ) ) {
173 foreach( $data['query']['pages'] as $info ) {
174 if( isset( $info['imageinfo'][0] ) ) {
175 return $info['imageinfo'][0];
182 function findBySha1( $hash ) {
183 $results = $this->fetchImageQuery( array(
184 'aisha1base36' => $hash,
185 'aiprop' => ForeignAPIFile
::getProps(),
186 'list' => 'allimages', ) );
188 if ( isset( $results['query']['allimages'] ) ) {
189 foreach ( $results['query']['allimages'] as $img ) {
190 // 1.14 was broken, doesn't return name attribute
191 if( !isset( $img['name'] ) ) {
194 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
200 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
201 $data = $this->fetchImageQuery( array(
202 'titles' => 'File:' . $name,
203 'iiprop' => 'url|timestamp',
204 'iiurlwidth' => $width,
205 'iiurlheight' => $height,
206 'iiurlparam' => $otherParams,
207 'prop' => 'imageinfo' ) );
208 $info = $this->getImageInfo( $data );
210 if( $data && $info && isset( $info['thumburl'] ) ) {
211 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
213 return $info['thumburl'];
220 * Return the imageurl from cache if possible
222 * If the url has been requested today, get it from cache
223 * Otherwise retrieve remote thumb url, check for local file.
225 * @param $name String is a dbkey form of a title
228 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
230 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
233 if ( !$this->canCacheThumbs() ) {
234 $result = null; // can't pass "null" by reference, but it's ok as default value
235 return $this->getThumbUrl( $name, $width, $height, $result, $params );
237 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
238 $sizekey = "$width:$height:$params";
240 /* Get the array of urls that we already know */
241 $knownThumbUrls = $wgMemc->get($key);
242 if( !$knownThumbUrls ) {
243 /* No knownThumbUrls for this file */
244 $knownThumbUrls = array();
246 if( isset( $knownThumbUrls[$sizekey] ) ) {
247 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
248 "{$knownThumbUrls[$sizekey]} \n");
249 return $knownThumbUrls[$sizekey];
251 /* This size is not yet known */
255 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
258 wfDebug( __METHOD__
. " Could not find thumburl\n" );
262 // We need the same filename as the remote one :)
263 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
264 if( !$this->validateFilename( $fileName ) ) {
265 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
268 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
269 $localFilename = $localPath . "/" . $fileName;
270 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
272 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
273 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
274 $modified = filemtime( $localFilename );
275 $remoteModified = strtotime( $metadata['timestamp'] );
277 $diff = abs( $modified - $current );
278 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
279 /* Use our current and already downloaded thumbnail */
280 $knownThumbUrls[$sizekey] = $localUrl;
281 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
284 /* There is a new Commons file, or existing thumbnail older than a month */
286 $thumb = self
::httpGet( $foreignUrl );
288 wfDebug( __METHOD__
. " Could not download thumb\n" );
291 if ( !is_dir($localPath) ) {
292 if( !wfMkdirParents($localPath) ) {
293 wfDebug( __METHOD__
. " could not create directory $localPath for thumb\n" );
298 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
299 wfSuppressWarnings();
300 if( !file_put_contents( $localFilename, $thumb ) ) {
302 wfDebug( __METHOD__
. " could not write to thumb path\n" );
306 $knownThumbUrls[$sizekey] = $localUrl;
307 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
308 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
313 * @see FileRepo::getZoneUrl()
315 function getZoneUrl( $zone ) {
320 return $this->thumbUrl
;
322 return parent
::getZoneUrl( $zone );
327 * Get the local directory corresponding to one of the three basic zones
329 function getZonePath( $zone ) {
332 return $this->directory
;
334 return $this->thumbDir
;
341 * Are we locally caching the thumbnails?
344 public function canCacheThumbs() {
345 return ( $this->apiThumbCacheExpiry
> 0 );
349 * The user agent the ForeignAPIRepo will use.
351 public static function getUserAgent() {
352 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
356 * Like a Http:get request, but with custom User-Agent.
359 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
360 $options['timeout'] = $timeout;
362 $url = wfExpandUrl( $url );
363 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
364 $options['method'] = "GET";
366 if ( !isset( $options['timeout'] ) ) {
367 $options['timeout'] = 'default';
370 $req = MWHttpRequest
::factory( $url, $options );
371 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
372 $status = $req->execute();
374 if ( $status->isOK() ) {
375 return $req->getContent();