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
93 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
94 'prop' => 'imageinfo' ) );
95 if( isset( $data['query']['pages'] ) ) {
97 foreach( $files as $key => $file ) {
98 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
105 function getFileProps( $virtualUrl ) {
109 function fetchImageQuery( $query ) {
112 $query = array_merge( $query,
116 'redirects' => 'true'
118 if ( $this->mApiBase
) {
119 $url = wfAppendQuery( $this->mApiBase
, $query );
121 $url = $this->makeUrl( $query, 'api' );
124 if( !isset( $this->mQueryCache
[$url] ) ) {
125 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
126 $data = $wgMemc->get( $key );
128 $data = self
::httpGet( $url );
132 $wgMemc->set( $key, $data, 3600 );
135 if( count( $this->mQueryCache
) > 100 ) {
136 // Keep the cache from growing infinitely
137 $this->mQueryCache
= array();
139 $this->mQueryCache
[$url] = $data;
141 return FormatJson
::decode( $this->mQueryCache
[$url], true );
144 function getImageInfo( $data ) {
145 if( $data && isset( $data['query']['pages'] ) ) {
146 foreach( $data['query']['pages'] as $info ) {
147 if( isset( $info['imageinfo'][0] ) ) {
148 return $info['imageinfo'][0];
155 function findBySha1( $hash ) {
156 $results = $this->fetchImageQuery( array(
157 'aisha1base36' => $hash,
158 'aiprop' => ForeignAPIFile
::getProps(),
159 'list' => 'allimages', ) );
161 if ( isset( $results['query']['allimages'] ) ) {
162 foreach ( $results['query']['allimages'] as $img ) {
163 // 1.14 was broken, doesn't return name attribute
164 if( !isset( $img['name'] ) ) {
167 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
173 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
174 $data = $this->fetchImageQuery( array(
175 'titles' => 'File:' . $name,
176 'iiprop' => 'url|timestamp',
177 'iiurlwidth' => $width,
178 'iiurlheight' => $height,
179 'iiurlparam' => $otherParams,
180 'prop' => 'imageinfo' ) );
181 $info = $this->getImageInfo( $data );
183 if( $data && $info && isset( $info['thumburl'] ) ) {
184 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
186 return $info['thumburl'];
193 * Return the imageurl from cache if possible
195 * If the url has been requested today, get it from cache
196 * Otherwise retrieve remote thumb url, check for local file.
198 * @param $name String is a dbkey form of a title
201 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
202 * @return bool|string
204 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
207 if ( !$this->canCacheThumbs() ) {
208 $result = null; // can't pass "null" by reference, but it's ok as default value
209 return $this->getThumbUrl( $name, $width, $height, $result, $params );
211 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
212 $sizekey = "$width:$height:$params";
214 /* Get the array of urls that we already know */
215 $knownThumbUrls = $wgMemc->get($key);
216 if( !$knownThumbUrls ) {
217 /* No knownThumbUrls for this file */
218 $knownThumbUrls = array();
220 if( isset( $knownThumbUrls[$sizekey] ) ) {
221 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
222 "{$knownThumbUrls[$sizekey]} \n");
223 return $knownThumbUrls[$sizekey];
225 /* This size is not yet known */
229 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
232 wfDebug( __METHOD__
. " Could not find thumburl\n" );
236 // We need the same filename as the remote one :)
237 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
238 if( !$this->validateFilename( $fileName ) ) {
239 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
242 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
243 $localFilename = $localPath . "/" . $fileName;
244 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
246 if( $this->fileExists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
247 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
248 $modified = $this->getFileTimestamp( $localFilename );
249 $remoteModified = strtotime( $metadata['timestamp'] );
251 $diff = abs( $modified - $current );
252 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
253 /* Use our current and already downloaded thumbnail */
254 $knownThumbUrls[$sizekey] = $localUrl;
255 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
258 /* There is a new Commons file, or existing thumbnail older than a month */
260 $thumb = self
::httpGet( $foreignUrl );
262 wfDebug( __METHOD__
. " Could not download thumb\n" );
266 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
267 wfSuppressWarnings();
268 $backend = $this->getBackend();
269 $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
270 if( !$backend->doOperation( $op )->isOK() ) {
272 wfDebug( __METHOD__
. " could not write to thumb path\n" );
276 $knownThumbUrls[$sizekey] = $localUrl;
277 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
278 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
283 * @see FileRepo::getZoneUrl()
286 function getZoneUrl( $zone ) {
291 return $this->thumbUrl
;
293 return parent
::getZoneUrl( $zone );
298 * Get the local directory corresponding to one of the basic zones
299 * @return bool|null|string
301 function getZonePath( $zone ) {
302 $supported = array( 'public', 'thumb' );
303 if ( in_array( $zone, $supported ) ) {
304 return parent
::getZonePath( $zone );
310 * Are we locally caching the thumbnails?
313 public function canCacheThumbs() {
314 return ( $this->apiThumbCacheExpiry
> 0 );
318 * The user agent the ForeignAPIRepo will use.
321 public static function getUserAgent() {
322 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
326 * Like a Http:get request, but with custom User-Agent.
328 * @return bool|String
330 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
331 $options['timeout'] = $timeout;
333 $url = wfExpandUrl( $url, PROTO_HTTP
);
334 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
335 $options['method'] = "GET";
337 if ( !isset( $options['timeout'] ) ) {
338 $options['timeout'] = 'default';
341 $req = MWHttpRequest
::factory( $url, $options );
342 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
343 $status = $req->execute();
345 if ( $status->isOK() ) {
346 return $req->getContent();
352 function enumFiles( $callback ) {
353 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
356 protected function assertWritableRepo() {
357 throw new MWException( get_class( $this ) . ': write operations are not supported.' );