Big attack on unused variables...
[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 var $apiThumbCacheExpiry = 86400;
29 protected $mQueryCache = array();
30 protected $mFileExists = array();
31
32 function __construct( $info ) {
33 parent::__construct( $info );
34
35 // http://commons.wikimedia.org/w/api.php
36 $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
37
38 if( isset( $info['apiThumbCacheExpiry'] ) ) {
39 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
40 }
41 if( !$this->scriptDirUrl ) {
42 // hack for description fetches
43 $this->scriptDirUrl = dirname( $this->mApiBase );
44 }
45 // If we can cache thumbs we can guess sane defaults for these
46 if( $this->canCacheThumbs() && !$this->url ) {
47 global $wgLocalFileRepo;
48 $this->url = $wgLocalFileRepo['url'];
49 }
50 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
51 $this->thumbUrl = $this->url . '/thumb';
52 }
53 }
54
55 /**
56 * Per docs in FileRepo, this needs to return false if we don't support versioned
57 * files. Well, we don't.
58 */
59 function newFile( $title, $time = false ) {
60 if ( $time ) {
61 return false;
62 }
63 return parent::newFile( $title, $time );
64 }
65
66 /**
67 * No-ops
68 */
69 function storeBatch( $triplets, $flags = 0 ) {
70 return false;
71 }
72 function storeTemp( $originalName, $srcPath ) {
73 return false;
74 }
75 function append( $srcPath, $toAppendPath, $flags = 0 ){
76 return false;
77 }
78 function publishBatch( $triplets, $flags = 0 ) {
79 return false;
80 }
81 function deleteBatch( $sourceDestPairs ) {
82 return false;
83 }
84
85
86 function fileExistsBatch( $files, $flags = 0 ) {
87 $results = array();
88 foreach ( $files as $k => $f ) {
89 if ( isset( $this->mFileExists[$k] ) ) {
90 $results[$k] = true;
91 unset( $files[$k] );
92 } elseif( self::isVirtualUrl( $f ) ) {
93 # TODO! FIXME! We need to be able to handle virtual
94 # URLs better, at least when we know they refer to the
95 # same repo.
96 $results[$k] = false;
97 unset( $files[$k] );
98 }
99 }
100
101 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
102 'prop' => 'imageinfo' ) );
103 if( isset( $data['query']['pages'] ) ) {
104 $i = 0;
105 foreach( $files as $key => $file ) {
106 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
107 $i++;
108 }
109 }
110 }
111 function getFileProps( $virtualUrl ) {
112 return false;
113 }
114
115 function fetchImageQuery( $query ) {
116 global $wgMemc;
117
118 $query = array_merge( $query,
119 array(
120 'format' => 'json',
121 'action' => 'query',
122 'redirects' => 'true'
123 ) );
124 if ( $this->mApiBase ) {
125 $url = wfAppendQuery( $this->mApiBase, $query );
126 } else {
127 $url = $this->makeUrl( $query, 'api' );
128 }
129
130 if( !isset( $this->mQueryCache[$url] ) ) {
131 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
132 $data = $wgMemc->get( $key );
133 if( !$data ) {
134 $data = Http::get( $url );
135 if ( !$data ) {
136 return null;
137 }
138 $wgMemc->set( $key, $data, 3600 );
139 }
140
141 if( count( $this->mQueryCache ) > 100 ) {
142 // Keep the cache from growing infinitely
143 $this->mQueryCache = array();
144 }
145 $this->mQueryCache[$url] = $data;
146 }
147 return FormatJson::decode( $this->mQueryCache[$url], true );
148 }
149
150 function getImageInfo( $data ) {
151 if( $data && isset( $data['query']['pages'] ) ) {
152 foreach( $data['query']['pages'] as $info ) {
153 if( isset( $info['imageinfo'][0] ) ) {
154 return $info['imageinfo'][0];
155 }
156 }
157 }
158 return false;
159 }
160
161 function findBySha1( $hash ) {
162 $results = $this->fetchImageQuery( array(
163 'aisha1base36' => $hash,
164 'aiprop' => ForeignAPIFile::getProps(),
165 'list' => 'allimages', ) );
166 $ret = array();
167 if ( isset( $results['query']['allimages'] ) ) {
168 foreach ( $results['query']['allimages'] as $img ) {
169 // 1.14 was broken, doesn't return name attribute
170 if( !isset( $img['name'] ) ) {
171 continue;
172 }
173 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
174 }
175 }
176 return $ret;
177 }
178
179 function getThumbUrl( $name, $width=-1, $height=-1 ) {
180 $data = $this->fetchImageQuery( array(
181 'titles' => 'File:' . $name,
182 'iiprop' => 'url',
183 'iiurlwidth' => $width,
184 'iiurlheight' => $height,
185 'prop' => 'imageinfo' ) );
186 $info = $this->getImageInfo( $data );
187
188 if( $data && $info && $info['thumburl'] ) {
189 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
190 return $info['thumburl'];
191 } else {
192 return false;
193 }
194 }
195
196 function getThumbUrlFromCache( $name, $width, $height ) {
197 global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
198
199 if ( !$this->canCacheThumbs() ) {
200 return $this->getThumbUrl( $name, $width, $height );
201 }
202
203 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
204 if ( $thumbUrl = $wgMemc->get($key) ) {
205 wfDebug("Got thumb from local cache. $thumbUrl \n");
206 return $thumbUrl;
207 }
208 else {
209 $foreignUrl = $this->getThumbUrl( $name, $width, $height );
210 if( !$foreignUrl ) {
211 wfDebug( __METHOD__ . " Could not find thumburl\n" );
212 return false;
213 }
214 $thumb = Http::get( $foreignUrl );
215 if( !$thumb ) {
216 wfDebug( __METHOD__ . " Could not download thumb\n" );
217 return false;
218 }
219 // We need the same filename as the remote one :)
220 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
221 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
222 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
223 if( !wfMkdirParents($wgUploadDirectory . '/' . $path) ) {
224 wfDebug( __METHOD__ . " could not create directory for thumb\n" );
225 return $foreignUrl;
226 }
227 }
228 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
229 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
230 wfSuppressWarnings();
231 if( !file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb ) ) {
232 wfRestoreWarnings();
233 wfDebug( __METHOD__ . " could not write to thumb path\n" );
234 return $foreignUrl;
235 }
236 wfRestoreWarnings();
237 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
238 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
239 return $localUrl;
240 }
241 }
242
243 /**
244 * @see FileRepo::getZoneUrl()
245 */
246 function getZoneUrl( $zone ) {
247 switch ( $zone ) {
248 case 'public':
249 return $this->url;
250 case 'thumb':
251 return $this->thumbUrl;
252 default:
253 return parent::getZoneUrl( $zone );
254 }
255 }
256
257 /**
258 * Are we locally caching the thumbnails?
259 * @return bool
260 */
261 public function canCacheThumbs() {
262 return ( $this->apiThumbCacheExpiry > 0 );
263 }
264 }