(bug 23703) ForeignAPIRepo fails on findBySha1() when using a 1.14 install as a repos...
[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 // 1.14 was broken, doesn't return name attribute
164 if( !isset( $img['name'] ) ) {
165 continue;
166 }
167 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
168 }
169 }
170 return $ret;
171 }
172
173 function getThumbUrl( $name, $width=-1, $height=-1 ) {
174 $data = $this->fetchImageQuery( array(
175 'titles' => 'File:' . $name,
176 'iiprop' => 'url',
177 'iiurlwidth' => $width,
178 'iiurlheight' => $height,
179 'prop' => 'imageinfo' ) );
180 $info = $this->getImageInfo( $data );
181
182 if( $data && $info && $info['thumburl'] ) {
183 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
184 return $info['thumburl'];
185 } else {
186 return false;
187 }
188 }
189
190 function getThumbUrlFromCache( $name, $width, $height ) {
191 global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
192
193 if ( !$this->canCacheThumbs() ) {
194 return $this->getThumbUrl( $name, $width, $height );
195 }
196
197 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
198 if ( $thumbUrl = $wgMemc->get($key) ) {
199 wfDebug("Got thumb from local cache. $thumbUrl \n");
200 return $thumbUrl;
201 }
202 else {
203 $foreignUrl = $this->getThumbUrl( $name, $width, $height );
204 if( !$foreignUrl ) {
205 wfDebug( __METHOD__ . " Could not find thumburl\n" );
206 return false;
207 }
208 $thumb = Http::get( $foreignUrl );
209 if( !$thumb ) {
210 wfDebug( __METHOD__ . " Could not download thumb\n" );
211 return false;
212 }
213 // We need the same filename as the remote one :)
214 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
215 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
216 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
217 if( !wfMkdirParents($wgUploadDirectory . '/' . $path) ) {
218 wfDebug( __METHOD__ . " could not create directory for thumb\n" );
219 return $foreignUrl;
220 }
221 }
222 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
223 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
224 wfSuppressWarnings();
225 if( !file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb ) ) {
226 wfRestoreWarnings();
227 wfDebug( __METHOD__ . " could not write to thumb path\n" );
228 return $foreignUrl;
229 }
230 wfRestoreWarnings();
231 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
232 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
233 return $localUrl;
234 }
235 }
236
237 /**
238 * @see FileRepo::getZoneUrl()
239 */
240 function getZoneUrl( $zone ) {
241 switch ( $zone ) {
242 case 'public':
243 return $this->url;
244 case 'thumb':
245 return $this->thumbUrl;
246 default:
247 return parent::getZoneUrl( $zone );
248 }
249 }
250
251 /**
252 * Are we locally caching the thumbnails?
253 * @return bool
254 */
255 public function canCacheThumbs() {
256 return ( $this->apiThumbCacheExpiry > 0 );
257 }
258 }