Merge "[FileRepo] Added more upload profiling."
[lhc/web/wiklou.git] / includes / filerepo / ForeignAPIRepo.php
1 <?php
2 /**
3 * Foreign repository accessible through api.php requests.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileRepo
22 */
23
24 /**
25 * A foreign repository with a remote MediaWiki with an API thingy
26 *
27 * Example config:
28 *
29 * $wgForeignFileRepos[] = array(
30 * 'class' => 'ForeignAPIRepo',
31 * 'name' => 'shared',
32 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
33 * 'fetchDescription' => true, // Optional
34 * 'descriptionCacheExpiry' => 3600,
35 * );
36 *
37 * @ingroup FileRepo
38 */
39 class ForeignAPIRepo extends FileRepo {
40 /* This version string is used in the user agent for requests and will help
41 * server maintainers in identify ForeignAPI usage.
42 * Update the version every time you make breaking or significant changes. */
43 const VERSION = "2.1";
44
45 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
46 /* Check back with Commons after a day */
47 var $apiThumbCacheExpiry = 86400; /* 24*60*60 */
48 /* Redownload thumbnail files after a month */
49 var $fileCacheExpiry = 2592000; /* 86400*30 */
50
51 protected $mQueryCache = array();
52 protected $mFileExists = array();
53
54 function __construct( $info ) {
55 global $wgLocalFileRepo;
56 parent::__construct( $info );
57
58 // http://commons.wikimedia.org/w/api.php
59 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
60
61 if( isset( $info['apiThumbCacheExpiry'] ) ) {
62 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
63 }
64 if( isset( $info['fileCacheExpiry'] ) ) {
65 $this->fileCacheExpiry = $info['fileCacheExpiry'];
66 }
67 if( !$this->scriptDirUrl ) {
68 // hack for description fetches
69 $this->scriptDirUrl = dirname( $this->mApiBase );
70 }
71 // If we can cache thumbs we can guess sane defaults for these
72 if( $this->canCacheThumbs() && !$this->url ) {
73 $this->url = $wgLocalFileRepo['url'];
74 }
75 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
76 $this->thumbUrl = $this->url . '/thumb';
77 }
78 }
79
80 /**
81 * Per docs in FileRepo, this needs to return false if we don't support versioned
82 * files. Well, we don't.
83 *
84 * @return File
85 */
86 function newFile( $title, $time = false ) {
87 if ( $time ) {
88 return false;
89 }
90 return parent::newFile( $title, $time );
91 }
92
93 function fileExistsBatch( array $files ) {
94 $results = array();
95 foreach ( $files as $k => $f ) {
96 if ( isset( $this->mFileExists[$k] ) ) {
97 $results[$k] = true;
98 unset( $files[$k] );
99 } elseif( self::isVirtualUrl( $f ) ) {
100 # @todo FIXME: We need to be able to handle virtual
101 # URLs better, at least when we know they refer to the
102 # same repo.
103 $results[$k] = false;
104 unset( $files[$k] );
105 } elseif ( FileBackend::isStoragePath( $f ) ) {
106 $results[$k] = false;
107 unset( $files[$k] );
108 wfWarn( "Got mwstore:// path '$f'." );
109 }
110 }
111
112 $data = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
113 'prop' => 'imageinfo' ) );
114 if( isset( $data['query']['pages'] ) ) {
115 $i = 0;
116 foreach( $files as $key => $file ) {
117 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
118 $i++;
119 }
120 }
121 return $results;
122 }
123
124 function getFileProps( $virtualUrl ) {
125 return false;
126 }
127
128 function fetchImageQuery( $query ) {
129 global $wgMemc;
130
131 $query = array_merge( $query,
132 array(
133 'format' => 'json',
134 'action' => 'query',
135 'redirects' => 'true'
136 ) );
137 if ( $this->mApiBase ) {
138 $url = wfAppendQuery( $this->mApiBase, $query );
139 } else {
140 $url = $this->makeUrl( $query, 'api' );
141 }
142
143 if( !isset( $this->mQueryCache[$url] ) ) {
144 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
145 $data = $wgMemc->get( $key );
146 if( !$data ) {
147 $data = self::httpGet( $url );
148 if ( !$data ) {
149 return null;
150 }
151 $wgMemc->set( $key, $data, 3600 );
152 }
153
154 if( count( $this->mQueryCache ) > 100 ) {
155 // Keep the cache from growing infinitely
156 $this->mQueryCache = array();
157 }
158 $this->mQueryCache[$url] = $data;
159 }
160 return FormatJson::decode( $this->mQueryCache[$url], true );
161 }
162
163 function getImageInfo( $data ) {
164 if( $data && isset( $data['query']['pages'] ) ) {
165 foreach( $data['query']['pages'] as $info ) {
166 if( isset( $info['imageinfo'][0] ) ) {
167 return $info['imageinfo'][0];
168 }
169 }
170 }
171 return false;
172 }
173
174 function findBySha1( $hash ) {
175 $results = $this->fetchImageQuery( array(
176 'aisha1base36' => $hash,
177 'aiprop' => ForeignAPIFile::getProps(),
178 'list' => 'allimages', ) );
179 $ret = array();
180 if ( isset( $results['query']['allimages'] ) ) {
181 foreach ( $results['query']['allimages'] as $img ) {
182 // 1.14 was broken, doesn't return name attribute
183 if( !isset( $img['name'] ) ) {
184 continue;
185 }
186 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
187 }
188 }
189 return $ret;
190 }
191
192 function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
193 $data = $this->fetchImageQuery( array(
194 'titles' => 'File:' . $name,
195 'iiprop' => 'url|timestamp',
196 'iiurlwidth' => $width,
197 'iiurlheight' => $height,
198 'iiurlparam' => $otherParams,
199 'prop' => 'imageinfo' ) );
200 $info = $this->getImageInfo( $data );
201
202 if( $data && $info && isset( $info['thumburl'] ) ) {
203 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
204 $result = $info;
205 return $info['thumburl'];
206 } else {
207 return false;
208 }
209 }
210
211 /**
212 * Return the imageurl from cache if possible
213 *
214 * If the url has been requested today, get it from cache
215 * Otherwise retrieve remote thumb url, check for local file.
216 *
217 * @param $name String is a dbkey form of a title
218 * @param $width
219 * @param $height
220 * @param String $param Other rendering parameters (page number, etc) from handler's makeParamString.
221 * @return bool|string
222 */
223 function getThumbUrlFromCache( $name, $width, $height, $params="" ) {
224 global $wgMemc;
225 // We can't check the local cache using FileRepo functions because
226 // we override fileExistsBatch(). We have to use the FileBackend directly.
227 $backend = $this->getBackend(); // convenience
228
229 if ( !$this->canCacheThumbs() ) {
230 $result = null; // can't pass "null" by reference, but it's ok as default value
231 return $this->getThumbUrl( $name, $width, $height, $result, $params );
232 }
233 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
234 $sizekey = "$width:$height:$params";
235
236 /* Get the array of urls that we already know */
237 $knownThumbUrls = $wgMemc->get($key);
238 if( !$knownThumbUrls ) {
239 /* No knownThumbUrls for this file */
240 $knownThumbUrls = array();
241 } else {
242 if( isset( $knownThumbUrls[$sizekey] ) ) {
243 wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
244 "{$knownThumbUrls[$sizekey]} \n");
245 return $knownThumbUrls[$sizekey];
246 }
247 /* This size is not yet known */
248 }
249
250 $metadata = null;
251 $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
252
253 if( !$foreignUrl ) {
254 wfDebug( __METHOD__ . " Could not find thumburl\n" );
255 return false;
256 }
257
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;
263 }
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 );
267
268 if( $backend->fileExists( array( 'src' => $localFilename ) )
269 && isset( $metadata['timestamp'] ) )
270 {
271 wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
272 $modified = $backend->getFileTimestamp( array( 'src' => $localFilename ) );
273 $remoteModified = strtotime( $metadata['timestamp'] );
274 $current = time();
275 $diff = abs( $modified - $current );
276 if( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
277 /* Use our current and already downloaded thumbnail */
278 $knownThumbUrls[$sizekey] = $localUrl;
279 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
280 return $localUrl;
281 }
282 /* There is a new Commons file, or existing thumbnail older than a month */
283 }
284 $thumb = self::httpGet( $foreignUrl );
285 if( !$thumb ) {
286 wfDebug( __METHOD__ . " Could not download thumb\n" );
287 return false;
288 }
289
290 # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
291 $backend->prepare( array( 'dir' => dirname( $localFilename ) ) );
292 $op = array( 'op' => 'create', 'dst' => $localFilename, 'content' => $thumb );
293 if( !$backend->doOperation( $op )->isOK() ) {
294 wfRestoreWarnings();
295 wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'\n" );
296 return $foreignUrl;
297 }
298 $knownThumbUrls[$sizekey] = $localUrl;
299 $wgMemc->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
300 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
301 return $localUrl;
302 }
303
304 /**
305 * @see FileRepo::getZoneUrl()
306 * @return String
307 */
308 function getZoneUrl( $zone ) {
309 switch ( $zone ) {
310 case 'public':
311 return $this->url;
312 case 'thumb':
313 return $this->thumbUrl;
314 default:
315 return parent::getZoneUrl( $zone );
316 }
317 }
318
319 /**
320 * Get the local directory corresponding to one of the basic zones
321 * @return bool|null|string
322 */
323 function getZonePath( $zone ) {
324 $supported = array( 'public', 'thumb' );
325 if ( in_array( $zone, $supported ) ) {
326 return parent::getZonePath( $zone );
327 }
328 return false;
329 }
330
331 /**
332 * Are we locally caching the thumbnails?
333 * @return bool
334 */
335 public function canCacheThumbs() {
336 return ( $this->apiThumbCacheExpiry > 0 );
337 }
338
339 /**
340 * The user agent the ForeignAPIRepo will use.
341 * @return string
342 */
343 public static function getUserAgent() {
344 return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
345 }
346
347 /**
348 * Like a Http:get request, but with custom User-Agent.
349 * @see Http:get
350 * @return bool|String
351 */
352 public static function httpGet( $url, $timeout = 'default', $options = array() ) {
353 $options['timeout'] = $timeout;
354 /* Http::get */
355 $url = wfExpandUrl( $url, PROTO_HTTP );
356 wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
357 $options['method'] = "GET";
358
359 if ( !isset( $options['timeout'] ) ) {
360 $options['timeout'] = 'default';
361 }
362
363 $req = MWHttpRequest::factory( $url, $options );
364 $req->setUserAgent( ForeignAPIRepo::getUserAgent() );
365 $status = $req->execute();
366
367 if ( $status->isOK() ) {
368 return $req->getContent();
369 } else {
370 return false;
371 }
372 }
373
374 function enumFiles( $callback ) {
375 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
376 }
377
378 protected function assertWritableRepo() {
379 throw new MWException( get_class( $this ) . ': write operations are not supported.' );
380 }
381 }