Merge "tests: remove date from @author docs statements"
[lhc/web/wiklou.git] / includes / filerepo / ForeignAPIRepo.php
1 <?php
2 /**
3 * Foreign repository accessible through api.php requests.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup FileRepo
22 */
23
24 /**
25 * A foreign repository with a remote MediaWiki with an API thingy
26 *
27 * Example config:
28 *
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 * );
36 *
37 * @ingroup FileRepo
38 */
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";
44
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 */
50
51 protected $mQueryCache = array();
52 protected $mFileExists = array();
53
54 /**
55 * @param $info array|null
56 */
57 function __construct( $info ) {
58 global $wgLocalFileRepo;
59 parent::__construct( $info );
60
61 // http://commons.wikimedia.org/w/api.php
62 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
63
64 if ( isset( $info['apiThumbCacheExpiry'] ) ) {
65 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
66 }
67 if ( isset( $info['fileCacheExpiry'] ) ) {
68 $this->fileCacheExpiry = $info['fileCacheExpiry'];
69 }
70 if ( !$this->scriptDirUrl ) {
71 // hack for description fetches
72 $this->scriptDirUrl = dirname( $this->mApiBase );
73 }
74 // If we can cache thumbs we can guess sane defaults for these
75 if ( $this->canCacheThumbs() && !$this->url ) {
76 $this->url = $wgLocalFileRepo['url'];
77 }
78 if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
79 $this->thumbUrl = $this->url . '/thumb';
80 }
81 }
82
83 /**
84 * @return string
85 * @since 1.22
86 */
87 function getApiUrl() {
88 return $this->mApiBase;
89 }
90
91 /**
92 * Per docs in FileRepo, this needs to return false if we don't support versioned
93 * files. Well, we don't.
94 *
95 * @param $title Title
96 * @param $time string|bool
97 * @return File
98 */
99 function newFile( $title, $time = false ) {
100 if ( $time ) {
101 return false;
102 }
103 return parent::newFile( $title, $time );
104 }
105
106 /**
107 * @param $files array
108 * @return array
109 */
110 function fileExistsBatch( array $files ) {
111 $results = array();
112 foreach ( $files as $k => $f ) {
113 if ( isset( $this->mFileExists[$k] ) ) {
114 $results[$k] = true;
115 unset( $files[$k] );
116 } elseif ( self::isVirtualUrl( $f ) ) {
117 # @todo FIXME: We need to be able to handle virtual
118 # URLs better, at least when we know they refer to the
119 # same repo.
120 $results[$k] = false;
121 unset( $files[$k] );
122 } elseif ( FileBackend::isStoragePath( $f ) ) {
123 $results[$k] = false;
124 unset( $files[$k] );
125 wfWarn( "Got mwstore:// path '$f'." );
126 }
127 }
128
129 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
130 'prop' => 'imageinfo' ) );
131 if ( isset( $data['query']['pages'] ) ) {
132 $i = 0;
133 foreach ( $files as $key => $file ) {
134 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
135 $i++;
136 }
137 }
138 return $results;
139 }
140
141 /**
142 * @param $virtualUrl string
143 * @return bool
144 */
145 function getFileProps( $virtualUrl ) {
146 return false;
147 }
148
149 /**
150 * @param $query array
151 * @return string
152 */
153 function fetchImageQuery( $query ) {
154 global $wgMemc, $wgLanguageCode;
155
156 $query = array_merge( $query,
157 array(
158 'format' => 'json',
159 'action' => 'query',
160 'redirects' => 'true'
161 ) );
162
163 if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
164 $query['uselang'] = $wgLanguageCode;
165 }
166
167 $data = $this->httpGetCached( 'Metadata', $query );
168
169 if ( $data ) {
170 return FormatJson::decode( $data, true );
171 } else {
172 return null;
173 }
174 }
175
176 /**
177 * @param $data array
178 * @return bool|array
179 */
180 function getImageInfo( $data ) {
181 if ( $data && isset( $data['query']['pages'] ) ) {
182 foreach ( $data['query']['pages'] as $info ) {
183 if ( isset( $info['imageinfo'][0] ) ) {
184 return $info['imageinfo'][0];
185 }
186 }
187 }
188 return false;
189 }
190
191 /**
192 * @param $hash string
193 * @return array
194 */
195 function findBySha1( $hash ) {
196 $results = $this->fetchImageQuery( array(
197 'aisha1base36' => $hash,
198 'aiprop' => ForeignAPIFile::getProps(),
199 'list' => 'allimages',
200 ) );
201 $ret = array();
202 if ( isset( $results['query']['allimages'] ) ) {
203 foreach ( $results['query']['allimages'] as $img ) {
204 // 1.14 was broken, doesn't return name attribute
205 if ( !isset( $img['name'] ) ) {
206 continue;
207 }
208 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
209 }
210 }
211 return $ret;
212 }
213
214 /**
215 * @param $name string
216 * @param $width int
217 * @param $height int
218 * @param $result null
219 * @param $otherParams string
220 * @return bool
221 */
222 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
223 $data = $this->fetchImageQuery( array(
224 'titles' => 'File:' . $name,
225 'iiprop' => 'url|timestamp',
226 'iiurlwidth' => $width,
227 'iiurlheight' => $height,
228 'iiurlparam' => $otherParams,
229 'prop' => 'imageinfo' ) );
230 $info = $this->getImageInfo( $data );
231
232 if ( $data && $info && isset( $info['thumburl'] ) ) {
233 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
234 $result = $info;
235 return $info['thumburl'];
236 } else {
237 return false;
238 }
239 }
240
241 /**
242 * @param $name string
243 * @param $width int
244 * @param $height int
245 * @param $otherParams string
246 * @return bool|MediaTransformError
247 * @since 1.22
248 */
249 function getThumbError( $name, $width = -1, $height = -1, $otherParams = '', $lang = null ) {
250 $data = $this->fetchImageQuery( array(
251 'titles' => 'File:' . $name,
252 'iiprop' => 'url|timestamp',
253 'iiurlwidth' => $width,
254 'iiurlheight' => $height,
255 'iiurlparam' => $otherParams,
256 'prop' => 'imageinfo',
257 'uselang' => $lang,
258 ) );
259 $info = $this->getImageInfo( $data );
260
261 if ( $data && $info && isset( $info['thumberror'] ) ) {
262 wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] . "\n" );
263 return new MediaTransformError(
264 'thumbnail_error_remote',
265 $width,
266 $height,
267 $this->getDisplayName(),
268 $info['thumberror'] // already parsed message from foreign repo
269 );
270 } else {
271 return false;
272 }
273 }
274
275 /**
276 * Return the imageurl from cache if possible
277 *
278 * If the url has been requested today, get it from cache
279 * Otherwise retrieve remote thumb url, check for local file.
280 *
281 * @param string $name is a dbkey form of a title
282 * @param $width
283 * @param $height
284 * @param string $params Other rendering parameters (page number, etc) from handler's makeParamString.
285 * @return bool|string
286 */
287 function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
288 global $wgMemc;
289 // We can't check the local cache using FileRepo functions because
290 // we override fileExistsBatch(). We have to use the FileBackend directly.
291 $backend = $this->getBackend(); // convenience
292
293 if ( !$this->canCacheThumbs() ) {
294 $result = null; // can't pass "null" by reference, but it's ok as default value
295 return $this->getThumbUrl( $name, $width, $height, $result, $params );
296 }
297 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
298 $sizekey = "$width:$height:$params";
299
300 /* Get the array of urls that we already know */
301 $knownThumbUrls = $wgMemc->get( $key );
302 if ( !$knownThumbUrls ) {
303 /* No knownThumbUrls for this file */
304 $knownThumbUrls = array();
305 } else {
306 if ( isset( $knownThumbUrls[$sizekey] ) ) {
307 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
308 "{$knownThumbUrls[$sizekey]} \n" );
309 return $knownThumbUrls[$sizekey];
310 }
311 /* This size is not yet known */
312 }
313
314 $metadata = null;
315 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
316
317 if ( !$foreignUrl ) {
318 wfDebug( __METHOD__ . " Could not find thumburl\n" );
319 return false;
320 }
321
322 // We need the same filename as the remote one :)
323 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
324 if ( !$this->validateFilename( $fileName ) ) {
325 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
326 return false;
327 }
328 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
329 $localFilename = $localPath . "/" . $fileName;
330 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
331
332 if ( $backend->fileExists( array( 'src' => $localFilename ) )
333 && isset( $metadata['timestamp'] ) ) {
334 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
335 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
336 $remoteModified = strtotime( $metadata['timestamp'] );
337 $current = time();
338 $diff = abs( $modified - $current );
339 if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
340 /* Use our current and already downloaded thumbnail */
341 $knownThumbUrls[$sizekey] = $localUrl;
342 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
343 return $localUrl;
344 }
345 /* There is a new Commons file, or existing thumbnail older than a month */
346 }
347 $thumb = self::httpGet( $foreignUrl );
348 if ( !$thumb ) {
349 wfDebug( __METHOD__ . " Could not download thumb\n" );
350 return false;
351 }
352
353 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
354 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
355 $params = array( 'dst' => $localFilename, 'content' => $thumb );
356 if ( !$backend->quickCreate( $params )->isOK() ) {
357 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'\n" );
358 return $foreignUrl;
359 }
360 $knownThumbUrls[$sizekey] = $localUrl;
361 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
362 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
363 return $localUrl;
364 }
365
366 /**
367 * @see FileRepo::getZoneUrl()
368 * @param $zone String
369 * @param string|null $ext Optional file extension
370 * @return String
371 */
372 function getZoneUrl( $zone, $ext = null ) {
373 switch ( $zone ) {
374 case 'public':
375 return $this->url;
376 case 'thumb':
377 return $this->thumbUrl;
378 default:
379 return parent::getZoneUrl( $zone, $ext );
380 }
381 }
382
383 /**
384 * Get the local directory corresponding to one of the basic zones
385 * @param $zone string
386 * @return bool|null|string
387 */
388 function getZonePath( $zone ) {
389 $supported = array( 'public', 'thumb' );
390 if ( in_array( $zone, $supported ) ) {
391 return parent::getZonePath( $zone );
392 }
393 return false;
394 }
395
396 /**
397 * Are we locally caching the thumbnails?
398 * @return bool
399 */
400 public function canCacheThumbs() {
401 return ( $this->apiThumbCacheExpiry > 0 );
402 }
403
404 /**
405 * The user agent the ForeignAPIRepo will use.
406 * @return string
407 */
408 public static function getUserAgent() {
409 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
410 }
411
412 /**
413 * Get information about the repo - overrides/extends the parent
414 * class's information.
415 * @return array
416 * @since 1.22
417 */
418 function getInfo() {
419 $info = parent::getInfo();
420 $info['apiurl'] = $this->getApiUrl();
421
422 $query = array(
423 'format' => 'json',
424 'action' => 'query',
425 'meta' => 'siteinfo',
426 'siprop' => 'general',
427 );
428
429 $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
430
431 if ( $data ) {
432 $siteInfo = FormatJson::decode( $data, true );
433 $general = $siteInfo['query']['general'];
434
435 $info['articlepath'] = $general['articlepath'];
436 $info['server'] = $general['server'];
437 }
438
439 return $info;
440 }
441
442 /**
443 * Like a Http:get request, but with custom User-Agent.
444 * @see Http:get
445 * @param $url string
446 * @param $timeout string
447 * @param $options array
448 * @return bool|String
449 */
450 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
451 $options['timeout'] = $timeout;
452 /* Http::get */
453 $url = wfExpandUrl( $url, PROTO_HTTP );
454 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
455 $options['method'] = "GET";
456
457 if ( !isset( $options['timeout'] ) ) {
458 $options['timeout'] = 'default';
459 }
460
461 $req = MWHttpRequest::factory( $url, $options );
462 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
463 $status = $req->execute();
464
465 if ( $status->isOK() ) {
466 return $req->getContent();
467 } else {
468 return false;
469 }
470 }
471
472 /**
473 * HTTP GET request to a mediawiki API (with caching)
474 * @param $target string Used in cache key creation, mostly
475 * @param $query array The query parameters for the API request
476 * @param $cacheTTL int Time to live for the memcached caching
477 */
478 public function httpGetCached( $target, $query, $cacheTTL = 3600 ) {
479 if ( $this->mApiBase ) {
480 $url = wfAppendQuery( $this->mApiBase, $query );
481 } else {
482 $url = $this->makeUrl( $query, 'api' );
483 }
484
485 if ( !isset( $this->mQueryCache[$url] ) ) {
486 global $wgMemc;
487
488 $key = $this->getLocalCacheKey( get_class( $this ), $target, md5( $url ) );
489 $data = $wgMemc->get( $key );
490
491 if ( !$data ) {
492 $data = self::httpGet( $url );
493
494 if ( !$data ) {
495 return null;
496 }
497
498 $wgMemc->set( $key, $data, $cacheTTL );
499 }
500
501 if ( count( $this->mQueryCache ) > 100 ) {
502 // Keep the cache from growing infinitely
503 $this->mQueryCache = array();
504 }
505
506 $this->mQueryCache[$url] = $data;
507 }
508
509 return $this->mQueryCache[$url];
510 }
511
512 /**
513 * @param $callback Array|string
514 * @throws MWException
515 */
516 function enumFiles( $callback ) {
517 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
518 }
519
520 /**
521 * @throws MWException
522 */
523 protected function assertWritableRepo() {
524 throw new MWException( get_class( $this ) . ': write operations are not supported.' );
525 }
526 }