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