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();
55 * @param $info array|null
57 function __construct( $info ) {
58 global $wgLocalFileRepo;
59 parent
::__construct( $info );
61 // http://commons.wikimedia.org/w/api.php
62 $this->mApiBase
= isset( $info['apibase'] ) ?
$info['apibase'] : null;
64 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
65 $this->apiThumbCacheExpiry
= $info['apiThumbCacheExpiry'];
67 if ( isset( $info['fileCacheExpiry'] ) ) {
68 $this->fileCacheExpiry
= $info['fileCacheExpiry'];
70 if ( !$this->scriptDirUrl
) {
71 // hack for description fetches
72 $this->scriptDirUrl
= dirname( $this->mApiBase
);
74 // If we can cache thumbs we can guess sane defaults for these
75 if ( $this->canCacheThumbs() && !$this->url
) {
76 $this->url
= $wgLocalFileRepo['url'];
78 if ( $this->canCacheThumbs() && !$this->thumbUrl
) {
79 $this->thumbUrl
= $this->url
. '/thumb';
84 * Per docs in FileRepo, this needs to return false if we don't support versioned
85 * files. Well, we don't.
88 * @param $time string|bool
91 function newFile( $title, $time = false ) {
95 return parent
::newFile( $title, $time );
102 function fileExistsBatch( array $files ) {
104 foreach ( $files as $k => $f ) {
105 if ( isset( $this->mFileExists
[$k] ) ) {
108 } elseif ( self
::isVirtualUrl( $f ) ) {
109 # @todo FIXME: We need to be able to handle virtual
110 # URLs better, at least when we know they refer to the
112 $results[$k] = false;
114 } elseif ( FileBackend
::isStoragePath( $f ) ) {
115 $results[$k] = false;
117 wfWarn( "Got mwstore:// path '$f'." );
121 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
122 'prop' => 'imageinfo' ) );
123 if ( isset( $data['query']['pages'] ) ) {
125 foreach ( $files as $key => $file ) {
126 $results[$key] = $this->mFileExists
[$key] = !isset( $data['query']['pages'][$i]['missing'] );
134 * @param $virtualUrl string
137 function getFileProps( $virtualUrl ) {
142 * @param $query array
145 function fetchImageQuery( $query ) {
148 $query = array_merge( $query,
152 'redirects' => 'true'
154 if ( $this->mApiBase
) {
155 $url = wfAppendQuery( $this->mApiBase
, $query );
157 $url = $this->makeUrl( $query, 'api' );
160 if ( !isset( $this->mQueryCache
[$url] ) ) {
161 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
162 $data = $wgMemc->get( $key );
164 $data = self
::httpGet( $url );
168 $wgMemc->set( $key, $data, 3600 );
171 if ( count( $this->mQueryCache
) > 100 ) {
172 // Keep the cache from growing infinitely
173 $this->mQueryCache
= array();
175 $this->mQueryCache
[$url] = $data;
177 return FormatJson
::decode( $this->mQueryCache
[$url], true );
184 function getImageInfo( $data ) {
185 if ( $data && isset( $data['query']['pages'] ) ) {
186 foreach ( $data['query']['pages'] as $info ) {
187 if ( isset( $info['imageinfo'][0] ) ) {
188 return $info['imageinfo'][0];
196 * @param $hash string
199 function findBySha1( $hash ) {
200 $results = $this->fetchImageQuery( array(
201 'aisha1base36' => $hash,
202 'aiprop' => ForeignAPIFile
::getProps(),
203 'list' => 'allimages',
206 if ( isset( $results['query']['allimages'] ) ) {
207 foreach ( $results['query']['allimages'] as $img ) {
208 // 1.14 was broken, doesn't return name attribute
209 if ( !isset( $img['name'] ) ) {
212 $ret[] = new ForeignAPIFile( Title
::makeTitle( NS_FILE
, $img['name'] ), $this, $img );
219 * @param $name string
222 * @param $result null
223 * @param $otherParams string
226 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
227 $data = $this->fetchImageQuery( array(
228 'titles' => 'File:' . $name,
229 'iiprop' => 'url|timestamp',
230 'iiurlwidth' => $width,
231 'iiurlheight' => $height,
232 'iiurlparam' => $otherParams,
233 'prop' => 'imageinfo' ) );
234 $info = $this->getImageInfo( $data );
236 if ( $data && $info && isset( $info['thumburl'] ) ) {
237 wfDebug( __METHOD__
. " got remote thumb " . $info['thumburl'] . "\n" );
239 return $info['thumburl'];
246 * Return the imageurl from cache if possible
248 * If the url has been requested today, get it from cache
249 * Otherwise retrieve remote thumb url, check for local file.
251 * @param string $name is a dbkey form of a title
254 * @param string $params Other rendering parameters (page number, etc) from handler's makeParamString.
255 * @return bool|string
257 function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
259 // We can't check the local cache using FileRepo functions because
260 // we override fileExistsBatch(). We have to use the FileBackend directly.
261 $backend = $this->getBackend(); // convenience
263 if ( !$this->canCacheThumbs() ) {
264 $result = null; // can't pass "null" by reference, but it's ok as default value
265 return $this->getThumbUrl( $name, $width, $height, $result, $params );
267 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
268 $sizekey = "$width:$height:$params";
270 /* Get the array of urls that we already know */
271 $knownThumbUrls = $wgMemc->get( $key );
272 if ( !$knownThumbUrls ) {
273 /* No knownThumbUrls for this file */
274 $knownThumbUrls = array();
276 if ( isset( $knownThumbUrls[$sizekey] ) ) {
277 wfDebug( __METHOD__
. ': Got thumburl from local cache: ' .
278 "{$knownThumbUrls[$sizekey]} \n" );
279 return $knownThumbUrls[$sizekey];
281 /* This size is not yet known */
285 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
287 if ( !$foreignUrl ) {
288 wfDebug( __METHOD__
. " Could not find thumburl\n" );
292 // We need the same filename as the remote one :)
293 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME
) );
294 if ( !$this->validateFilename( $fileName ) ) {
295 wfDebug( __METHOD__
. " The deduced filename $fileName is not safe\n" );
298 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
299 $localFilename = $localPath . "/" . $fileName;
300 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
302 if ( $backend->fileExists( array( 'src' => $localFilename ) )
303 && isset( $metadata['timestamp'] ) ) {
304 wfDebug( __METHOD__
. " Thumbnail was already downloaded before\n" );
305 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
306 $remoteModified = strtotime( $metadata['timestamp'] );
308 $diff = abs( $modified - $current );
309 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry
) {
310 /* Use our current and already downloaded thumbnail */
311 $knownThumbUrls[$sizekey] = $localUrl;
312 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
315 /* There is a new Commons file, or existing thumbnail older than a month */
317 $thumb = self
::httpGet( $foreignUrl );
319 wfDebug( __METHOD__
. " Could not download thumb\n" );
323 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
324 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
325 $params = array( 'dst' => $localFilename, 'content' => $thumb );
326 if ( !$backend->quickCreate( $params )->isOK() ) {
327 wfDebug( __METHOD__
. " could not write to thumb path '$localFilename'\n" );
330 $knownThumbUrls[$sizekey] = $localUrl;
331 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry
);
332 wfDebug( __METHOD__
. " got local thumb $localUrl, saving to cache \n" );
337 * @see FileRepo::getZoneUrl()
338 * @param $zone String
339 * @param string|null $ext Optional file extension
342 function getZoneUrl( $zone, $ext = null ) {
347 return $this->thumbUrl
;
349 return parent
::getZoneUrl( $zone, $ext );
354 * Get the local directory corresponding to one of the basic zones
355 * @param $zone string
356 * @return bool|null|string
358 function getZonePath( $zone ) {
359 $supported = array( 'public', 'thumb' );
360 if ( in_array( $zone, $supported ) ) {
361 return parent
::getZonePath( $zone );
367 * Are we locally caching the thumbnails?
370 public function canCacheThumbs() {
371 return ( $this->apiThumbCacheExpiry
> 0 );
375 * The user agent the ForeignAPIRepo will use.
378 public static function getUserAgent() {
379 return Http
::userAgent() . " ForeignAPIRepo/" . self
::VERSION
;
383 * Like a Http:get request, but with custom User-Agent.
386 * @param $timeout string
387 * @param $options array
388 * @return bool|String
390 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
391 $options['timeout'] = $timeout;
393 $url = wfExpandUrl( $url, PROTO_HTTP
);
394 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
395 $options['method'] = "GET";
397 if ( !isset( $options['timeout'] ) ) {
398 $options['timeout'] = 'default';
401 $req = MWHttpRequest
::factory( $url, $options );
402 $req->setUserAgent( ForeignAPIRepo
::getUserAgent() );
403 $status = $req->execute();
405 if ( $status->isOK() ) {
406 return $req->getContent();
413 * @param $callback Array|string
414 * @throws MWException
416 function enumFiles( $callback ) {
417 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
421 * @throws MWException
423 protected function assertWritableRepo() {
424 throw new MWException( get_class( $this ) . ': write operations are not supported.' );