* Added scriptExtension setting to $wgForeignFileRepos
[lhc/web/wiklou.git] / includes / filerepo / ForeignAPIRepo.php
1 <?php
2
3 /**
4 * A foreign repository with a remote MediaWiki with an API thingy
5 * Very hacky and inefficient
6 * do not use except for testing :D
7 *
8 * Example config:
9 *
10 * $wgForeignFileRepos[] = array(
11 * 'class' => 'ForeignAPIRepo',
12 * 'name' => 'shared',
13 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
14 * 'fetchDescription' => true, // Optional
15 * 'descriptionCacheExpiry' => 3600,
16 * );
17 *
18 * @ingroup FileRepo
19 */
20 class ForeignAPIRepo extends FileRepo {
21 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
22 var $apiThumbCacheExpiry = 86400;
23 protected $mQueryCache = array();
24 protected $mFileExists = array();
25
26 function __construct( $info ) {
27 parent::__construct( $info );
28
29 // http://commons.wikimedia.org/w/api.php
30 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
31
32 if( isset( $info['apiThumbCacheExpiry'] ) ) {
33 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
34 }
35 if( !$this->scriptDirUrl ) {
36 // hack for description fetches
37 $this->scriptDirUrl = dirname( $this->mApiBase );
38 }
39 // If we can cache thumbs we can guess sane defaults for these
40 if( $this->canCacheThumbs() && !$this->url ) {
41 global $wgLocalFileRepo;
42 $this->url = $wgLocalFileRepo['url'];
43 }
44 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
45 $this->thumbUrl = $this->url . '/thumb';
46 }
47 }
48
49 /**
50 * Per docs in FileRepo, this needs to return false if we don't support versioned
51 * files. Well, we don't.
52 */
53 function newFile( $title, $time = false ) {
54 if ( $time ) {
55 return false;
56 }
57 return parent::newFile( $title, $time );
58 }
59
60 /**
61 * No-ops
62 */
63 function storeBatch( $triplets, $flags = 0 ) {
64 return false;
65 }
66 function storeTemp( $originalName, $srcPath ) {
67 return false;
68 }
69 function append( $srcPath, $toAppendPath, $flags = 0 ){
70 return false;
71 }
72 function publishBatch( $triplets, $flags = 0 ) {
73 return false;
74 }
75 function deleteBatch( $sourceDestPairs ) {
76 return false;
77 }
78
79
80 function fileExistsBatch( $files, $flags = 0 ) {
81 $results = array();
82 foreach ( $files as $k => $f ) {
83 if ( isset( $this->mFileExists[$k] ) ) {
84 $results[$k] = true;
85 unset( $files[$k] );
86 } elseif( self::isVirtualUrl( $f ) ) {
87 # TODO! FIXME! We need to be able to handle virtual
88 # URLs better, at least when we know they refer to the
89 # same repo.
90 $results[$k] = false;
91 unset( $files[$k] );
92 }
93 }
94
95 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
96 'prop' => 'imageinfo' ) );
97 if( isset( $data['query']['pages'] ) ) {
98 $i = 0;
99 foreach( $files as $key => $file ) {
100 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
101 $i++;
102 }
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 = Http::get( $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 $pageid => $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 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
164 }
165 }
166 return $ret;
167 }
168
169 function getThumbUrl( $name, $width=-1, $height=-1 ) {
170 $data = $this->fetchImageQuery( array(
171 'titles' => 'File:' . $name,
172 'iiprop' => 'url',
173 'iiurlwidth' => $width,
174 'iiurlheight' => $height,
175 'prop' => 'imageinfo' ) );
176 $info = $this->getImageInfo( $data );
177
178 if( $data && $info && $info['thumburl'] ) {
179 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
180 return $info['thumburl'];
181 } else {
182 return false;
183 }
184 }
185
186 function getThumbUrlFromCache( $name, $width, $height ) {
187 global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
188
189 if ( !$this->canCacheThumbs() ) {
190 return $this->getThumbUrl( $name, $width, $height );
191 }
192
193 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
194 if ( $thumbUrl = $wgMemc->get($key) ) {
195 wfDebug("Got thumb from local cache. $thumbUrl \n");
196 return $thumbUrl;
197 }
198 else {
199 $foreignUrl = $this->getThumbUrl( $name, $width, $height );
200 if( !$foreignUrl ) {
201 wfDebug( __METHOD__ . " Could not find thumburl\n" );
202 return false;
203 }
204 $thumb = Http::get( $foreignUrl );
205 if( !$thumb ) {
206 wfDebug( __METHOD__ . " Could not download thumb\n" );
207 return false;
208 }
209 // We need the same filename as the remote one :)
210 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
211 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
212 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
213 if( !wfMkdirParents($wgUploadDirectory . '/' . $path) ) {
214 wfDebug( __METHOD__ . " could not create directory for thumb\n" );
215 return $foreignUrl;
216 }
217 }
218 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
219 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
220 wfSuppressWarnings();
221 if( !file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb ) ) {
222 wfRestoreWarnings();
223 wfDebug( __METHOD__ . " could not write to thumb path\n" );
224 return $foreignUrl;
225 }
226 wfRestoreWarnings();
227 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
228 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
229 return $localUrl;
230 }
231 }
232
233 /**
234 * @see FileRepo::getZoneUrl()
235 */
236 function getZoneUrl( $zone ) {
237 switch ( $zone ) {
238 case 'public':
239 return $this->url;
240 case 'thumb':
241 return $this->thumbUrl;
242 default:
243 return parent::getZoneUrl( $zone );
244 }
245 }
246
247 /**
248 * Are we locally caching the thumbnails?
249 * @return bool
250 */
251 public function canCacheThumbs() {
252 return ( $this->apiThumbCacheExpiry > 0 );
253 }
254 }