3 * Foreign repository accessible through api.php requests.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * A foreign repository with a remote MediaWiki with an API thingy
29 * $wgForeignFileRepos[] = array(
30 * 'class' => 'ForeignAPIRepo',
32 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
33 * 'fetchDescription' => true, // Optional
34 * 'descriptionCacheExpiry' => 3600,
39 class ForeignAPIRepo
extends FileRepo
{
40 /* This version string is used in the user agent for requests and will help
41 * server maintainers in identify ForeignAPI usage.
42 * Update the version every time you make breaking or significant changes. */
43 const VERSION
= "2.1";
45 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
46 /* Check back with Commons after a day */
47 var $apiThumbCacheExpiry = 86400; /* 24*60*60 */
48 /* Redownload thumbnail files after a month */
49 var $fileCacheExpiry = 2592000; /* 86400*30 */
51 protected $mQueryCache = array();
52 protected $mFileExists = array();
54 function __construct( $info ) {
55 global $wgLocalFileRepo;
56 parent
::__construct( $info );
58 // http://commons.wikimedia.org/w/api.php
59 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
61 if( isset( $info['apiThumbCacheExpiry'] ) ) {
62 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
64 if( isset( $info['fileCacheExpiry'] ) ) {
65 $this->fileCacheExpiry
= $info['fileCacheExpiry'];
67 if( !$this->scriptDirUrl
) {
68 // hack for description fetches
69 $this->scriptDirUrl
= dirname( $this->mApiBase
);
71 // If we can cache thumbs we can guess sane defaults for these
72 if( $this->canCacheThumbs() && !$this->url
) {
73 $this->url
= $wgLocalFileRepo['url'];
75 if( $this->canCacheThumbs() && !$this->thumbUrl
) {
76 $this->thumbUrl
= $this->url
. '/thumb';
81 * Per docs in FileRepo, this needs to return false if we don't support versioned
82 * files. Well, we don't.
86 function newFile( $title, $time = false ) {
90 return parent
::newFile( $title, $time );
93 function fileExistsBatch( array $files ) {
95 foreach ( $files as $k => $f ) {
96 if ( isset( $this->mFileExists
[$k] ) ) {
99 } elseif( self
::isVirtualUrl( $f ) ) {
100 # @todo FIXME: We need to be able to handle virtual
101 # URLs better, at least when we know they refer to the
103 $results[$k] = false;
105 } elseif ( FileBackend
::isStoragePath( $f ) ) {
106 $results[$k] = false;
108 wfWarn( "Got mwstore:// path '$f'." );
112 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
113 'prop' => 'imageinfo' ) );
114 if( isset( $data['query']['pages'] ) ) {
116 foreach( $files as $key => $file ) {
117 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
124 function getFileProps( $virtualUrl ) {
128 function fetchImageQuery( $query ) {
131 $query = array_merge( $query,
135 'redirects' => 'true'
137 if ( $this->mApiBase
) {
138 $url = wfAppendQuery( $this->mApiBase
, $query );
140 $url = $this->makeUrl( $query, 'api' );
143 if( !isset( $this->mQueryCache
[$url] ) ) {
144 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
145 $data = $wgMemc->get( $key );
147 $data = self
::httpGet( $url );
151 $wgMemc->set( $key, $data, 3600 );
154 if( count( $this->mQueryCache
) > 100 ) {
155 // Keep the cache from growing infinitely
156 $this->mQueryCache
= array();
158 $this->mQueryCache
[$url] = $data;
160 return FormatJson
::decode( $this->mQueryCache
[$url], true );
163 function getImageInfo( $data ) {
164 if( $data && isset( $data['query']['pages'] ) ) {
165 foreach( $data['query']['pages'] as $info ) {
166 if( isset( $info['imageinfo'][0] ) ) {
167 return $info['imageinfo'][0];
174 function findBySha1( $hash ) {
175 $results = $this->fetchImageQuery( array(
176 'aisha1base36' => $hash,
177 'aiprop' => ForeignAPIFile
::getProps(),
178 'list' => 'allimages', ) );
180 if ( isset( $results['query']['allimages'] ) ) {
181 foreach ( $results['query']['allimages'] as $img ) {
182 // 1.14 was broken, doesn't return name attribute
183 if( !isset( $img['name'] ) ) {
186 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
192 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
193 $data = $this->fetchImageQuery( array(
194 'titles' => 'File:' . $name,
195 'iiprop' => 'url|timestamp',
196 'iiurlwidth' => $width,
197 'iiurlheight' => $height,
198 'iiurlparam' => $otherParams,
199 'prop' => 'imageinfo' ) );
200 $info = $this->getImageInfo( $data );
202 if( $data && $info && isset( $info['thumburl'] ) ) {
203 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
205 return $info['thumburl'];
212 * Return the imageurl from cache if possible
214 * If the url has been requested today, get it from cache
215 * Otherwise retrieve remote thumb url, check for local file.
217 * @param $name String is a dbkey form of a title
220 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
221 * @return bool|string
223 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
225 // We can't check the local cache using FileRepo functions because
226 // we override fileExistsBatch(). We have to use the FileBackend directly.
227 $backend = $this->getBackend(); // convenience
229 if ( !$this->canCacheThumbs() ) {
230 $result = null; // can't pass "null" by reference, but it's ok as default value
231 return $this->getThumbUrl( $name, $width, $height, $result, $params );
233 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
234 $sizekey = "$width:$height:$params";
236 /* Get the array of urls that we already know */
237 $knownThumbUrls = $wgMemc->get($key);
238 if( !$knownThumbUrls ) {
239 /* No knownThumbUrls for this file */
240 $knownThumbUrls = array();
242 if( isset( $knownThumbUrls[$sizekey] ) ) {
243 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
244 "{$knownThumbUrls[$sizekey]} \n");
245 return $knownThumbUrls[$sizekey];
247 /* This size is not yet known */
251 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
254 wfDebug( __METHOD__
. " Could not find thumburl\n" );
258 // We need the same filename as the remote one :)
259 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
260 if( !$this->validateFilename( $fileName ) ) {
261 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
264 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
265 $localFilename = $localPath . "/" . $fileName;
266 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
268 if( $backend->fileExists( array( 'src' => $localFilename ) )
269 && isset( $metadata['timestamp'] ) )
271 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
272 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
273 $remoteModified = strtotime( $metadata['timestamp'] );
275 $diff = abs( $modified - $current );
276 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
277 /* Use our current and already downloaded thumbnail */
278 $knownThumbUrls[$sizekey] = $localUrl;
279 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
282 /* There is a new Commons file, or existing thumbnail older than a month */
284 $thumb = self
::httpGet( $foreignUrl );
286 wfDebug( __METHOD__
. " Could not download thumb\n" );
290 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
291 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
292 $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
293 if( !$backend->doOperation( $op )->isOK() ) {
295 wfDebug( __METHOD__
. " could not write to thumb path\n" );
298 $knownThumbUrls[$sizekey] = $localUrl;
299 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
300 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
305 * @see FileRepo::getZoneUrl()
308 function getZoneUrl( $zone ) {
313 return $this->thumbUrl
;
315 return parent
::getZoneUrl( $zone );
320 * Get the local directory corresponding to one of the basic zones
321 * @return bool|null|string
323 function getZonePath( $zone ) {
324 $supported = array( 'public', 'thumb' );
325 if ( in_array( $zone, $supported ) ) {
326 return parent
::getZonePath( $zone );
332 * Are we locally caching the thumbnails?
335 public function canCacheThumbs() {
336 return ( $this->apiThumbCacheExpiry
> 0 );
340 * The user agent the ForeignAPIRepo will use.
343 public static function getUserAgent() {
344 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
348 * Like a Http:get request, but with custom User-Agent.
350 * @return bool|String
352 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
353 $options['timeout'] = $timeout;
355 $url = wfExpandUrl( $url, PROTO_HTTP
);
356 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
357 $options['method'] = "GET";
359 if ( !isset( $options['timeout'] ) ) {
360 $options['timeout'] = 'default';
363 $req = MWHttpRequest
::factory( $url, $options );
364 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
365 $status = $req->execute();
367 if ( $status->isOK() ) {
368 return $req->getContent();
374 function enumFiles( $callback ) {
375 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
378 protected function assertWritableRepo() {
379 throw new MWException( get_class( $this ) . ': write operations are not supported.' );