(bug 27046) Do not strip newlines following C++-style // comments. Prior to this...
[mediawiki.git] / includes / filerepo / ForeignAPIRepo.php
blobf465273b695709159288bcdfef808dad6a0daf8f
1 <?php
2 /**
3 * Foreign repository accessible through api.php requests.
5 * @file
6 * @ingroup FileRepo
7 */
9 /**
10 * A foreign repository with a remote MediaWiki with an API thingy
12 * Example config:
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 * );
22 * @ingroup FileRepo
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";
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;
39 protected $mQueryCache = array();
40 protected $mFileExists = array();
42 function __construct( $info ) {
43 parent::__construct( $info );
44 global $wgUploadDirectory;
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;
50 if( isset( $info['apiThumbCacheExpiry'] ) ) {
51 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
53 if( isset( $info['fileCacheExpiry'] ) ) {
54 $this->fileCacheExpiry = $info['fileCacheExpiry'];
56 if( !$this->scriptDirUrl ) {
57 // hack for description fetches
58 $this->scriptDirUrl = dirname( $this->mApiBase );
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'];
65 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
66 $this->thumbUrl = $this->url . '/thumb';
68 if ( isset( $info['thumbDir'] ) ) {
69 $this->thumbDir = $info['thumbDir'];
70 } else {
71 $this->thumbDir = "{$this->directory}/thumb";
75 /**
76 * Per docs in FileRepo, this needs to return false if we don't support versioned
77 * files. Well, we don't.
79 function newFile( $title, $time = false ) {
80 if ( $time ) {
81 return false;
83 return parent::newFile( $title, $time );
86 /**
87 * No-ops
89 function storeBatch( $triplets, $flags = 0 ) {
90 return false;
92 function storeTemp( $originalName, $srcPath ) {
93 return false;
95 function append( $srcPath, $toAppendPath, $flags = 0 ){
96 return false;
98 function publishBatch( $triplets, $flags = 0 ) {
99 return false;
101 function deleteBatch( $sourceDestPairs ) {
102 return false;
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] );
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++;
129 return $results;
132 function getFileProps( $virtualUrl ) {
133 return false;
136 function fetchImageQuery( $query ) {
137 global $wgMemc;
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' );
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;
159 $wgMemc->set( $key, $data, 3600 );
162 if( count( $this->mQueryCache ) > 100 ) {
163 // Keep the cache from growing infinitely
164 $this->mQueryCache = array();
166 $this->mQueryCache[$url] = $data;
168 return FormatJson::decode( $this->mQueryCache[$url], true );
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];
179 return false;
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;
194 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
197 return $ret;
200 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null ) {
201 $data = $this->fetchImageQuery( array(
202 'titles' => 'File:' . $name,
203 'iiprop' => 'url|timestamp',
204 'iiurlwidth' => $width,
205 'iiurlheight' => $height,
206 'prop' => 'imageinfo' ) );
207 $info = $this->getImageInfo( $data );
209 if( $data && $info && isset( $info['thumburl'] ) ) {
210 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
211 $result = $info;
212 return $info['thumburl'];
213 } else {
214 return false;
219 * Return the imageurl from cache if possible
221 * If the url has been requested today, get it from cache
222 * Otherwise retrieve remote thumb url, check for local file.
224 * @param $name String is a dbkey form of a title
225 * @param $width
226 * @param $height
228 function getThumbUrlFromCache( $name, $width, $height ) {
229 global $wgMemc;
231 if ( !$this->canCacheThumbs() ) {
232 return $this->getThumbUrl( $name, $width, $height );
234 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
235 $sizekey = "$width:$height";
237 /* Get the array of urls that we already know */
238 $knownThumbUrls = $wgMemc->get($key);
239 if( !$knownThumbUrls ) {
240 /* No knownThumbUrls for this file */
241 $knownThumbUrls = array();
242 } else {
243 if( isset( $knownThumbUrls[$sizekey] ) ) {
244 wfDebug("Got thumburl from local cache. {$knownThumbUrls[$sizekey]} \n");
245 return $knownThumbUrls[$sizekey];
247 /* This size is not yet known */
250 $metadata = null;
251 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata );
253 if( !$foreignUrl ) {
254 wfDebug( __METHOD__ . " Could not find thumburl\n" );
255 return false;
258 // We need the same filename as the remote one :)
259 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
260 if( !$this->validateFilename( $fileName ) ) {
261 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
262 return false;
264 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
265 $localFilename = $localPath . "/" . $fileName;
266 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
268 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
269 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
270 $modified = filemtime( $localFilename );
271 $remoteModified = strtotime( $metadata['timestamp'] );
272 $current = time();
273 $diff = abs( $modified - $current );
274 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
275 /* Use our current and already downloaded thumbnail */
276 $knownThumbUrls["$width:$height"] = $localUrl;
277 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
278 return $localUrl;
280 /* There is a new Commons file, or existing thumbnail older than a month */
282 $thumb = self::httpGet( $foreignUrl );
283 if( !$thumb ) {
284 wfDebug( __METHOD__ . " Could not download thumb\n" );
285 return false;
287 if ( !is_dir($localPath) ) {
288 if( !wfMkdirParents($localPath) ) {
289 wfDebug( __METHOD__ . " could not create directory $localPath for thumb\n" );
290 return $foreignUrl;
294 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
295 wfSuppressWarnings();
296 if( !file_put_contents( $localFilename, $thumb ) ) {
297 wfRestoreWarnings();
298 wfDebug( __METHOD__ . " could not write to thumb path\n" );
299 return $foreignUrl;
301 wfRestoreWarnings();
302 $knownThumbUrls[$sizekey] = $localUrl;
303 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
304 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
305 return $localUrl;
309 * @see FileRepo::getZoneUrl()
311 function getZoneUrl( $zone ) {
312 switch ( $zone ) {
313 case 'public':
314 return $this->url;
315 case 'thumb':
316 return $this->thumbUrl;
317 default:
318 return parent::getZoneUrl( $zone );
323 * Get the local directory corresponding to one of the three basic zones
325 function getZonePath( $zone ) {
326 switch ( $zone ) {
327 case 'public':
328 return $this->directory;
329 case 'thumb':
330 return $this->thumbDir;
331 default:
332 return false;
337 * Are we locally caching the thumbnails?
338 * @return bool
340 public function canCacheThumbs() {
341 return ( $this->apiThumbCacheExpiry > 0 );
345 * The user agent the ForeignAPIRepo will use.
347 public static function getUserAgent() {
348 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
352 * Like a Http:get request, but with custom User-Agent.
353 * @see Http:get
355 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
356 $options['timeout'] = $timeout;
357 /* Http::get */
358 $url = wfExpandUrl( $url );
359 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
360 $options['method'] = "GET";
362 if ( !isset( $options['timeout'] ) ) {
363 $options['timeout'] = 'default';
366 $req = MWHttpRequest::factory( $url, $options );
367 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
368 $status = $req->execute();
370 if ( $status->isOK() ) {
371 return $req->getContent();
372 } else {
373 return false;