follow up r76111. I had picked the wrong timedifference for the filecache.
[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 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
26 /* Check back with Commons after a day */
27 var $apiThumbCacheExpiry = 86400;
28 /* Redownload thumbnail files after a month */
29 var $fileCacheExpiry = 2629743;
30 /* Local image directory */
31 var $directory;
32 var $thumbDir;
33
34 protected $mQueryCache = array();
35 protected $mFileExists = array();
36
37 function __construct( $info ) {
38 parent::__construct( $info );
39 global $wgUploadDirectory;
40
41 // http://commons.wikimedia.org/w/api.php
42 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
43 $this->directory = isset( $info['directory'] ) ? $info['directory'] : $wgUploadDirectory;
44
45 if( isset( $info['apiThumbCacheExpiry'] ) ) {
46 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
47 }
48 if( isset( $info['fileCacheExpiry'] ) ) {
49 $this->fileCacheExpiry = $info['fileCacheExpiry'];
50 }
51 if( !$this->scriptDirUrl ) {
52 // hack for description fetches
53 $this->scriptDirUrl = dirname( $this->mApiBase );
54 }
55 // If we can cache thumbs we can guess sane defaults for these
56 if( $this->canCacheThumbs() && !$this->url ) {
57 global $wgLocalFileRepo;
58 $this->url = $wgLocalFileRepo['url'];
59 }
60 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
61 $this->thumbUrl = $this->url . '/thumb';
62 }
63 if ( isset( $info['thumbDir'] ) ) {
64 $this->thumbDir = $info['thumbDir'];
65 } else {
66 $this->thumbDir = "{$this->directory}/thumb";
67 }
68 }
69
70 /**
71 * Per docs in FileRepo, this needs to return false if we don't support versioned
72 * files. Well, we don't.
73 */
74 function newFile( $title, $time = false ) {
75 if ( $time ) {
76 return false;
77 }
78 return parent::newFile( $title, $time );
79 }
80
81 /**
82 * No-ops
83 */
84 function storeBatch( $triplets, $flags = 0 ) {
85 return false;
86 }
87 function storeTemp( $originalName, $srcPath ) {
88 return false;
89 }
90 function append( $srcPath, $toAppendPath, $flags = 0 ){
91 return false;
92 }
93 function publishBatch( $triplets, $flags = 0 ) {
94 return false;
95 }
96 function deleteBatch( $sourceDestPairs ) {
97 return false;
98 }
99
100
101 function fileExistsBatch( $files, $flags = 0 ) {
102 $results = array();
103 foreach ( $files as $k => $f ) {
104 if ( isset( $this->mFileExists[$k] ) ) {
105 $results[$k] = true;
106 unset( $files[$k] );
107 } elseif( self::isVirtualUrl( $f ) ) {
108 # TODO! FIXME! We need to be able to handle virtual
109 # URLs better, at least when we know they refer to the
110 # same repo.
111 $results[$k] = false;
112 unset( $files[$k] );
113 }
114 }
115
116 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
117 'prop' => 'imageinfo' ) );
118 if( isset( $data['query']['pages'] ) ) {
119 $i = 0;
120 foreach( $files as $key => $file ) {
121 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
122 $i++;
123 }
124 }
125 }
126 function getFileProps( $virtualUrl ) {
127 return false;
128 }
129
130 function fetchImageQuery( $query ) {
131 global $wgMemc;
132
133 $query = array_merge( $query,
134 array(
135 'format' => 'json',
136 'action' => 'query',
137 'redirects' => 'true'
138 ) );
139 if ( $this->mApiBase ) {
140 $url = wfAppendQuery( $this->mApiBase, $query );
141 } else {
142 $url = $this->makeUrl( $query, 'api' );
143 }
144
145 if( !isset( $this->mQueryCache[$url] ) ) {
146 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
147 $data = $wgMemc->get( $key );
148 if( !$data ) {
149 $data = Http::get( $url );
150 if ( !$data ) {
151 return null;
152 }
153 $wgMemc->set( $key, $data, 3600 );
154 }
155
156 if( count( $this->mQueryCache ) > 100 ) {
157 // Keep the cache from growing infinitely
158 $this->mQueryCache = array();
159 }
160 $this->mQueryCache[$url] = $data;
161 }
162 return FormatJson::decode( $this->mQueryCache[$url], true );
163 }
164
165 function getImageInfo( $data ) {
166 if( $data && isset( $data['query']['pages'] ) ) {
167 foreach( $data['query']['pages'] as $info ) {
168 if( isset( $info['imageinfo'][0] ) ) {
169 return $info['imageinfo'][0];
170 }
171 }
172 }
173 return false;
174 }
175
176 function findBySha1( $hash ) {
177 $results = $this->fetchImageQuery( array(
178 'aisha1base36' => $hash,
179 'aiprop' => ForeignAPIFile::getProps(),
180 'list' => 'allimages', ) );
181 $ret = array();
182 if ( isset( $results['query']['allimages'] ) ) {
183 foreach ( $results['query']['allimages'] as $img ) {
184 // 1.14 was broken, doesn't return name attribute
185 if( !isset( $img['name'] ) ) {
186 continue;
187 }
188 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
189 }
190 }
191 return $ret;
192 }
193
194 function getThumbUrl( $name, $width=-1, $height=-1, &$result ) {
195 $data = $this->fetchImageQuery( array(
196 'titles' => 'File:' . $name,
197 'iiprop' => 'url|timestamp',
198 'iiurlwidth' => $width,
199 'iiurlheight' => $height,
200 'prop' => 'imageinfo' ) );
201 $info = $this->getImageInfo( $data );
202
203 if( $data && $info && isset( $info['thumburl'] ) ) {
204 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
205 $result = $info;
206 return $info['thumburl'];
207 } else {
208 return false;
209 }
210 }
211
212 /*
213 * Return the imageurl from cache if possible
214 *
215 * If the url has been requested today, get it from cache
216 * Otherwise retrieve remote thumb url, check for local file.
217 *
218 * @param $name String is a dbkey form of a title
219 * @param $width
220 * @param $height
221 */
222 function getThumbUrlFromCache( $name, $width, $height ) {
223 global $wgMemc;
224
225 if ( !$this->canCacheThumbs() ) {
226 return $this->getThumbUrl( $name, $width, $height );
227 }
228 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name, $width );
229
230 $thumbUrl = $wgMemc->get($key);
231 if ( $thumbUrl ) {
232 wfDebug("Got thumb from local cache. $thumbUrl \n");
233 return $thumbUrl;
234 }
235 else {
236 $metadata = null;
237 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata );
238
239 if( !$foreignUrl ) {
240 wfDebug( __METHOD__ . " Could not find thumburl\n" );
241 return false;
242 }
243
244 // We need the same filename as the remote one :)
245 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
246 if( !$this->validateFilename( $fileName ) ) {
247 wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
248 return false;
249 }
250 $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
251 $localFilename = $localPath . "/" . $fileName;
252 $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) . urlencode( $name ) . "/" . urlencode( $fileName );
253
254 if( file_exists( $localFilename ) && isset( $metadata['timestamp'] ) ) {
255 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
256 $modified = filemtime( $localFilename );
257 $remoteModified = strtotime( $metadata['timestamp'] );
258 $current = time();
259 $diff = abs( $modified - $current );
260 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
261 /* Use our current and already downloaded thumbnail */
262 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
263 return $localUrl;
264 }
265 /* There is a new Commons file, or existing thumbnail older than a month */
266 }
267 $thumb = Http::get( $foreignUrl );
268 if( !$thumb ) {
269 wfDebug( __METHOD__ . " Could not download thumb\n" );
270 return false;
271 }
272 if ( !is_dir($localPath) ) {
273 if( !wfMkdirParents($localPath) ) {
274 wfDebug( __METHOD__ . " could not create directory $localPath for thumb\n" );
275 return $foreignUrl;
276 }
277 }
278
279 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
280 wfSuppressWarnings();
281 if( !file_put_contents( $localFilename, $thumb ) ) {
282 wfRestoreWarnings();
283 wfDebug( __METHOD__ . " could not write to thumb path\n" );
284 return $foreignUrl;
285 }
286 wfRestoreWarnings();
287 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
288 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
289 return $localUrl;
290 }
291 }
292
293 /**
294 * @see FileRepo::getZoneUrl()
295 */
296 function getZoneUrl( $zone ) {
297 switch ( $zone ) {
298 case 'public':
299 return $this->url;
300 case 'thumb':
301 return $this->thumbUrl;
302 default:
303 return parent::getZoneUrl( $zone );
304 }
305 }
306
307 /**
308 * Get the local directory corresponding to one of the three basic zones
309 */
310 function getZonePath( $zone ) {
311 switch ( $zone ) {
312 case 'public':
313 return $this->directory;
314 case 'thumb':
315 return $this->thumbDir;
316 default:
317 return false;
318 }
319 }
320
321 /**
322 * Are we locally caching the thumbnails?
323 * @return bool
324 */
325 public function canCacheThumbs() {
326 return ( $this->apiThumbCacheExpiry > 0 );
327 }
328 }