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