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