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