Moved FileBackendStore and helper classes to their own file (no code changes). Update...
[lhc/web/wiklou.git] / includes / filerepo / ForeignAPIRepo.php
1 <?php
2 /**
3 * Foreign repository accessible through api.php requests.
4 *
5 * @file
6 * @ingroup FileRepo
7 */
8
9 /**
10 * A foreign repository with a remote MediaWiki with an API thingy
11 *
12 * Example config:
13 *
14 * $wgForeignFileRepos[] = array(
15 * 'class' => 'ForeignAPIRepo',
16 * 'name' => 'shared',
17 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
18 * 'fetchDescription' => true, // Optional
19 * 'descriptionCacheExpiry' => 3600,
20 * );
21 *
22 * @ingroup FileRepo
23 */
24 class ForeignAPIRepo extends FileRepo {
25 /* This version string is used in the user agent for requests and will help
26 * server maintainers in identify ForeignAPI usage.
27 * Update the version every time you make breaking or significant changes. */
28 const VERSION = "2.1";
29
30 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
31 /* Check back with Commons after a day */
32 var $apiThumbCacheExpiry = 86400; /* 24*60*60 */
33 /* Redownload thumbnail files after a month */
34 var $fileCacheExpiry = 2592000; /* 86400*30 */
35
36 protected $mQueryCache = array();
37 protected $mFileExists = array();
38
39 function __construct( $info ) {
40 global $wgLocalFileRepo;
41 parent::__construct( $info );
42
43 // http://commons.wikimedia.org/w/api.php
44 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
45
46 if( isset( $info['apiThumbCacheExpiry'] ) ) {
47 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
48 }
49 if( isset( $info['fileCacheExpiry'] ) ) {
50 $this->fileCacheExpiry = $info['fileCacheExpiry'];
51 }
52 if( !$this->scriptDirUrl ) {
53 // hack for description fetches
54 $this->scriptDirUrl = dirname( $this->mApiBase );
55 }
56 // If we can cache thumbs we can guess sane defaults for these
57 if( $this->canCacheThumbs() && !$this->url ) {
58 $this->url = $wgLocalFileRepo['url'];
59 }
60 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
61 $this->thumbUrl = $this->url . '/thumb';
62 }
63 }
64
65 /**
66 * Per docs in FileRepo, this needs to return false if we don't support versioned
67 * files. Well, we don't.
68 *
69 * @return File
70 */
71 function newFile( $title, $time = false ) {
72 if ( $time ) {
73 return false;
74 }
75 return parent::newFile( $title, $time );
76 }
77
78 /**
79 * No-ops
80 * @return bool
81 */
82
83 function storeBatch( $triplets, $flags = 0 ) {
84 return false;
85 }
86
87 function storeTemp( $originalName, $srcPath ) {
88 return false;
89 }
90
91 function concatenate( $fileList, $targetPath, $flags = 0 ){
92 return false;
93 }
94
95 function append( $srcPath, $toAppendPath, $flags = 0 ){
96 return false;
97 }
98
99 function appendFinish( $toAppendPath ){
100 return false;
101 }
102
103 function publishBatch( $triplets, $flags = 0 ) {
104 return false;
105 }
106
107 function deleteBatch( $sourceDestPairs ) {
108 return false;
109 }
110
111 function fileExistsBatch( $files, $flags = 0 ) {
112 $results = array();
113 foreach ( $files as $k => $f ) {
114 if ( isset( $this->mFileExists[$k] ) ) {
115 $results[$k] = true;
116 unset( $files[$k] );
117 } elseif( self::isVirtualUrl( $f ) ) {
118 # @todo FIXME: We need to be able to handle virtual
119 # URLs better, at least when we know they refer to the
120 # same repo.
121 $results[$k] = false;
122 unset( $files[$k] );
123 }
124 }
125
126 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
127 'prop' => 'imageinfo' ) );
128 if( isset( $data['query']['pages'] ) ) {
129 $i = 0;
130 foreach( $files as $key => $file ) {
131 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
132 $i++;
133 }
134 }
135 return $results;
136 }
137
138 function getFileProps( $virtualUrl ) {
139 return false;
140 }
141
142 function fetchImageQuery( $query ) {
143 global $wgMemc;
144
145 $query = array_merge( $query,
146 array(
147 'format' => 'json',
148 'action' => 'query',
149 'redirects' => 'true'
150 ) );
151 if ( $this->mApiBase ) {
152 $url = wfAppendQuery( $this->mApiBase, $query );
153 } else {
154 $url = $this->makeUrl( $query, 'api' );
155 }
156
157 if( !isset( $this->mQueryCache[$url] ) ) {
158 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
159 $data = $wgMemc->get( $key );
160 if( !$data ) {
161 $data = self::httpGet( $url );
162 if ( !$data ) {
163 return null;
164 }
165 $wgMemc->set( $key, $data, 3600 );
166 }
167
168 if( count( $this->mQueryCache ) > 100 ) {
169 // Keep the cache from growing infinitely
170 $this->mQueryCache = array();
171 }
172 $this->mQueryCache[$url] = $data;
173 }
174 return FormatJson::decode( $this->mQueryCache[$url], true );
175 }
176
177 function getImageInfo( $data ) {
178 if( $data && isset( $data['query']['pages'] ) ) {
179 foreach( $data['query']['pages'] as $info ) {
180 if( isset( $info['imageinfo'][0] ) ) {
181 return $info['imageinfo'][0];
182 }
183 }
184 }
185 return false;
186 }
187
188 function findBySha1( $hash ) {
189 $results = $this->fetchImageQuery( array(
190 'aisha1base36' => $hash,
191 'aiprop' => ForeignAPIFile::getProps(),
192 'list' => 'allimages', ) );
193 $ret = array();
194 if ( isset( $results['query']['allimages'] ) ) {
195 foreach ( $results['query']['allimages'] as $img ) {
196 // 1.14 was broken, doesn't return name attribute
197 if( !isset( $img['name'] ) ) {
198 continue;
199 }
200 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
201 }
202 }
203 return $ret;
204 }
205
206 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
207 $data = $this->fetchImageQuery( array(
208 'titles' => 'File:' . $name,
209 'iiprop' => 'url|timestamp',
210 'iiurlwidth' => $width,
211 'iiurlheight' => $height,
212 'iiurlparam' => $otherParams,
213 'prop' => 'imageinfo' ) );
214 $info = $this->getImageInfo( $data );
215
216 if( $data && $info && isset( $info['thumburl'] ) ) {
217 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
218 $result = $info;
219 return $info['thumburl'];
220 } else {
221 return false;
222 }
223 }
224
225 /**
226 * Return the imageurl from cache if possible
227 *
228 * If the url has been requested today, get it from cache
229 * Otherwise retrieve remote thumb url, check for local file.
230 *
231 * @param $name String is a dbkey form of a title
232 * @param $width
233 * @param $height
234 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
235 * @return bool|string
236 */
237 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
238 global $wgMemc;
239
240 if ( !$this->canCacheThumbs() ) {
241 $result = null; // can't pass "null" by reference, but it's ok as default value
242 return $this->getThumbUrl( $name, $width, $height, $result, $params );
243 }
244 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
245 $sizekey = "$width:$height:$params";
246
247 /* Get the array of urls that we already know */
248 $knownThumbUrls = $wgMemc->get($key);
249 if( !$knownThumbUrls ) {
250 /* No knownThumbUrls for this file */
251 $knownThumbUrls = array();
252 } else {
253 if( isset( $knownThumbUrls[$sizekey] ) ) {
254 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
255 "{$knownThumbUrls[$sizekey]} \n");
256 return $knownThumbUrls[$sizekey];
257 }
258 /* This size is not yet known */
259 }
260
261 $metadata = null;
262 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
263
264 if( !$foreignUrl ) {
265 wfDebug( __METHOD__ . " Could not find thumburl\n" );
266 return false;
267 }
268
269 // We need the same filename as the remote one :)
270 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
271 if( !$this->validateFilename( $fileName ) ) {
272 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
273 return false;
274 }
275 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
276 $localFilename = $localPath . "/" . $fileName;
277 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
278
279 if( $this->fileExists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
280 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
281 $modified = $this->getFileTimestamp( $localFilename );
282 $remoteModified = strtotime( $metadata['timestamp'] );
283 $current = time();
284 $diff = abs( $modified - $current );
285 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
286 /* Use our current and already downloaded thumbnail */
287 $knownThumbUrls[$sizekey] = $localUrl;
288 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
289 return $localUrl;
290 }
291 /* There is a new Commons file, or existing thumbnail older than a month */
292 }
293 $thumb = self::httpGet( $foreignUrl );
294 if( !$thumb ) {
295 wfDebug( __METHOD__ . " Could not download thumb\n" );
296 return false;
297 }
298
299 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
300 wfSuppressWarnings();
301 $backend = $this->getBackend();
302 $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
303 if( !$backend->doOperation( $op )->isOK() ) {
304 wfRestoreWarnings();
305 wfDebug( __METHOD__ . " could not write to thumb path\n" );
306 return $foreignUrl;
307 }
308 wfRestoreWarnings();
309 $knownThumbUrls[$sizekey] = $localUrl;
310 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
311 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
312 return $localUrl;
313 }
314
315 /**
316 * @see FileRepo::getZoneUrl()
317 * @return String
318 */
319 function getZoneUrl( $zone ) {
320 switch ( $zone ) {
321 case 'public':
322 return $this->url;
323 case 'thumb':
324 return $this->thumbUrl;
325 default:
326 return parent::getZoneUrl( $zone );
327 }
328 }
329
330 /**
331 * Get the local directory corresponding to one of the basic zones
332 * @return bool|null|string
333 */
334 function getZonePath( $zone ) {
335 $supported = array( 'public', 'thumb' );
336 if ( in_array( $zone, $supported ) ) {
337 return parent::getZonePath( $zone );
338 }
339 return false;
340 }
341
342 /**
343 * Are we locally caching the thumbnails?
344 * @return bool
345 */
346 public function canCacheThumbs() {
347 return ( $this->apiThumbCacheExpiry > 0 );
348 }
349
350 /**
351 * The user agent the ForeignAPIRepo will use.
352 * @return string
353 */
354 public static function getUserAgent() {
355 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
356 }
357
358 /**
359 * Like a Http:get request, but with custom User-Agent.
360 * @see Http:get
361 * @return bool|String
362 */
363 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
364 $options['timeout'] = $timeout;
365 /* Http::get */
366 $url = wfExpandUrl( $url, PROTO_HTTP );
367 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
368 $options['method'] = "GET";
369
370 if ( !isset( $options['timeout'] ) ) {
371 $options['timeout'] = 'default';
372 }
373
374 $req = MWHttpRequest::factory( $url, $options );
375 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
376 $status = $req->execute();
377
378 if ( $status->isOK() ) {
379 return $req->getContent();
380 } else {
381 return false;
382 }
383 }
384
385 function enumFiles( $callback ) {
386 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
387 }
388 }