Check return value from wfMkdirParents() rather than proceeding and probably failing
[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, $flags = 0 ){
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 function fetchImageQuery( $query ) {
107 global $wgMemc;
108
109 $url = $this->mApiBase .
110 '?' .
111 wfArrayToCgi(
112 array_merge( $query,
113 array(
114 'format' => 'json',
115 'action' => 'query',
116 'redirects' => 'true' ) ) );
117
118 if( !isset( $this->mQueryCache[$url] ) ) {
119 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
120 $data = $wgMemc->get( $key );
121 if( !$data ) {
122 $data = Http::get( $url );
123 if ( !$data ) {
124 return null;
125 }
126 $wgMemc->set( $key, $data, 3600 );
127 }
128
129 if( count( $this->mQueryCache ) > 100 ) {
130 // Keep the cache from growing infinitely
131 $this->mQueryCache = array();
132 }
133 $this->mQueryCache[$url] = $data;
134 }
135 return FormatJson::decode( $this->mQueryCache[$url], true );
136 }
137
138 function getImageInfo( $data ) {
139 if( $data && isset( $data['query']['pages'] ) ) {
140 foreach( $data['query']['pages'] as $pageid => $info ) {
141 if( isset( $info['imageinfo'][0] ) ) {
142 return $info['imageinfo'][0];
143 }
144 }
145 }
146 return false;
147 }
148
149 function findBySha1( $hash ) {
150 $results = $this->fetchImageQuery( array(
151 'aisha1base36' => $hash,
152 'aiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
153 'list' => 'allimages', ) );
154 $ret = array();
155 if ( isset( $results['query']['allimages'] ) ) {
156 foreach ( $results['query']['allimages'] as $img ) {
157 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
158 }
159 }
160 return $ret;
161 }
162
163 function getThumbUrl( $name, $width=-1, $height=-1 ) {
164 $data = $this->fetchImageQuery( array(
165 'titles' => 'File:' . $name,
166 'iiprop' => 'url',
167 'iiurlwidth' => $width,
168 'iiurlheight' => $height,
169 'prop' => 'imageinfo' ) );
170 $info = $this->getImageInfo( $data );
171
172 if( $data && $info && $info['thumburl'] ) {
173 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
174 return $info['thumburl'];
175 } else {
176 return false;
177 }
178 }
179
180 function getThumbUrlFromCache( $name, $width, $height ) {
181 global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
182
183 if ( !$this->canCacheThumbs() ) {
184 return $this->getThumbUrl( $name, $width, $height );
185 }
186
187 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
188 if ( $thumbUrl = $wgMemc->get($key) ) {
189 wfDebug("Got thumb from local cache. $thumbUrl \n");
190 return $thumbUrl;
191 }
192 else {
193 $foreignUrl = $this->getThumbUrl( $name, $width, $height );
194 if( !$foreignUrl ) {
195 wfDebug( __METHOD__ . " Could not find thumburl\n" );
196 return false;
197 }
198 $thumb = Http::get( $foreignUrl );
199 if( !$thumb ) {
200 wfDebug( __METHOD__ . " Could not download thumb\n" );
201 return false;
202 }
203 // We need the same filename as the remote one :)
204 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
205 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
206 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
207 if( !wfMkdirParents($wgUploadDirectory . '/' . $path) ) {
208 wfDebug( __METHOD__ . " could not create directory for thumb\n" );
209 return $foreignUrl;
210 }
211 }
212 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
213 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
214 if( !file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb ) ) {
215 wfDebug( __METHOD__ . " could not write to thumb path\n" );
216 return $foreignUrl;
217 }
218 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
219 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
220 return $localUrl;
221 }
222 }
223
224 /**
225 * @see FileRepo::getZoneUrl()
226 */
227 function getZoneUrl( $zone ) {
228 switch ( $zone ) {
229 case 'public':
230 return $this->url;
231 case 'thumb':
232 return $this->thumbUrl;
233 default:
234 return parent::getZoneUrl( $zone );
235 }
236 }
237
238 /**
239 * Are we locally caching the thumbnails?
240 * @return bool
241 */
242 public function canCacheThumbs() {
243 return ( $this->apiThumbCacheExpiry > 0 );
244 }
245 }