(bug 26130) Revert changes to WebStart.php in r72349, which turn out to have been...
[lhc/web/wiklou.git] / includes / upload / UploadStash.php
1 <?php
2 /**
3 * UploadStash is intended to accomplish a few things:
4 * - enable applications to temporarily stash files without publishing them to the wiki.
5 * - Several parts of MediaWiki do this in similar ways: UploadBase, UploadWizard, and FirefoggChunkedExtension
6 * And there are several that reimplement stashing from scratch, in idiosyncratic ways. The idea is to unify them all here.
7 * Mostly all of them are the same except for storing some custom fields, which we subsume into the data array.
8 * - enable applications to find said files later, as long as the session or temp files haven't been purged.
9 * - enable the uploading user (and *ONLY* the uploading user) to access said files, and thumbnails of said files, via a URL.
10 * We accomplish this by making the session serve as a URL->file mapping, on the assumption that nobody else can access
11 * the session, even the uploading user. See SpecialUploadStash, which implements a web interface to some files stored this way.
12 */
13 class UploadStash {
14
15 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
16 const KEY_FORMAT_REGEX = '/^[\w-]+\.\w+$/';
17
18 // repository that this uses to store temp files
19 // public because we sometimes need to get a LocalFile within the same repo.
20 public $repo;
21
22 // array of initialized objects obtained from session (lazily initialized upon getFile())
23 private $files = array();
24
25 // Session ID
26 private $sessionID;
27
28 // Cache to store stash metadata in
29 private $cache;
30
31 // TODO: Once UploadBase starts using this, switch to use these constants rather than UploadBase::SESSION*
32 // const SESSION_VERSION = 2;
33 // const SESSION_KEYNAME = 'wsUploadData';
34
35 /**
36 * Represents the session which contains temporarily stored files.
37 * Designed to be compatible with the session stashing code in UploadBase (should replace it eventually)
38 *
39 * @param $repo FileRepo: optional -- repo in which to store files. Will choose LocalRepo if not supplied.
40 */
41 public function __construct( $repo = null ) {
42
43 if ( is_null( $repo ) ) {
44 $repo = RepoGroup::singleton()->getLocalRepo();
45 }
46
47 $this->repo = $repo;
48
49 if ( session_id() === '' ) {
50 // FIXME: Should we just start a session in this case?
51 // Anonymous uploading could be allowed
52 throw new UploadStashNotAvailableException( 'no session ID' );
53 }
54 $this->sessionID = '';
55 $this->cache = wfGetCache( CACHE_ANYTHING );
56 }
57
58 /**
59 * Get a file and its metadata from the stash.
60 * May throw exception if session data cannot be parsed due to schema change, or key not found.
61 *
62 * @param $key Integer: key
63 * @throws UploadStashFileNotFoundException
64 * @throws UploadStashBadVersionException
65 * @return UploadStashFile
66 */
67 public function getFile( $key ) {
68 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
69 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
70 }
71
72 if ( !isset( $this->files[$key] ) ) {
73 $cacheKey = wfMemcKey( 'uploadstash', $this->sessionID, $key );
74 $data = $this->cache->get( $cacheKey );
75 if ( !$data ) {
76 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
77 }
78
79 $this->files[$key] = $this->getFileFromData( $data );
80
81 }
82 return $this->files[$key];
83 }
84
85 protected function getFileFromData( $data ) {
86 // guards against PHP class changing while session data doesn't
87 if ( $data['version'] !== UploadBase::SESSION_VERSION ) {
88 throw new UploadStashBadVersionException( $data['version'] . " does not match current version " . UploadBase::SESSION_VERSION );
89 }
90
91 // separate the stashData into the path, and then the rest of the data
92 $path = $data['mTempPath'];
93 unset( $data['mTempPath'] );
94
95 $file = new UploadStashFile( $this, $this->repo, $path, $key, $data );
96 if ( $file->getSize() === 0 ) {
97 throw new UploadStashZeroLengthFileException( "File is zero length" );
98 }
99 return $file;
100 }
101
102 /**
103 * Stash a file in a temp directory and record that we did this in the session, along with other metadata.
104 * We store data in a flat key-val namespace because that's how UploadBase did it. This also means we have to
105 * ensure that the key-val pairs in $data do not overwrite other required fields.
106 *
107 * @param $path String: path to file you want stashed
108 * @param $data Array: optional, other data you want associated with the file. Do not use 'mTempPath', 'mFileProps', 'mFileSize', or 'version' as keys here
109 * @param $key String: optional, unique key for this file in this session. Used for directory hashing when storing, otherwise not important
110 * @throws UploadStashBadPathException
111 * @throws UploadStashFileException
112 * @return UploadStashFile: file, or null on failure
113 */
114 public function stashFile( $path, $data = array(), $key = null ) {
115 if ( ! file_exists( $path ) ) {
116 wfDebug( "UploadStash: tried to stash file at '$path', but it doesn't exist\n" );
117 throw new UploadStashBadPathException( "path doesn't exist" );
118 }
119 $fileProps = File::getPropsFromPath( $path );
120
121 // we will be initializing from some tmpnam files that don't have extensions.
122 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
123 $extension = self::getExtensionForPath( $path );
124 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
125 $pathWithGoodExtension = "$path.$extension";
126 if ( ! rename( $path, $pathWithGoodExtension ) ) {
127 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
128 }
129 $path = $pathWithGoodExtension;
130 }
131
132 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
133 // uploaded this session, which could happen if uploads had failed.
134 if ( is_null( $key ) ) {
135 $key = $fileProps['sha1'] . "." . $extension;
136 }
137
138 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
139 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
140 }
141
142
143 // if not already in a temporary area, put it there
144 $status = $this->repo->storeTemp( basename( $path ), $path );
145
146 if( ! $status->isOK() ) {
147 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
148 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
149 // This is a bit lame, as we may have more info in the $status and we're throwing it away, but to fix it means
150 // redesigning API errors significantly.
151 // $status->value just contains the virtual URL (if anything) which is probably useless to the caller
152 $error = reset( $status->getErrorsArray() );
153 if ( ! count( $error ) ) {
154 $error = reset( $status->getWarningsArray() );
155 if ( ! count( $error ) ) {
156 $error = array( 'unknown', 'no error recorded' );
157 }
158 }
159 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
160 }
161 $stashPath = $status->value;
162
163 // required info we always store. Must trump any other application info in $data
164 // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
165 // chosen for compatibility with UploadBase's way of doing this.
166 $requiredData = array(
167 'mTempPath' => $stashPath,
168 'mFileSize' => $fileProps['size'],
169 'mFileProps' => $fileProps,
170 'version' => UploadBase::SESSION_VERSION
171 );
172
173 // now, merge required info and extra data into the session. (The extra data changes from application to application.
174 // UploadWizard wants different things than say FirefoggChunkedUpload.)
175 $finalData = array_merge( $data, $requiredData );
176
177 global $wgUploadStashExpiry;
178 wfDebug( __METHOD__ . " storing under $key\n" );
179 $cacheKey = wfMemcKey( 'uploadstash', $this->sessionID, $key );
180 $this->cache->set( $cacheKey, array_merge( $data, $requiredData ), $wgUploadStashExpiry );
181
182 $this->files[$key] = $this->getFileFromData( $data );
183 return $this->files[$key];
184 }
185
186 /**
187 * Find or guess extension -- ensuring that our extension matches our mime type.
188 * Since these files are constructed from php tempnames they may not start off
189 * with an extension.
190 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
191 * uploads versus the desired filename. Maybe we can get that passed to us...
192 */
193 public static function getExtensionForPath( $path ) {
194 // Does this have an extension?
195 $n = strrpos( $path, '.' );
196 $extension = null;
197 if ( $n !== false ) {
198 $extension = $n ? substr( $path, $n + 1 ) : '';
199 } else {
200 // If not, assume that it should be related to the mime type of the original file.
201 $magic = MimeMagic::singleton();
202 $mimeType = $magic->guessMimeType( $path );
203 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
204 if ( count( $extensions ) ) {
205 $extension = $extensions[0];
206 }
207 }
208
209 if ( is_null( $extension ) ) {
210 throw new UploadStashFileException( "extension is null" );
211 }
212
213 return File::normalizeExtension( $extension );
214 }
215
216 }
217
218 class UploadStashFile extends UnregisteredLocalFile {
219 private $sessionStash;
220 private $sessionKey;
221 private $sessionData;
222 private $urlName;
223
224 /**
225 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
226 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
227 *
228 * @param $stash UploadStash: useful for obtaining config, stashing transformed files
229 * @param $repo FileRepo: repository where we should find the path
230 * @param $path String: path to file
231 * @param $key String: key to store the path and any stashed data under
232 * @param $data String: any other data we want stored with this file
233 * @throws UploadStashBadPathException
234 * @throws UploadStashFileNotFoundException
235 */
236 public function __construct( $stash, $repo, $path, $key, $data ) {
237 $this->sessionStash = $stash;
238 $this->sessionKey = $key;
239 $this->sessionData = $data;
240
241 // resolve mwrepo:// urls
242 if ( $repo->isVirtualUrl( $path ) ) {
243 $path = $repo->resolveVirtualUrl( $path );
244 }
245
246 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
247 $repoTempPath = $repo->getZonePath( 'temp' );
248 if ( ( ! $repo->validateFilename( $path ) ) ||
249 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
250 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
251 throw new UploadStashBadPathException( 'path is not valid' );
252 }
253
254 // check if path exists! and is a plain file.
255 if ( ! $repo->fileExists( $path, FileRepo::FILES_ONLY ) ) {
256 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
257 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
258 }
259
260
261
262 parent::__construct( false, $repo, $path, false );
263
264 $this->name = basename( $this->path );
265 }
266
267 /**
268 * A method needed by the file transforming and scaling routines in File.php
269 * We do not necessarily care about doing the description at this point
270 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
271 * convert require it to be there)
272 *
273 * @return String: dummy value
274 */
275 public function getDescriptionUrl() {
276 return $this->getUrl();
277 }
278
279 /**
280 * Get the path for the thumbnail (actually any transformation of this file)
281 * The actual argument is the result of thumbName although we seem to have
282 * buggy code elsewhere that expects a boolean 'suffix'
283 *
284 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
285 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
286 */
287 public function getThumbPath( $thumbName = false ) {
288 $path = dirname( $this->path );
289 if ( $thumbName !== false ) {
290 $path .= "/$thumbName";
291 }
292 return $path;
293 }
294
295 /**
296 * Return the file/url base name of a thumbnail with the specified parameters
297 *
298 * @param $params Array: handler-specific parameters
299 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
300 */
301 function thumbName( $params ) {
302 return $this->getParamThumbName( $this->getUrlName(), $params );
303 }
304
305
306 /**
307 * Given the name of the original, i.e. Foo.jpg, and scaling parameters, returns filename with appropriate extension
308 * This is abstracted from getThumbName because we also use it to calculate the thumbname the file should have on
309 * remote image scalers
310 *
311 * @param String $urlName: A filename, like MyMovie.ogx
312 * @param Array $parameters: scaling parameters, like array( 'width' => '120' );
313 * @return String|null parameterized thumb name, like 120px-MyMovie.ogx.jpg, or null if no handler found
314 */
315 function getParamThumbName( $urlName, $params ) {
316 if ( !$this->getHandler() ) {
317 return null;
318 }
319 $extension = $this->getExtension();
320 list( $thumbExt, ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
321 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $urlName;
322 if ( $thumbExt != $extension ) {
323 $thumbName .= ".$thumbExt";
324 }
325 return $thumbName;
326 }
327
328 /**
329 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
330 * @param {String} $subPage
331 * @return {String} local URL for this subpage in the Special:UploadStash space.
332 */
333 private function getSpecialUrl( $subPage ) {
334 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
335 }
336
337
338 /**
339 * Get a URL to access the thumbnail
340 * This is required because the model of how files work requires that
341 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
342 * (that's hidden in the session)
343 *
344 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
345 * @return String: URL to access thumbnail, or URL with partial path
346 */
347 public function getThumbUrl( $thumbName = false ) {
348 wfDebug( __METHOD__ . " getting for $thumbName \n" );
349 return $this->getSpecialUrl( $thumbName );
350 }
351
352 /**
353 * The basename for the URL, which we want to not be related to the filename.
354 * Will also be used as the lookup key for a thumbnail file.
355 *
356 * @return String: base url name, like '120px-123456.jpg'
357 */
358 public function getUrlName() {
359 if ( ! $this->urlName ) {
360 $this->urlName = $this->sessionKey;
361 }
362 return $this->urlName;
363 }
364
365 /**
366 * Return the URL of the file, if for some reason we wanted to download it
367 * We tend not to do this for the original file, but we do want thumb icons
368 *
369 * @return String: url
370 */
371 public function getUrl() {
372 if ( !isset( $this->url ) ) {
373 $this->url = $this->getSpecialUrl( $this->getUrlName() );
374 }
375 return $this->url;
376 }
377
378 /**
379 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
380 * But with this class, the URL is unrelated to the path.
381 *
382 * @return String: url
383 */
384 public function getFullUrl() {
385 return $this->getUrl();
386 }
387
388
389 /**
390 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
391 *
392 * @return String: session key
393 */
394 public function getSessionKey() {
395 return $this->sessionKey;
396 }
397
398 /**
399 * Remove the associated temporary file
400 * @return Status: success
401 */
402 public function remove() {
403 return $this->repo->freeTemp( $this->path );
404 }
405
406 }
407
408 class UploadStashNotAvailableException extends MWException {};
409 class UploadStashFileNotFoundException extends MWException {};
410 class UploadStashBadPathException extends MWException {};
411 class UploadStashBadVersionException extends MWException {};
412 class UploadStashFileException extends MWException {};
413 class UploadStashZeroLengthFileException extends MWException {};
414