Few style/whitespace/comment issues from r86169
[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 $result = null; // can't pass "null" by reference, but it's ok as default value
235 return $this->getThumbUrl( $name, $width, $height, $result, $params );
236 }
237 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
238 $sizekey = "$width:$height:$params";
239
240 /* Get the array of urls that we already know */
241 $knownThumbUrls = $wgMemc->get($key);
242 if( !$knownThumbUrls ) {
243 /* No knownThumbUrls for this file */
244 $knownThumbUrls = array();
245 } else {
246 if( isset( $knownThumbUrls[$sizekey] ) ) {
247 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
248 "{$knownThumbUrls[$sizekey]} \n");
249 return $knownThumbUrls[$sizekey];
250 }
251 /* This size is not yet known */
252 }
253
254 $metadata = null;
255 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
256
257 if( !$foreignUrl ) {
258 wfDebug( __METHOD__ . " Could not find thumburl\n" );
259 return false;
260 }
261
262 // We need the same filename as the remote one :)
263 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
264 if( !$this->validateFilename( $fileName ) ) {
265 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
266 return false;
267 }
268 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
269 $localFilename = $localPath . "/" . $fileName;
270 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
271
272 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
273 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
274 $modified = filemtime( $localFilename );
275 $remoteModified = strtotime( $metadata['timestamp'] );
276 $current = time();
277 $diff = abs( $modified - $current );
278 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
279 /* Use our current and already downloaded thumbnail */
280 $knownThumbUrls[$sizekey] = $localUrl;
281 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
282 return $localUrl;
283 }
284 /* There is a new Commons file, or existing thumbnail older than a month */
285 }
286 $thumb = self::httpGet( $foreignUrl );
287 if( !$thumb ) {
288 wfDebug( __METHOD__ . " Could not download thumb\n" );
289 return false;
290 }
291 if ( !is_dir($localPath) ) {
292 if( !wfMkdirParents($localPath) ) {
293 wfDebug( __METHOD__ . " could not create directory $localPath for thumb\n" );
294 return $foreignUrl;
295 }
296 }
297
298 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
299 wfSuppressWarnings();
300 if( !file_put_contents( $localFilename, $thumb ) ) {
301 wfRestoreWarnings();
302 wfDebug( __METHOD__ . " could not write to thumb path\n" );
303 return $foreignUrl;
304 }
305 wfRestoreWarnings();
306 $knownThumbUrls[$sizekey] = $localUrl;
307 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
308 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
309 return $localUrl;
310 }
311
312 /**
313 * @see FileRepo::getZoneUrl()
314 */
315 function getZoneUrl( $zone ) {
316 switch ( $zone ) {
317 case 'public':
318 return $this->url;
319 case 'thumb':
320 return $this->thumbUrl;
321 default:
322 return parent::getZoneUrl( $zone );
323 }
324 }
325
326 /**
327 * Get the local directory corresponding to one of the three basic zones
328 */
329 function getZonePath( $zone ) {
330 switch ( $zone ) {
331 case 'public':
332 return $this->directory;
333 case 'thumb':
334 return $this->thumbDir;
335 default:
336 return false;
337 }
338 }
339
340 /**
341 * Are we locally caching the thumbnails?
342 * @return bool
343 */
344 public function canCacheThumbs() {
345 return ( $this->apiThumbCacheExpiry > 0 );
346 }
347
348 /**
349 * The user agent the ForeignAPIRepo will use.
350 */
351 public static function getUserAgent() {
352 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
353 }
354
355 /**
356 * Like a Http:get request, but with custom User-Agent.
357 * @see Http:get
358 */
359 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
360 $options['timeout'] = $timeout;
361 /* Http::get */
362 $url = wfExpandUrl( $url );
363 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
364 $options['method'] = "GET";
365
366 if ( !isset( $options['timeout'] ) ) {
367 $options['timeout'] = 'default';
368 }
369
370 $req = MWHttpRequest::factory( $url, $options );
371 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
372 $status = $req->execute();
373
374 if ( $status->isOK() ) {
375 return $req->getContent();
376 } else {
377 return false;
378 }
379 }
380 }