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