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