3 * Foreign repository accessible through api.php requests.
10 * A foreign repository with a remote MediaWiki with an API thingy
11 * Very hacky and inefficient
12 * do not use except for testing :D
16 * $wgForeignFileRepos[] = array(
17 * 'class' => 'ForeignAPIRepo',
19 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
20 * 'fetchDescription' => true, // Optional
21 * 'descriptionCacheExpiry' => 3600,
26 class ForeignAPIRepo
extends FileRepo
{
27 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
28 /* Check back with Commons after a day */
29 var $apiThumbCacheExpiry = 86400;
30 /* Redownload thumbnail files after a month */
31 var $fileCacheExpiry = 2629743;
33 protected $mQueryCache = array();
34 protected $mFileExists = array();
36 function __construct( $info ) {
37 parent
::__construct( $info );
39 // http://commons.wikimedia.org/w/api.php
40 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
42 if( isset( $info['apiThumbCacheExpiry'] ) ) {
43 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
45 if( !$this->scriptDirUrl
) {
46 // hack for description fetches
47 $this->scriptDirUrl
= dirname( $this->mApiBase
);
49 // If we can cache thumbs we can guess sane defaults for these
50 if( $this->canCacheThumbs() && !$this->url
) {
51 global $wgLocalFileRepo;
52 $this->url
= $wgLocalFileRepo['url'];
54 if( $this->canCacheThumbs() && !$this->thumbUrl
) {
55 $this->thumbUrl
= $this->url
. '/thumb';
60 * Per docs in FileRepo, this needs to return false if we don't support versioned
61 * files. Well, we don't.
63 function newFile( $title, $time = false ) {
67 return parent
::newFile( $title, $time );
73 function storeBatch( $triplets, $flags = 0 ) {
76 function storeTemp( $originalName, $srcPath ) {
79 function append( $srcPath, $toAppendPath, $flags = 0 ){
82 function publishBatch( $triplets, $flags = 0 ) {
85 function deleteBatch( $sourceDestPairs ) {
90 function fileExistsBatch( $files, $flags = 0 ) {
92 foreach ( $files as $k => $f ) {
93 if ( isset( $this->mFileExists
[$k] ) ) {
96 } elseif( self
::isVirtualUrl( $f ) ) {
97 # TODO! FIXME! We need to be able to handle virtual
98 # URLs better, at least when we know they refer to the
100 $results[$k] = false;
105 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
106 'prop' => 'imageinfo' ) );
107 if( isset( $data['query']['pages'] ) ) {
109 foreach( $files as $key => $file ) {
110 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
115 function getFileProps( $virtualUrl ) {
119 function fetchImageQuery( $query ) {
122 $query = array_merge( $query,
126 'redirects' => 'true'
128 if ( $this->mApiBase
) {
129 $url = wfAppendQuery( $this->mApiBase
, $query );
131 $url = $this->makeUrl( $query, 'api' );
134 if( !isset( $this->mQueryCache
[$url] ) ) {
135 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
136 $data = $wgMemc->get( $key );
138 $data = Http
::get( $url );
142 $wgMemc->set( $key, $data, 3600 );
145 if( count( $this->mQueryCache
) > 100 ) {
146 // Keep the cache from growing infinitely
147 $this->mQueryCache
= array();
149 $this->mQueryCache
[$url] = $data;
151 return FormatJson
::decode( $this->mQueryCache
[$url], true );
154 function getImageInfo( $data ) {
155 if( $data && isset( $data['query']['pages'] ) ) {
156 foreach( $data['query']['pages'] as $info ) {
157 if( isset( $info['imageinfo'][0] ) ) {
158 return $info['imageinfo'][0];
165 function findBySha1( $hash ) {
166 $results = $this->fetchImageQuery( array(
167 'aisha1base36' => $hash,
168 'aiprop' => ForeignAPIFile
::getProps(),
169 'list' => 'allimages', ) );
171 if ( isset( $results['query']['allimages'] ) ) {
172 foreach ( $results['query']['allimages'] as $img ) {
173 // 1.14 was broken, doesn't return name attribute
174 if( !isset( $img['name'] ) ) {
177 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
183 function getThumbUrl( $name, $width=-1, $height=-1, &$result ) {
184 $data = $this->fetchImageQuery( array(
185 'titles' => 'File:' . $name,
186 'iiprop' => 'url|timestamp',
187 'iiurlwidth' => $width,
188 'iiurlheight' => $height,
189 'prop' => 'imageinfo' ) );
190 $info = $this->getImageInfo( $data );
192 if( $data && $info && isset( $info['thumburl'] ) ) {
193 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
195 return $info['thumburl'];
202 * Return the imageurl from cache if possible
204 * If the url has been requested today, get it from cache
205 * Otherwise retrieve remote thumb url, check for local file.
207 * @param $name String is a dbkey form of a title
211 function getThumbUrlFromCache( $name, $width, $height ) {
212 global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
214 if ( !$this->canCacheThumbs() ) {
215 return $this->getThumbUrl( $name, $width, $height );
218 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name, $width );
220 $thumbUrl = $wgMemc->get($key);
222 wfDebug("Got thumb from local cache. $thumbUrl \n");
227 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata );
228 // We need the same filename as the remote one :)
229 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
230 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
231 $localFilename = $wgUploadDirectory . '/' . $path . $fileName;
232 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
235 wfDebug( __METHOD__
. " Could not find thumburl\n" );
238 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
239 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
240 $modified = filemtime( $localFilename );
241 $remoteModified = strtotime( $metadata['timestamp'] );
242 $diff = abs( $modified - $remoteModified );
243 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
244 /* Use our current already downloaded thumbnail */
245 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry
);
248 /* There is a new Commons file, or existing thumbnail older than a month */
251 $thumb = Http
::get( $foreignUrl );
253 wfDebug( __METHOD__
. " Could not download thumb\n" );
256 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
257 if( !wfMkdirParents($wgUploadDirectory . '/' . $path) ) {
258 wfDebug( __METHOD__
. " could not create directory for thumb\n" );
263 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
264 wfSuppressWarnings();
265 if( !file_put_contents($localFilename, $thumb ) ) {
267 wfDebug( __METHOD__
. " could not write to thumb path\n" );
271 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry
);
272 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
278 * @see FileRepo::getZoneUrl()
280 function getZoneUrl( $zone ) {
285 return $this->thumbUrl
;
287 return parent
::getZoneUrl( $zone );
292 * Are we locally caching the thumbnails?
295 public function canCacheThumbs() {
296 return ( $this->apiThumbCacheExpiry
> 0 );