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