Merge "CSSJanus: Support text-shadow and box-shadow flipping"
[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 * Per docs in FileRepo, this needs to return false if we don't support versioned
85 * files. Well, we don't.
86 *
87 * @param $title Title
88 * @param $time string|bool
89 * @return File
90 */
91 function newFile( $title, $time = false ) {
92 if ( $time ) {
93 return false;
94 }
95 return parent::newFile( $title, $time );
96 }
97
98 /**
99 * @param $files array
100 * @return array
101 */
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'." );
118 }
119 }
120
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++;
128 }
129 }
130 return $results;
131 }
132
133 /**
134 * @param $virtualUrl string
135 * @return bool
136 */
137 function getFileProps( $virtualUrl ) {
138 return false;
139 }
140
141 /**
142 * @param $query array
143 * @return string
144 */
145 function fetchImageQuery( $query ) {
146 global $wgMemc, $wgLanguageCode;
147
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;
156 }
157 if ( $this->mApiBase ) {
158 $url = wfAppendQuery( $this->mApiBase, $query );
159 } else {
160 $url = $this->makeUrl( $query, 'api' );
161 }
162
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;
170 }
171 $wgMemc->set( $key, $data, 3600 );
172 }
173
174 if ( count( $this->mQueryCache ) > 100 ) {
175 // Keep the cache from growing infinitely
176 $this->mQueryCache = array();
177 }
178 $this->mQueryCache[$url] = $data;
179 }
180 return FormatJson::decode( $this->mQueryCache[$url], true );
181 }
182
183 /**
184 * @param $data array
185 * @return bool|array
186 */
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];
192 }
193 }
194 }
195 return false;
196 }
197
198 /**
199 * @param $hash string
200 * @return array
201 */
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;
214 }
215 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
216 }
217 }
218 return $ret;
219 }
220
221 /**
222 * @param $name string
223 * @param $width int
224 * @param $height int
225 * @param $result null
226 * @param $otherParams string
227 * @return bool
228 */
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 );
238
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;
245 }
246 }
247
248 /**
249 * @param $name string
250 * @param $width int
251 * @param $height int
252 * @param $otherParams string
253 * @return bool|MediaTransformError
254 * @since 1.22
255 */
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 );
267
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
276 );
277 } else {
278 return false;
279 }
280 }
281
282 /**
283 * Return the imageurl from cache if possible
284 *
285 * If the url has been requested today, get it from cache
286 * Otherwise retrieve remote thumb url, check for local file.
287 *
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
293 */
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
299
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 );
303 }
304 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
305 $sizekey = "$width:$height:$params";
306
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];
317 }
318 /* This size is not yet known */
319 }
320
321 $metadata = null;
322 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
323
324 if ( !$foreignUrl ) {
325 wfDebug( __METHOD__ . " Could not find thumburl\n" );
326 return false;
327 }
328
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;
334 }
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 );
338
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;
351 }
352 /* There is a new Commons file, or existing thumbnail older than a month */
353 }
354 $thumb = self::httpGet( $foreignUrl );
355 if ( !$thumb ) {
356 wfDebug( __METHOD__ . " Could not download thumb\n" );
357 return false;
358 }
359
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;
366 }
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;
371 }
372
373 /**
374 * @see FileRepo::getZoneUrl()
375 * @param $zone String
376 * @param string|null $ext Optional file extension
377 * @return String
378 */
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 );
387 }
388 }
389
390 /**
391 * Get the local directory corresponding to one of the basic zones
392 * @param $zone string
393 * @return bool|null|string
394 */
395 function getZonePath( $zone ) {
396 $supported = array( 'public', 'thumb' );
397 if ( in_array( $zone, $supported ) ) {
398 return parent::getZonePath( $zone );
399 }
400 return false;
401 }
402
403 /**
404 * Are we locally caching the thumbnails?
405 * @return bool
406 */
407 public function canCacheThumbs() {
408 return ( $this->apiThumbCacheExpiry > 0 );
409 }
410
411 /**
412 * The user agent the ForeignAPIRepo will use.
413 * @return string
414 */
415 public static function getUserAgent() {
416 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
417 }
418
419 /**
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
426 */
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";
433
434 if ( !isset( $options['timeout'] ) ) {
435 $options['timeout'] = 'default';
436 }
437
438 $req = MWHttpRequest::factory( $url, $options );
439 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
440 $status = $req->execute();
441
442 if ( $status->isOK() ) {
443 return $req->getContent();
444 } else {
445 return false;
446 }
447 }
448
449 /**
450 * @param $callback Array|string
451 * @throws MWException
452 */
453 function enumFiles( $callback ) {
454 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
455 }
456
457 /**
458 * @throws MWException
459 */
460 protected function assertWritableRepo() {
461 throw new MWException( get_class( $this ) . ': write operations are not supported.' );
462 }
463 }