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