fixes #22501 follow up r61101 remove superfluous, buggy code that was over-rideing...
[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 $this->mApiBase = $info['apibase']; // http://commons.wikimedia.org/w/api.php
29 if( isset( $info['apiThumbCacheExpiry'] ) ) {
30 $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
31 }
32 if( !$this->scriptDirUrl ) {
33 // hack for description fetches
34 $this->scriptDirUrl = dirname( $this->mApiBase );
35 }
36 // If we can cache thumbs we can guess sane defaults for these
37 if( $this->canCacheThumbs() && !$this->url ) {
38 global $wgLocalFileRepo;
39 $this->url = $wgLocalFileRepo['url'];
40 }
41 if( $this->canCacheThumbs() && !$this->thumbUrl ) {
42 $this->thumbUrl = $this->url . '/thumb';
43 }
44 }
45
46 /**
47 * Per docs in FileRepo, this needs to return false if we don't support versioned
48 * files. Well, we don't.
49 */
50 function newFile( $title, $time = false ) {
51 if ( $time ) {
52 return false;
53 }
54 return parent::newFile( $title, $time );
55 }
56
57 /**
58 * No-ops
59 */
60 function storeBatch( $triplets, $flags = 0 ) {
61 return false;
62 }
63 function storeTemp( $originalName, $srcPath ) {
64 return false;
65 }
66 function append( $srcPath, $toAppendPath ){
67 return false;
68 }
69 function publishBatch( $triplets, $flags = 0 ) {
70 return false;
71 }
72 function deleteBatch( $sourceDestPairs ) {
73 return false;
74 }
75
76
77 function fileExistsBatch( $files, $flags = 0 ) {
78 $results = array();
79 foreach ( $files as $k => $f ) {
80 if ( isset( $this->mFileExists[$k] ) ) {
81 $results[$k] = true;
82 unset( $files[$k] );
83 } elseif( self::isVirtualUrl( $f ) ) {
84 # TODO! FIXME! We need to be able to handle virtual
85 # URLs better, at least when we know they refer to the
86 # same repo.
87 $results[$k] = false;
88 unset( $files[$k] );
89 }
90 }
91
92 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
93 'prop' => 'imageinfo' ) );
94 if( isset( $data['query']['pages'] ) ) {
95 $i = 0;
96 foreach( $files as $key => $file ) {
97 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
98 $i++;
99 }
100 }
101 }
102 function getFileProps( $virtualUrl ) {
103 return false;
104 }
105
106 protected function queryImage( $query ) {
107 $data = $this->fetchImageQuery( $query );
108
109 if( isset( $data['query']['pages'] ) ) {
110 foreach( $data['query']['pages'] as $pageid => $info ) {
111 if( isset( $info['imageinfo'][0] ) ) {
112 return $info['imageinfo'][0];
113 }
114 }
115 }
116 return false;
117 }
118
119 protected function fetchImageQuery( $query ) {
120 global $wgMemc;
121
122 $url = $this->mApiBase .
123 '?' .
124 wfArrayToCgi(
125 array_merge( $query,
126 array(
127 'format' => 'json',
128 'action' => 'query' ) ) );
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( $title, $time = false ) {
151 return $this->queryImage( array(
152 'titles' => 'Image:' . $title->getText(),
153 'iiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
154 'prop' => 'imageinfo' ) );
155 }
156
157 function findBySha1( $hash ) {
158 $results = $this->fetchImageQuery( array(
159 'aisha1base36' => $hash,
160 'aiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
161 'list' => 'allimages', ) );
162 $ret = array();
163 if ( isset( $results['query']['allimages'] ) ) {
164 foreach ( $results['query']['allimages'] as $img ) {
165 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
166 }
167 }
168 return $ret;
169 }
170
171 function getThumbUrl( $name, $width=-1, $height=-1 ) {
172 $info = $this->queryImage( array(
173 'titles' => 'Image:' . $name,
174 'iiprop' => 'url',
175 'iiurlwidth' => $width,
176 'iiurlheight' => $height,
177 'prop' => 'imageinfo' ) );
178 if( $info ) {
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
201 // We need the same filename as the remote one :)
202 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
203 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
204 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
205 wfMkdirParents($wgUploadDirectory . '/' . $path);
206 }
207 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
208 $thumb = Http::get( $foreignUrl );
209 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
210 if( !file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb ) ) {
211 wfDebug( __METHOD__ . " could not write to thumb path\n" );
212 return $foreignUrl;
213 }
214 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
215 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
216 return $localUrl;
217 }
218 }
219
220 /**
221 * @see FileRepo::getZoneUrl()
222 */
223 function getZoneUrl( $zone ) {
224 switch ( $zone ) {
225 case 'public':
226 return $this->url;
227 case 'thumb':
228 return $this->thumbUrl;
229 default:
230 return parent::getZoneUrl( $zone );
231 }
232 }
233
234 /**
235 * Are we locally caching the thumbnails?
236 * @return bool
237 */
238 public function canCacheThumbs() {
239 return ( $this->apiThumbCacheExpiry > 0 );
240 }
241 }