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