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 );
78 function fileExistsBatch( array $files ) {
80 foreach ( $files as $k => $f ) {
81 if ( isset( $this->mFileExists
[$k] ) ) {
84 } elseif( self
::isVirtualUrl( $f ) ) {
85 # @todo FIXME: We need to be able to handle virtual
86 # URLs better, at least when we know they refer to the
90 } elseif ( FileBackend
::isStoragePath( $f ) ) {
93 wfWarn( "Got mwstore:// path '$f'." );
97 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
98 'prop' => 'imageinfo' ) );
99 if( isset( $data['query']['pages'] ) ) {
101 foreach( $files as $key => $file ) {
102 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
109 function getFileProps( $virtualUrl ) {
113 function fetchImageQuery( $query ) {
116 $query = array_merge( $query,
120 'redirects' => 'true'
122 if ( $this->mApiBase
) {
123 $url = wfAppendQuery( $this->mApiBase
, $query );
125 $url = $this->makeUrl( $query, 'api' );
128 if( !isset( $this->mQueryCache
[$url] ) ) {
129 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
130 $data = $wgMemc->get( $key );
132 $data = self
::httpGet( $url );
136 $wgMemc->set( $key, $data, 3600 );
139 if( count( $this->mQueryCache
) > 100 ) {
140 // Keep the cache from growing infinitely
141 $this->mQueryCache
= array();
143 $this->mQueryCache
[$url] = $data;
145 return FormatJson
::decode( $this->mQueryCache
[$url], true );
148 function getImageInfo( $data ) {
149 if( $data && isset( $data['query']['pages'] ) ) {
150 foreach( $data['query']['pages'] as $info ) {
151 if( isset( $info['imageinfo'][0] ) ) {
152 return $info['imageinfo'][0];
159 function findBySha1( $hash ) {
160 $results = $this->fetchImageQuery( array(
161 'aisha1base36' => $hash,
162 'aiprop' => ForeignAPIFile
::getProps(),
163 'list' => 'allimages', ) );
165 if ( isset( $results['query']['allimages'] ) ) {
166 foreach ( $results['query']['allimages'] as $img ) {
167 // 1.14 was broken, doesn't return name attribute
168 if( !isset( $img['name'] ) ) {
171 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
177 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
178 $data = $this->fetchImageQuery( array(
179 'titles' => 'File:' . $name,
180 'iiprop' => 'url|timestamp',
181 'iiurlwidth' => $width,
182 'iiurlheight' => $height,
183 'iiurlparam' => $otherParams,
184 'prop' => 'imageinfo' ) );
185 $info = $this->getImageInfo( $data );
187 if( $data && $info && isset( $info['thumburl'] ) ) {
188 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
190 return $info['thumburl'];
197 * Return the imageurl from cache if possible
199 * If the url has been requested today, get it from cache
200 * Otherwise retrieve remote thumb url, check for local file.
202 * @param $name String is a dbkey form of a title
205 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
206 * @return bool|string
208 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
210 // We can't check the local cache using FileRepo functions because
211 // we override fileExistsBatch(). We have to use the FileBackend directly.
212 $backend = $this->getBackend(); // convenience
214 if ( !$this->canCacheThumbs() ) {
215 $result = null; // can't pass "null" by reference, but it's ok as default value
216 return $this->getThumbUrl( $name, $width, $height, $result, $params );
218 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
219 $sizekey = "$width:$height:$params";
221 /* Get the array of urls that we already know */
222 $knownThumbUrls = $wgMemc->get($key);
223 if( !$knownThumbUrls ) {
224 /* No knownThumbUrls for this file */
225 $knownThumbUrls = array();
227 if( isset( $knownThumbUrls[$sizekey] ) ) {
228 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
229 "{$knownThumbUrls[$sizekey]} \n");
230 return $knownThumbUrls[$sizekey];
232 /* This size is not yet known */
236 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
239 wfDebug( __METHOD__
. " Could not find thumburl\n" );
243 // We need the same filename as the remote one :)
244 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
245 if( !$this->validateFilename( $fileName ) ) {
246 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
249 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
250 $localFilename = $localPath . "/" . $fileName;
251 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
253 if( $backend->fileExists( array( 'src' => $localFilename ) )
254 && isset( $metadata['timestamp'] ) )
256 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
257 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
258 $remoteModified = strtotime( $metadata['timestamp'] );
260 $diff = abs( $modified - $current );
261 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
262 /* Use our current and already downloaded thumbnail */
263 $knownThumbUrls[$sizekey] = $localUrl;
264 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
267 /* There is a new Commons file, or existing thumbnail older than a month */
269 $thumb = self
::httpGet( $foreignUrl );
271 wfDebug( __METHOD__
. " Could not download thumb\n" );
275 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
276 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
277 $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
278 if( !$backend->doOperation( $op )->isOK() ) {
280 wfDebug( __METHOD__
. " could not write to thumb path\n" );
283 $knownThumbUrls[$sizekey] = $localUrl;
284 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
285 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
290 * @see FileRepo::getZoneUrl()
293 function getZoneUrl( $zone ) {
298 return $this->thumbUrl
;
300 return parent
::getZoneUrl( $zone );
305 * Get the local directory corresponding to one of the basic zones
306 * @return bool|null|string
308 function getZonePath( $zone ) {
309 $supported = array( 'public', 'thumb' );
310 if ( in_array( $zone, $supported ) ) {
311 return parent
::getZonePath( $zone );
317 * Are we locally caching the thumbnails?
320 public function canCacheThumbs() {
321 return ( $this->apiThumbCacheExpiry
> 0 );
325 * The user agent the ForeignAPIRepo will use.
328 public static function getUserAgent() {
329 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
333 * Like a Http:get request, but with custom User-Agent.
335 * @return bool|String
337 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
338 $options['timeout'] = $timeout;
340 $url = wfExpandUrl( $url, PROTO_HTTP
);
341 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
342 $options['method'] = "GET";
344 if ( !isset( $options['timeout'] ) ) {
345 $options['timeout'] = 'default';
348 $req = MWHttpRequest
::factory( $url, $options );
349 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
350 $status = $req->execute();
352 if ( $status->isOK() ) {
353 return $req->getContent();
359 function enumFiles( $callback ) {
360 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
363 protected function assertWritableRepo() {
364 throw new MWException( get_class( $this ) . ': write operations are not supported.' );