thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / filerepo / ForeignAPIRepo.php
blob6b0bc3a608c5117dac9bc22f5bed7d116219acec
1 <?php
2 /**
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
20 * @file
21 * @ingroup FileRepo
24 /**
25 * A foreign repository with a remote MediaWiki with an API thingy
27 * Example config:
29 * $wgForeignFileRepos[] = array(
30 * 'class' => 'ForeignAPIRepo',
31 * 'name' => 'shared',
32 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
33 * 'fetchDescription' => true, // Optional
34 * 'descriptionCacheExpiry' => 3600,
35 * );
37 * @ingroup FileRepo
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 /**
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';
83 /**
84 * Per docs in FileRepo, this needs to return false if we don't support versioned
85 * files. Well, we don't.
87 * @param $title Title
88 * @param $time string|bool
89 * @return File
91 function newFile( $title, $time = false ) {
92 if ( $time ) {
93 return false;
95 return parent::newFile( $title, $time );
98 /**
99 * @param $files array
100 * @return array
102 function fileExistsBatch( array $files ) {
103 $results = array();
104 foreach ( $files as $k => $f ) {
105 if ( isset( $this->mFileExists[$k] ) ) {
106 $results[$k] = true;
107 unset( $files[$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
111 # same repo.
112 $results[$k] = false;
113 unset( $files[$k] );
114 } elseif ( FileBackend::isStoragePath( $f ) ) {
115 $results[$k] = false;
116 unset( $files[$k] );
117 wfWarn( "Got mwstore:// path '$f'." );
121 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
122 'prop' => 'imageinfo' ) );
123 if ( isset( $data['query']['pages'] ) ) {
124 $i = 0;
125 foreach ( $files as $key => $file ) {
126 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
127 $i++;
130 return $results;
134 * @param $virtualUrl string
135 * @return bool
137 function getFileProps( $virtualUrl ) {
138 return false;
142 * @param $query array
143 * @return string
145 function fetchImageQuery( $query ) {
146 global $wgMemc, $wgLanguageCode;
148 $query = array_merge( $query,
149 array(
150 'format' => 'json',
151 'action' => 'query',
152 'redirects' => 'true'
153 ) );
154 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
155 $query['uselang'] = $wgLanguageCode;
157 if ( $this->mApiBase ) {
158 $url = wfAppendQuery( $this->mApiBase, $query );
159 } else {
160 $url = $this->makeUrl( $query, 'api' );
163 if ( !isset( $this->mQueryCache[$url] ) ) {
164 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
165 $data = $wgMemc->get( $key );
166 if ( !$data ) {
167 $data = self::httpGet( $url );
168 if ( !$data ) {
169 return null;
171 $wgMemc->set( $key, $data, 3600 );
174 if ( count( $this->mQueryCache ) > 100 ) {
175 // Keep the cache from growing infinitely
176 $this->mQueryCache = array();
178 $this->mQueryCache[$url] = $data;
180 return FormatJson::decode( $this->mQueryCache[$url], true );
184 * @param $data array
185 * @return bool|array
187 function getImageInfo( $data ) {
188 if ( $data && isset( $data['query']['pages'] ) ) {
189 foreach ( $data['query']['pages'] as $info ) {
190 if ( isset( $info['imageinfo'][0] ) ) {
191 return $info['imageinfo'][0];
195 return false;
199 * @param $hash string
200 * @return array
202 function findBySha1( $hash ) {
203 $results = $this->fetchImageQuery( array(
204 'aisha1base36' => $hash,
205 'aiprop' => ForeignAPIFile::getProps(),
206 'list' => 'allimages',
207 ) );
208 $ret = array();
209 if ( isset( $results['query']['allimages'] ) ) {
210 foreach ( $results['query']['allimages'] as $img ) {
211 // 1.14 was broken, doesn't return name attribute
212 if ( !isset( $img['name'] ) ) {
213 continue;
215 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
218 return $ret;
222 * @param $name string
223 * @param $width int
224 * @param $height int
225 * @param $result null
226 * @param $otherParams string
227 * @return bool
229 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
230 $data = $this->fetchImageQuery( array(
231 'titles' => 'File:' . $name,
232 'iiprop' => 'url|timestamp',
233 'iiurlwidth' => $width,
234 'iiurlheight' => $height,
235 'iiurlparam' => $otherParams,
236 'prop' => 'imageinfo' ) );
237 $info = $this->getImageInfo( $data );
239 if ( $data && $info && isset( $info['thumburl'] ) ) {
240 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
241 $result = $info;
242 return $info['thumburl'];
243 } else {
244 return false;
249 * @param $name string
250 * @param $width int
251 * @param $height int
252 * @param $otherParams string
253 * @return bool|MediaTransformError
254 * @since 1.22
256 function getThumbError( $name, $width = -1, $height = -1, $otherParams = '', $lang = null ) {
257 $data = $this->fetchImageQuery( array(
258 'titles' => 'File:' . $name,
259 'iiprop' => 'url|timestamp',
260 'iiurlwidth' => $width,
261 'iiurlheight' => $height,
262 'iiurlparam' => $otherParams,
263 'prop' => 'imageinfo',
264 'uselang' => $lang,
265 ) );
266 $info = $this->getImageInfo( $data );
268 if( $data && $info && isset( $info['thumberror'] ) ) {
269 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] . "\n" );
270 return new MediaTransformError(
271 'thumbnail_error_remote',
272 $width,
273 $height,
274 $this->getDisplayName(),
275 $info['thumberror'] // already parsed message from foreign repo
277 } else {
278 return false;
283 * Return the imageurl from cache if possible
285 * If the url has been requested today, get it from cache
286 * Otherwise retrieve remote thumb url, check for local file.
288 * @param string $name is a dbkey form of a title
289 * @param $width
290 * @param $height
291 * @param string $params Other rendering parameters (page number, etc) from handler's makeParamString.
292 * @return bool|string
294 function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
295 global $wgMemc;
296 // We can't check the local cache using FileRepo functions because
297 // we override fileExistsBatch(). We have to use the FileBackend directly.
298 $backend = $this->getBackend(); // convenience
300 if ( !$this->canCacheThumbs() ) {
301 $result = null; // can't pass "null" by reference, but it's ok as default value
302 return $this->getThumbUrl( $name, $width, $height, $result, $params );
304 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
305 $sizekey = "$width:$height:$params";
307 /* Get the array of urls that we already know */
308 $knownThumbUrls = $wgMemc->get( $key );
309 if ( !$knownThumbUrls ) {
310 /* No knownThumbUrls for this file */
311 $knownThumbUrls = array();
312 } else {
313 if ( isset( $knownThumbUrls[$sizekey] ) ) {
314 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
315 "{$knownThumbUrls[$sizekey]} \n" );
316 return $knownThumbUrls[$sizekey];
318 /* This size is not yet known */
321 $metadata = null;
322 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
324 if ( !$foreignUrl ) {
325 wfDebug( __METHOD__ . " Could not find thumburl\n" );
326 return false;
329 // We need the same filename as the remote one :)
330 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
331 if ( !$this->validateFilename( $fileName ) ) {
332 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
333 return false;
335 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
336 $localFilename = $localPath . "/" . $fileName;
337 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
339 if ( $backend->fileExists( array( 'src' => $localFilename ) )
340 && isset( $metadata['timestamp'] ) ) {
341 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
342 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
343 $remoteModified = strtotime( $metadata['timestamp'] );
344 $current = time();
345 $diff = abs( $modified - $current );
346 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
347 /* Use our current and already downloaded thumbnail */
348 $knownThumbUrls[$sizekey] = $localUrl;
349 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
350 return $localUrl;
352 /* There is a new Commons file, or existing thumbnail older than a month */
354 $thumb = self::httpGet( $foreignUrl );
355 if ( !$thumb ) {
356 wfDebug( __METHOD__ . " Could not download thumb\n" );
357 return false;
360 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
361 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
362 $params = array( 'dst' => $localFilename, 'content' => $thumb );
363 if ( !$backend->quickCreate( $params )->isOK() ) {
364 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'\n" );
365 return $foreignUrl;
367 $knownThumbUrls[$sizekey] = $localUrl;
368 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
369 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
370 return $localUrl;
374 * @see FileRepo::getZoneUrl()
375 * @param $zone String
376 * @param string|null $ext Optional file extension
377 * @return String
379 function getZoneUrl( $zone, $ext = null ) {
380 switch ( $zone ) {
381 case 'public':
382 return $this->url;
383 case 'thumb':
384 return $this->thumbUrl;
385 default:
386 return parent::getZoneUrl( $zone, $ext );
391 * Get the local directory corresponding to one of the basic zones
392 * @param $zone string
393 * @return bool|null|string
395 function getZonePath( $zone ) {
396 $supported = array( 'public', 'thumb' );
397 if ( in_array( $zone, $supported ) ) {
398 return parent::getZonePath( $zone );
400 return false;
404 * Are we locally caching the thumbnails?
405 * @return bool
407 public function canCacheThumbs() {
408 return ( $this->apiThumbCacheExpiry > 0 );
412 * The user agent the ForeignAPIRepo will use.
413 * @return string
415 public static function getUserAgent() {
416 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
420 * Like a Http:get request, but with custom User-Agent.
421 * @see Http:get
422 * @param $url string
423 * @param $timeout string
424 * @param $options array
425 * @return bool|String
427 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
428 $options['timeout'] = $timeout;
429 /* Http::get */
430 $url = wfExpandUrl( $url, PROTO_HTTP );
431 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
432 $options['method'] = "GET";
434 if ( !isset( $options['timeout'] ) ) {
435 $options['timeout'] = 'default';
438 $req = MWHttpRequest::factory( $url, $options );
439 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
440 $status = $req->execute();
442 if ( $status->isOK() ) {
443 return $req->getContent();
444 } else {
445 return false;
450 * @param $callback Array|string
451 * @throws MWException
453 function enumFiles( $callback ) {
454 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
458 * @throws MWException
460 protected function assertWritableRepo() {
461 throw new MWException( get_class( $this ) . ': write operations are not supported.' );