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