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