[FileRepo] Various ForeignApiRepo fixes.
[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
36 protected $mQueryCache = array();
37 protected $mFileExists = array();
38
39 function __construct( $info ) {
40 global $wgLocalFileRepo;
41 parent::__construct( $info );
42
43 // http://commons.wikimedia.org/w/api.php
44 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
45
46 if( isset( $info['apiThumbCacheExpiry'] ) ) {
47 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
48 }
49 if( isset( $info['fileCacheExpiry'] ) ) {
50 $this->fileCacheExpiry = $info['fileCacheExpiry'];
51 }
52 if( !$this->scriptDirUrl ) {
53 // hack for description fetches
54 $this->scriptDirUrl = dirname( $this->mApiBase );
55 }
56 // If we can cache thumbs we can guess sane defaults for these
57 if( $this->canCacheThumbs() && !$this->url ) {
58 $this->url = $wgLocalFileRepo['url'];
59 }
60 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
61 $this->thumbUrl = $this->url . '/thumb';
62 }
63 }
64
65 /**
66 * Per docs in FileRepo, this needs to return false if we don't support versioned
67 * files. Well, we don't.
68 *
69 * @return File
70 */
71 function newFile( $title, $time = false ) {
72 if ( $time ) {
73 return false;
74 }
75 return parent::newFile( $title, $time );
76 }
77
78 function fileExistsBatch( array $files ) {
79 $results = array();
80 foreach ( $files as $k => $f ) {
81 if ( isset( $this->mFileExists[$k] ) ) {
82 $results[$k] = true;
83 unset( $files[$k] );
84 } elseif( self::isVirtualUrl( $f ) ) {
85 # @todo FIXME: We need to be able to handle virtual
86 # URLs better, at least when we know they refer to the
87 # same repo.
88 $results[$k] = false;
89 unset( $files[$k] );
90 } elseif ( FileBackend::isStoragePath( $f ) ) {
91 $results[$k] = false;
92 unset( $files[$k] );
93 wfWarn( "Got mwstore:// path '$f'." );
94 }
95 }
96
97 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
98 'prop' => 'imageinfo' ) );
99 if( isset( $data['query']['pages'] ) ) {
100 $i = 0;
101 foreach( $files as $key => $file ) {
102 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
103 $i++;
104 }
105 }
106 return $results;
107 }
108
109 function getFileProps( $virtualUrl ) {
110 return false;
111 }
112
113 function fetchImageQuery( $query ) {
114 global $wgMemc;
115
116 $query = array_merge( $query,
117 array(
118 'format' => 'json',
119 'action' => 'query',
120 'redirects' => 'true'
121 ) );
122 if ( $this->mApiBase ) {
123 $url = wfAppendQuery( $this->mApiBase, $query );
124 } else {
125 $url = $this->makeUrl( $query, 'api' );
126 }
127
128 if( !isset( $this->mQueryCache[$url] ) ) {
129 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
130 $data = $wgMemc->get( $key );
131 if( !$data ) {
132 $data = self::httpGet( $url );
133 if ( !$data ) {
134 return null;
135 }
136 $wgMemc->set( $key, $data, 3600 );
137 }
138
139 if( count( $this->mQueryCache ) > 100 ) {
140 // Keep the cache from growing infinitely
141 $this->mQueryCache = array();
142 }
143 $this->mQueryCache[$url] = $data;
144 }
145 return FormatJson::decode( $this->mQueryCache[$url], true );
146 }
147
148 function getImageInfo( $data ) {
149 if( $data && isset( $data['query']['pages'] ) ) {
150 foreach( $data['query']['pages'] as $info ) {
151 if( isset( $info['imageinfo'][0] ) ) {
152 return $info['imageinfo'][0];
153 }
154 }
155 }
156 return false;
157 }
158
159 function findBySha1( $hash ) {
160 $results = $this->fetchImageQuery( array(
161 'aisha1base36' => $hash,
162 'aiprop' => ForeignAPIFile::getProps(),
163 'list' => 'allimages', ) );
164 $ret = array();
165 if ( isset( $results['query']['allimages'] ) ) {
166 foreach ( $results['query']['allimages'] as $img ) {
167 // 1.14 was broken, doesn't return name attribute
168 if( !isset( $img['name'] ) ) {
169 continue;
170 }
171 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
172 }
173 }
174 return $ret;
175 }
176
177 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
178 $data = $this->fetchImageQuery( array(
179 'titles' => 'File:' . $name,
180 'iiprop' => 'url|timestamp',
181 'iiurlwidth' => $width,
182 'iiurlheight' => $height,
183 'iiurlparam' => $otherParams,
184 'prop' => 'imageinfo' ) );
185 $info = $this->getImageInfo( $data );
186
187 if( $data && $info && isset( $info['thumburl'] ) ) {
188 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
189 $result = $info;
190 return $info['thumburl'];
191 } else {
192 return false;
193 }
194 }
195
196 /**
197 * Return the imageurl from cache if possible
198 *
199 * If the url has been requested today, get it from cache
200 * Otherwise retrieve remote thumb url, check for local file.
201 *
202 * @param $name String is a dbkey form of a title
203 * @param $width
204 * @param $height
205 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
206 * @return bool|string
207 */
208 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
209 global $wgMemc;
210 // We can't check the local cache using FileRepo functions because
211 // we override fileExistsBatch(). We have to use the FileBackend directly.
212 $backend = $this->getBackend(); // convenience
213
214 if ( !$this->canCacheThumbs() ) {
215 $result = null; // can't pass "null" by reference, but it's ok as default value
216 return $this->getThumbUrl( $name, $width, $height, $result, $params );
217 }
218 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
219 $sizekey = "$width:$height:$params";
220
221 /* Get the array of urls that we already know */
222 $knownThumbUrls = $wgMemc->get($key);
223 if( !$knownThumbUrls ) {
224 /* No knownThumbUrls for this file */
225 $knownThumbUrls = array();
226 } else {
227 if( isset( $knownThumbUrls[$sizekey] ) ) {
228 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
229 "{$knownThumbUrls[$sizekey]} \n");
230 return $knownThumbUrls[$sizekey];
231 }
232 /* This size is not yet known */
233 }
234
235 $metadata = null;
236 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
237
238 if( !$foreignUrl ) {
239 wfDebug( __METHOD__ . " Could not find thumburl\n" );
240 return false;
241 }
242
243 // We need the same filename as the remote one :)
244 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
245 if( !$this->validateFilename( $fileName ) ) {
246 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
247 return false;
248 }
249 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
250 $localFilename = $localPath . "/" . $fileName;
251 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . rawurlencode( $name ) . "/" . rawurlencode( $fileName );
252
253 if( $backend->fileExists( array( 'src' => $localFilename ) )
254 && isset( $metadata['timestamp'] ) )
255 {
256 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
257 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
258 $remoteModified = strtotime( $metadata['timestamp'] );
259 $current = time();
260 $diff = abs( $modified - $current );
261 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
262 /* Use our current and already downloaded thumbnail */
263 $knownThumbUrls[$sizekey] = $localUrl;
264 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
265 return $localUrl;
266 }
267 /* There is a new Commons file, or existing thumbnail older than a month */
268 }
269 $thumb = self::httpGet( $foreignUrl );
270 if( !$thumb ) {
271 wfDebug( __METHOD__ . " Could not download thumb\n" );
272 return false;
273 }
274
275 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
276 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
277 $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
278 if( !$backend->doOperation( $op )->isOK() ) {
279 wfRestoreWarnings();
280 wfDebug( __METHOD__ . " could not write to thumb path\n" );
281 return $foreignUrl;
282 }
283 $knownThumbUrls[$sizekey] = $localUrl;
284 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
285 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
286 return $localUrl;
287 }
288
289 /**
290 * @see FileRepo::getZoneUrl()
291 * @return String
292 */
293 function getZoneUrl( $zone ) {
294 switch ( $zone ) {
295 case 'public':
296 return $this->url;
297 case 'thumb':
298 return $this->thumbUrl;
299 default:
300 return parent::getZoneUrl( $zone );
301 }
302 }
303
304 /**
305 * Get the local directory corresponding to one of the basic zones
306 * @return bool|null|string
307 */
308 function getZonePath( $zone ) {
309 $supported = array( 'public', 'thumb' );
310 if ( in_array( $zone, $supported ) ) {
311 return parent::getZonePath( $zone );
312 }
313 return false;
314 }
315
316 /**
317 * Are we locally caching the thumbnails?
318 * @return bool
319 */
320 public function canCacheThumbs() {
321 return ( $this->apiThumbCacheExpiry > 0 );
322 }
323
324 /**
325 * The user agent the ForeignAPIRepo will use.
326 * @return string
327 */
328 public static function getUserAgent() {
329 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
330 }
331
332 /**
333 * Like a Http:get request, but with custom User-Agent.
334 * @see Http:get
335 * @return bool|String
336 */
337 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
338 $options['timeout'] = $timeout;
339 /* Http::get */
340 $url = wfExpandUrl( $url, PROTO_HTTP );
341 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
342 $options['method'] = "GET";
343
344 if ( !isset( $options['timeout'] ) ) {
345 $options['timeout'] = 'default';
346 }
347
348 $req = MWHttpRequest::factory( $url, $options );
349 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
350 $status = $req->execute();
351
352 if ( $status->isOK() ) {
353 return $req->getContent();
354 } else {
355 return false;
356 }
357 }
358
359 function enumFiles( $callback ) {
360 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
361 }
362
363 protected function assertWritableRepo() {
364 throw new MWException( get_class( $this ) . ': write operations are not supported.' );
365 }
366 }