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 */
36 protected $mQueryCache = array();
37 protected $mFileExists = array();
39 function __construct( $info ) {
40 global $wgLocalFileRepo;
41 parent
::__construct( $info );
43 // http://commons.wikimedia.org/w/api.php
44 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
46 if( isset( $info['apiThumbCacheExpiry'] ) ) {
47 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
49 if( isset( $info['fileCacheExpiry'] ) ) {
50 $this->fileCacheExpiry
= $info['fileCacheExpiry'];
52 if( !$this->scriptDirUrl
) {
53 // hack for description fetches
54 $this->scriptDirUrl
= dirname( $this->mApiBase
);
56 // If we can cache thumbs we can guess sane defaults for these
57 if( $this->canCacheThumbs() && !$this->url
) {
58 $this->url
= $wgLocalFileRepo['url'];
60 if( $this->canCacheThumbs() && !$this->thumbUrl
) {
61 $this->thumbUrl
= $this->url
. '/thumb';
66 * Per docs in FileRepo, this needs to return false if we don't support versioned
67 * files. Well, we don't.
71 function newFile( $title, $time = false ) {
75 return parent
::newFile( $title, $time );
83 function storeBatch( $triplets, $flags = 0 ) {
87 function storeTemp( $originalName, $srcPath ) {
91 function concatenate( $fileList, $targetPath, $flags = 0 ){
95 function append( $srcPath, $toAppendPath, $flags = 0 ){
99 function appendFinish( $toAppendPath ){
103 function publishBatch( $triplets, $flags = 0 ) {
107 function deleteBatch( $sourceDestPairs ) {
111 function fileExistsBatch( $files, $flags = 0 ) {
113 foreach ( $files as $k => $f ) {
114 if ( isset( $this->mFileExists
[$k] ) ) {
117 } elseif( self
::isVirtualUrl( $f ) ) {
118 # @todo FIXME: We need to be able to handle virtual
119 # URLs better, at least when we know they refer to the
121 $results[$k] = false;
126 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
127 'prop' => 'imageinfo' ) );
128 if( isset( $data['query']['pages'] ) ) {
130 foreach( $files as $key => $file ) {
131 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
138 function getFileProps( $virtualUrl ) {
142 function fetchImageQuery( $query ) {
145 $query = array_merge( $query,
149 'redirects' => 'true'
151 if ( $this->mApiBase
) {
152 $url = wfAppendQuery( $this->mApiBase
, $query );
154 $url = $this->makeUrl( $query, 'api' );
157 if( !isset( $this->mQueryCache
[$url] ) ) {
158 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
159 $data = $wgMemc->get( $key );
161 $data = self
::httpGet( $url );
165 $wgMemc->set( $key, $data, 3600 );
168 if( count( $this->mQueryCache
) > 100 ) {
169 // Keep the cache from growing infinitely
170 $this->mQueryCache
= array();
172 $this->mQueryCache
[$url] = $data;
174 return FormatJson
::decode( $this->mQueryCache
[$url], true );
177 function getImageInfo( $data ) {
178 if( $data && isset( $data['query']['pages'] ) ) {
179 foreach( $data['query']['pages'] as $info ) {
180 if( isset( $info['imageinfo'][0] ) ) {
181 return $info['imageinfo'][0];
188 function findBySha1( $hash ) {
189 $results = $this->fetchImageQuery( array(
190 'aisha1base36' => $hash,
191 'aiprop' => ForeignAPIFile
::getProps(),
192 'list' => 'allimages', ) );
194 if ( isset( $results['query']['allimages'] ) ) {
195 foreach ( $results['query']['allimages'] as $img ) {
196 // 1.14 was broken, doesn't return name attribute
197 if( !isset( $img['name'] ) ) {
200 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
206 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
207 $data = $this->fetchImageQuery( array(
208 'titles' => 'File:' . $name,
209 'iiprop' => 'url|timestamp',
210 'iiurlwidth' => $width,
211 'iiurlheight' => $height,
212 'iiurlparam' => $otherParams,
213 'prop' => 'imageinfo' ) );
214 $info = $this->getImageInfo( $data );
216 if( $data && $info && isset( $info['thumburl'] ) ) {
217 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
219 return $info['thumburl'];
226 * Return the imageurl from cache if possible
228 * If the url has been requested today, get it from cache
229 * Otherwise retrieve remote thumb url, check for local file.
231 * @param $name String is a dbkey form of a title
234 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
235 * @return bool|string
237 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
240 if ( !$this->canCacheThumbs() ) {
241 $result = null; // can't pass "null" by reference, but it's ok as default value
242 return $this->getThumbUrl( $name, $width, $height, $result, $params );
244 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
245 $sizekey = "$width:$height:$params";
247 /* Get the array of urls that we already know */
248 $knownThumbUrls = $wgMemc->get($key);
249 if( !$knownThumbUrls ) {
250 /* No knownThumbUrls for this file */
251 $knownThumbUrls = array();
253 if( isset( $knownThumbUrls[$sizekey] ) ) {
254 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
255 "{$knownThumbUrls[$sizekey]} \n");
256 return $knownThumbUrls[$sizekey];
258 /* This size is not yet known */
262 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
265 wfDebug( __METHOD__
. " Could not find thumburl\n" );
269 // We need the same filename as the remote one :)
270 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
271 if( !$this->validateFilename( $fileName ) ) {
272 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
275 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
276 $localFilename = $localPath . "/" . $fileName;
277 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
279 if( $this->fileExists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
280 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
281 $modified = $this->getFileTimestamp( $localFilename );
282 $remoteModified = strtotime( $metadata['timestamp'] );
284 $diff = abs( $modified - $current );
285 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
286 /* Use our current and already downloaded thumbnail */
287 $knownThumbUrls[$sizekey] = $localUrl;
288 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
291 /* There is a new Commons file, or existing thumbnail older than a month */
293 $thumb = self
::httpGet( $foreignUrl );
295 wfDebug( __METHOD__
. " Could not download thumb\n" );
299 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
300 wfSuppressWarnings();
301 $backend = $this->getBackend();
302 $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
303 if( !$backend->doOperation( $op )->isOK() ) {
305 wfDebug( __METHOD__
. " could not write to thumb path\n" );
309 $knownThumbUrls[$sizekey] = $localUrl;
310 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
311 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
316 * @see FileRepo::getZoneUrl()
319 function getZoneUrl( $zone ) {
324 return $this->thumbUrl
;
326 return parent
::getZoneUrl( $zone );
331 * Get the local directory corresponding to one of the basic zones
332 * @return bool|null|string
334 function getZonePath( $zone ) {
335 $supported = array( 'public', 'thumb' );
336 if ( in_array( $zone, $supported ) ) {
337 return parent
::getZonePath( $zone );
343 * Are we locally caching the thumbnails?
346 public function canCacheThumbs() {
347 return ( $this->apiThumbCacheExpiry
> 0 );
351 * The user agent the ForeignAPIRepo will use.
354 public static function getUserAgent() {
355 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
359 * Like a Http:get request, but with custom User-Agent.
361 * @return bool|String
363 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
364 $options['timeout'] = $timeout;
366 $url = wfExpandUrl( $url, PROTO_HTTP
);
367 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
368 $options['method'] = "GET";
370 if ( !isset( $options['timeout'] ) ) {
371 $options['timeout'] = 'default';
374 $req = MWHttpRequest
::factory( $url, $options );
375 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
376 $status = $req->execute();
378 if ( $status->isOK() ) {
379 return $req->getContent();
385 function enumFiles( $callback ) {
386 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );