(bug 27046) Do not strip newlines following C++-style // comments. Prior to this...
[mediawiki.git] / includes / upload / UploadStash.php
blob27e0ec1bb724636889e0f53a5d95ca8129c1b657
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.
14 class UploadStash {
16 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
17 const KEY_FORMAT_REGEX = '/^[\w-]+\.\w+$/';
19 // repository that this uses to store temp files
20 // public because we sometimes need to get a LocalFile within the same repo.
21 public $repo;
23 // array of initialized objects obtained from session (lazily initialized upon getFile())
24 private $files = array();
26 // TODO: Once UploadBase starts using this, switch to use these constants rather than UploadBase::SESSION*
27 // const SESSION_VERSION = 2;
28 // const SESSION_KEYNAME = 'wsUploadData';
30 /**
31 * Represents the session which contains temporarily stored files.
32 * Designed to be compatible with the session stashing code in UploadBase (should replace it eventually)
34 public function __construct( $repo ) {
36 // this might change based on wiki's configuration.
37 $this->repo = $repo;
39 if ( ! isset( $_SESSION ) ) {
40 throw new UploadStashNotAvailableException( 'no session variable' );
43 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME] ) ) {
44 $_SESSION[UploadBase::SESSION_KEYNAME] = array();
50 /**
51 * Get a file and its metadata from the stash.
52 * May throw exception if session data cannot be parsed due to schema change, or key not found.
54 * @param $key Integer: key
55 * @throws UploadStashFileNotFoundException
56 * @throws UploadStashBadVersionException
57 * @return UploadStashFile
59 public function getFile( $key ) {
60 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
61 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
64 if ( !isset( $this->files[$key] ) ) {
65 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME][$key] ) ) {
66 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
69 $data = $_SESSION[UploadBase::SESSION_KEYNAME][$key];
70 // guards against PHP class changing while session data doesn't
71 if ($data['version'] !== UploadBase::SESSION_VERSION ) {
72 throw new UploadStashBadVersionException( $data['version'] . " does not match current version " . UploadBase::SESSION_VERSION );
75 // separate the stashData into the path, and then the rest of the data
76 $path = $data['mTempPath'];
77 unset( $data['mTempPath'] );
79 $file = new UploadStashFile( $this, $this->repo, $path, $key, $data );
80 if ( $file->getSize() === 0 ) {
81 throw new UploadStashZeroLengthFileException( "File is zero length" );
83 $this->files[$key] = $file;
86 return $this->files[$key];
89 /**
90 * Stash a file in a temp directory and record that we did this in the session, along with other metadata.
91 * We store data in a flat key-val namespace because that's how UploadBase did it. This also means we have to
92 * ensure that the key-val pairs in $data do not overwrite other required fields.
94 * @param $path String: path to file you want stashed
95 * @param $data Array: optional, other data you want associated with the file. Do not use 'mTempPath', 'mFileProps', 'mFileSize', or 'version' as keys here
96 * @param $key String: optional, unique key for this file in this session. Used for directory hashing when storing, otherwise not important
97 * @throws UploadStashBadPathException
98 * @throws UploadStashFileException
99 * @return UploadStashFile: file, or null on failure
101 public function stashFile( $path, $data = array(), $key = null ) {
102 if ( ! file_exists( $path ) ) {
103 wfDebug( "UploadStash: tried to stash file at '$path', but it doesn't exist\n" );
104 throw new UploadStashBadPathException( "path doesn't exist" );
106 $fileProps = File::getPropsFromPath( $path );
108 // we will be initializing from some tmpnam files that don't have extensions.
109 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
110 $extension = self::getExtensionForPath( $path );
111 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
112 $pathWithGoodExtension = "$path.$extension";
113 if ( ! rename( $path, $pathWithGoodExtension ) ) {
114 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
116 $path = $pathWithGoodExtension;
119 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
120 // uploaded this session, which could happen if uploads had failed.
121 if ( is_null( $key ) ) {
122 $key = $fileProps['sha1'] . "." . $extension;
125 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
126 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
130 // if not already in a temporary area, put it there
131 $status = $this->repo->storeTemp( basename( $path ), $path );
133 if( ! $status->isOK() ) {
134 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
135 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
136 // 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
137 // redesigning API errors significantly.
138 // $status->value just contains the virtual URL (if anything) which is probably useless to the caller
139 $error = reset( $status->getErrorsArray() );
140 if ( ! count( $error ) ) {
141 $error = reset( $status->getWarningsArray() );
142 if ( ! count( $error ) ) {
143 $error = array( 'unknown', 'no error recorded' );
146 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
148 $stashPath = $status->value;
150 // required info we always store. Must trump any other application info in $data
151 // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
152 // chosen for compatibility with UploadBase's way of doing this.
153 $requiredData = array(
154 'mTempPath' => $stashPath,
155 'mFileSize' => $fileProps['size'],
156 'mFileProps' => $fileProps,
157 'version' => UploadBase::SESSION_VERSION
160 // now, merge required info and extra data into the session. (The extra data changes from application to application.
161 // UploadWizard wants different things than say FirefoggChunkedUpload.)
162 wfDebug( __METHOD__ . " storing under $key\n" );
163 $_SESSION[UploadBase::SESSION_KEYNAME][$key] = array_merge( $data, $requiredData );
165 return $this->getFile( $key );
169 * Remove all files from the stash.
170 * Does not clean up files in the repo, just the record of them.
171 * @return boolean: success
173 public function clear() {
174 $_SESSION[UploadBase::SESSION_KEYNAME] = array();
175 return true;
180 * Remove a particular file from the stash.
181 * Does not clean up file in the repo, just the record of it.
182 * @return boolean: success
184 public function removeFile( $key ) {
185 unset ( $_SESSION[UploadBase::SESSION_KEYNAME][$key] );
186 return true;
191 * List all files in the stash.
193 public function listFiles() {
194 return array_keys( $_SESSION[UploadBase::SESSION_KEYNAME] );
199 * Find or guess extension -- ensuring that our extension matches our mime type.
200 * Since these files are constructed from php tempnames they may not start off
201 * with an extension.
202 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
203 * uploads versus the desired filename. Maybe we can get that passed to us...
205 public static function getExtensionForPath( $path ) {
206 // Does this have an extension?
207 $n = strrpos( $path, '.' );
208 $extension = null;
209 if ( $n !== false ) {
210 $extension = $n ? substr( $path, $n + 1 ) : '';
211 } else {
212 // If not, assume that it should be related to the mime type of the original file.
213 $magic = MimeMagic::singleton();
214 $mimeType = $magic->guessMimeType( $path );
215 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
216 if ( count( $extensions ) ) {
217 $extension = $extensions[0];
221 if ( is_null( $extension ) ) {
222 throw new UploadStashFileException( "extension is null" );
225 return File::normalizeExtension( $extension );
230 class UploadStashFile extends UnregisteredLocalFile {
231 private $sessionStash;
232 private $sessionKey;
233 private $sessionData;
234 private $urlName;
237 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
238 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
240 * @param $stash UploadStash: useful for obtaining config, stashing transformed files
241 * @param $repo FileRepo: repository where we should find the path
242 * @param $path String: path to file
243 * @param $key String: key to store the path and any stashed data under
244 * @param $data String: any other data we want stored with this file
245 * @throws UploadStashBadPathException
246 * @throws UploadStashFileNotFoundException
248 public function __construct( $stash, $repo, $path, $key, $data ) {
249 $this->sessionStash = $stash;
250 $this->sessionKey = $key;
251 $this->sessionData = $data;
253 // resolve mwrepo:// urls
254 if ( $repo->isVirtualUrl( $path ) ) {
255 $path = $repo->resolveVirtualUrl( $path );
258 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
259 $repoTempPath = $repo->getZonePath( 'temp' );
260 if ( ( ! $repo->validateFilename( $path ) ) ||
261 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
262 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
263 throw new UploadStashBadPathException( 'path is not valid' );
266 // check if path exists! and is a plain file.
267 if ( ! $repo->fileExists( $path, FileRepo::FILES_ONLY ) ) {
268 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
269 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
274 parent::__construct( false, $repo, $path, false );
276 $this->name = basename( $this->path );
280 * A method needed by the file transforming and scaling routines in File.php
281 * We do not necessarily care about doing the description at this point
282 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
283 * convert require it to be there)
285 * @return String: dummy value
287 public function getDescriptionUrl() {
288 return $this->getUrl();
292 * Get the path for the thumbnail (actually any transformation of this file)
293 * The actual argument is the result of thumbName although we seem to have
294 * buggy code elsewhere that expects a boolean 'suffix'
296 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
297 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
299 public function getThumbPath( $thumbName = false ) {
300 $path = dirname( $this->path );
301 if ( $thumbName !== false ) {
302 $path .= "/$thumbName";
304 return $path;
308 * Return the file/url base name of a thumbnail with the specified parameters
310 * @param $params Array: handler-specific parameters
311 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
313 function thumbName( $params ) {
314 return $this->getParamThumbName( $this->getUrlName(), $params );
319 * Given the name of the original, i.e. Foo.jpg, and scaling parameters, returns filename with appropriate extension
320 * This is abstracted from getThumbName because we also use it to calculate the thumbname the file should have on
321 * remote image scalers
323 * @param String $urlName: A filename, like MyMovie.ogx
324 * @param Array $parameters: scaling parameters, like array( 'width' => '120' );
325 * @return String|null parameterized thumb name, like 120px-MyMovie.ogx.jpg, or null if no handler found
327 function getParamThumbName( $urlName, $params ) {
328 if ( !$this->getHandler() ) {
329 return null;
331 $extension = $this->getExtension();
332 list( $thumbExt, ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
333 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $urlName;
334 if ( $thumbExt != $extension ) {
335 $thumbName .= ".$thumbExt";
337 return $thumbName;
341 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
342 * @param {String} $subPage
343 * @return {String} local URL for this subpage in the Special:UploadStash space.
345 private function getSpecialUrl( $subPage ) {
346 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
350 /**
351 * Get a URL to access the thumbnail
352 * This is required because the model of how files work requires that
353 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
354 * (that's hidden in the session)
356 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
357 * @return String: URL to access thumbnail, or URL with partial path
359 public function getThumbUrl( $thumbName = false ) {
360 wfDebug( __METHOD__ . " getting for $thumbName \n" );
361 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
364 /**
365 * The basename for the URL, which we want to not be related to the filename.
366 * Will also be used as the lookup key for a thumbnail file.
368 * @return String: base url name, like '120px-123456.jpg'
370 public function getUrlName() {
371 if ( ! $this->urlName ) {
372 $this->urlName = $this->sessionKey;
374 return $this->urlName;
378 * Return the URL of the file, if for some reason we wanted to download it
379 * We tend not to do this for the original file, but we do want thumb icons
381 * @return String: url
383 public function getUrl() {
384 if ( !isset( $this->url ) ) {
385 $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
387 return $this->url;
391 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
392 * But with this class, the URL is unrelated to the path.
394 * @return String: url
396 public function getFullUrl() {
397 return $this->getUrl();
402 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
404 * @return String: session key
406 public function getSessionKey() {
407 return $this->sessionKey;
411 * Remove the associated temporary file
412 * @return Status: success
414 public function remove() {
415 return $this->repo->freeTemp( $this->path );
420 class UploadStashNotAvailableException extends MWException {};
421 class UploadStashFileNotFoundException extends MWException {};
422 class UploadStashBadPathException extends MWException {};
423 class UploadStashBadVersionException extends MWException {};
424 class UploadStashFileException extends MWException {};
425 class UploadStashZeroLengthFileException extends MWException {};