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 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
26 /* Check back with Commons after a day */
27 var $apiThumbCacheExpiry = 86400;
28 /* Redownload thumbnail files after a month */
29 var $fileCacheExpiry = 2629743;
30 /* Local image directory */
34 protected $mQueryCache = array();
35 protected $mFileExists = array();
37 function __construct( $info ) {
38 parent
::__construct( $info );
39 global $wgUploadDirectory;
41 // http://commons.wikimedia.org/w/api.php
42 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
43 $this->directory
= isset( $info['directory'] ) ?
$info['directory'] : $wgUploadDirectory;
45 if( isset( $info['apiThumbCacheExpiry'] ) ) {
46 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
48 if( isset( $info['fileCacheExpiry'] ) ) {
49 $this->fileCacheExpiry
= $info['fileCacheExpiry'];
51 if( !$this->scriptDirUrl
) {
52 // hack for description fetches
53 $this->scriptDirUrl
= dirname( $this->mApiBase
);
55 // If we can cache thumbs we can guess sane defaults for these
56 if( $this->canCacheThumbs() && !$this->url
) {
57 global $wgLocalFileRepo;
58 $this->url
= $wgLocalFileRepo['url'];
60 if( $this->canCacheThumbs() && !$this->thumbUrl
) {
61 $this->thumbUrl
= $this->url
. '/thumb';
63 if ( isset( $info['thumbDir'] ) ) {
64 $this->thumbDir
= $info['thumbDir'];
66 $this->thumbDir
= "{$this->directory}/thumb";
71 * Per docs in FileRepo, this needs to return false if we don't support versioned
72 * files. Well, we don't.
74 function newFile( $title, $time = false ) {
78 return parent
::newFile( $title, $time );
84 function storeBatch( $triplets, $flags = 0 ) {
87 function storeTemp( $originalName, $srcPath ) {
90 function append( $srcPath, $toAppendPath, $flags = 0 ){
93 function publishBatch( $triplets, $flags = 0 ) {
96 function deleteBatch( $sourceDestPairs ) {
101 function fileExistsBatch( $files, $flags = 0 ) {
103 foreach ( $files as $k => $f ) {
104 if ( isset( $this->mFileExists
[$k] ) ) {
107 } elseif( self
::isVirtualUrl( $f ) ) {
108 # TODO! FIXME! We need to be able to handle virtual
109 # URLs better, at least when we know they refer to the
111 $results[$k] = false;
116 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
117 'prop' => 'imageinfo' ) );
118 if( isset( $data['query']['pages'] ) ) {
120 foreach( $files as $key => $file ) {
121 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
126 function getFileProps( $virtualUrl ) {
130 function fetchImageQuery( $query ) {
133 $query = array_merge( $query,
137 'redirects' => 'true'
139 if ( $this->mApiBase
) {
140 $url = wfAppendQuery( $this->mApiBase
, $query );
142 $url = $this->makeUrl( $query, 'api' );
145 if( !isset( $this->mQueryCache
[$url] ) ) {
146 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
147 $data = $wgMemc->get( $key );
149 $data = Http
::get( $url );
153 $wgMemc->set( $key, $data, 3600 );
156 if( count( $this->mQueryCache
) > 100 ) {
157 // Keep the cache from growing infinitely
158 $this->mQueryCache
= array();
160 $this->mQueryCache
[$url] = $data;
162 return FormatJson
::decode( $this->mQueryCache
[$url], true );
165 function getImageInfo( $data ) {
166 if( $data && isset( $data['query']['pages'] ) ) {
167 foreach( $data['query']['pages'] as $info ) {
168 if( isset( $info['imageinfo'][0] ) ) {
169 return $info['imageinfo'][0];
176 function findBySha1( $hash ) {
177 $results = $this->fetchImageQuery( array(
178 'aisha1base36' => $hash,
179 'aiprop' => ForeignAPIFile
::getProps(),
180 'list' => 'allimages', ) );
182 if ( isset( $results['query']['allimages'] ) ) {
183 foreach ( $results['query']['allimages'] as $img ) {
184 // 1.14 was broken, doesn't return name attribute
185 if( !isset( $img['name'] ) ) {
188 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
194 function getThumbUrl( $name, $width=-1, $height=-1, &$result ) {
195 $data = $this->fetchImageQuery( array(
196 'titles' => 'File:' . $name,
197 'iiprop' => 'url|timestamp',
198 'iiurlwidth' => $width,
199 'iiurlheight' => $height,
200 'prop' => 'imageinfo' ) );
201 $info = $this->getImageInfo( $data );
203 if( $data && $info && isset( $info['thumburl'] ) ) {
204 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
206 return $info['thumburl'];
213 * Return the imageurl from cache if possible
215 * If the url has been requested today, get it from cache
216 * Otherwise retrieve remote thumb url, check for local file.
218 * @param $name String is a dbkey form of a title
222 function getThumbUrlFromCache( $name, $width, $height ) {
225 if ( !$this->canCacheThumbs() ) {
226 return $this->getThumbUrl( $name, $width, $height );
228 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name, $width );
230 $thumbUrl = $wgMemc->get($key);
232 wfDebug("Got thumb from local cache. $thumbUrl \n");
237 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata );
240 wfDebug( __METHOD__
. " Could not find thumburl\n" );
244 // We need the same filename as the remote one :)
245 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
246 if( !$this->validateFilename( $fileName ) ) {
247 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
250 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
251 $localFilename = $localPath . "/" . $fileName;
252 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . urlencode( $name ) . "/" . urlencode( $fileName );
254 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
255 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
256 $modified = filemtime( $localFilename );
257 $remoteModified = strtotime( $metadata['timestamp'] );
259 $diff = abs( $modified - $current );
260 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
261 /* Use our current and already downloaded thumbnail */
262 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry
);
265 /* There is a new Commons file, or existing thumbnail older than a month */
267 $thumb = Http
::get( $foreignUrl );
269 wfDebug( __METHOD__
. " Could not download thumb\n" );
272 if ( !is_dir($localPath) ) {
273 if( !wfMkdirParents($localPath) ) {
274 wfDebug( __METHOD__
. " could not create directory $localPath for thumb\n" );
279 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
280 wfSuppressWarnings();
281 if( !file_put_contents( $localFilename, $thumb ) ) {
283 wfDebug( __METHOD__
. " could not write to thumb path\n" );
287 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry
);
288 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
294 * @see FileRepo::getZoneUrl()
296 function getZoneUrl( $zone ) {
301 return $this->thumbUrl
;
303 return parent
::getZoneUrl( $zone );
308 * Get the local directory corresponding to one of the three basic zones
310 function getZonePath( $zone ) {
313 return $this->directory
;
315 return $this->thumbDir
;
322 * Are we locally caching the thumbnails?
325 public function canCacheThumbs() {
326 return ( $this->apiThumbCacheExpiry
> 0 );