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.
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.
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';
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 * @param $repo FileRepo: optional -- repo in which to store files. Will choose LocalRepo if not supplied.
36 public function __construct( $repo ) {
38 // this might change based on wiki's configuration.
41 if ( ! isset( $_SESSION ) ) {
42 throw new UploadStashNotAvailableException( 'no session variable' );
45 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME] ) ) {
46 $_SESSION[UploadBase::SESSION_KEYNAME] = array();
52 * Get a file and its metadata from the stash.
53 * May throw exception if session data cannot be parsed due to schema change, or key not found.
55 * @param $key Integer: key
56 * @throws UploadStashFileNotFoundException
57 * @throws UploadStashBadVersionException
58 * @return UploadStashFile
60 public function getFile( $key ) {
61 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
62 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
65 if ( !isset( $this->files[$key] ) ) {
66 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME][$key] ) ) {
67 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
70 $data = $_SESSION[UploadBase::SESSION_KEYNAME][$key];
71 // guards against PHP class changing while session data doesn't
72 if ($data['version'] !== UploadBase::SESSION_VERSION ) {
73 throw new UploadStashBadVersionException( $data['version'] . " does not match current version " . UploadBase::SESSION_VERSION );
76 // separate the stashData into the path, and then the rest of the data
77 $path = $data['mTempPath'];
78 unset( $data['mTempPath'] );
80 $file = new UploadStashFile( $this, $this->repo, $path, $key, $data );
81 if ( $file->getSize === 0 ) {
82 throw new UploadStashZeroLengthFileException( "File is zero length" );
84 $this->files[$key] = $file;
87 return $this->files[$key];
91 * Stash a file in a temp directory and record that we did this in the session, along with other metadata.
92 * We store data in a flat key-val namespace because that's how UploadBase did it. This also means we have to
93 * ensure that the key-val pairs in $data do not overwrite other required fields.
95 * @param $path String: path to file you want stashed
96 * @param $data Array: optional, other data you want associated with the file. Do not use 'mTempPath', 'mFileProps', 'mFileSize', or 'version' as keys here
97 * @param $key String: optional, unique key for this file in this session. Used for directory hashing when storing, otherwise not important
98 * @throws UploadStashBadPathException
99 * @throws UploadStashFileException
100 * @return UploadStashFile: file, or null on failure
102 public function stashFile( $path, $data = array(), $key = null ) {
103 if ( ! file_exists( $path ) ) {
104 wfDebug( "UploadStash: tried to stash file at '$path', but it doesn't exist\n" );
105 throw new UploadStashBadPathException( "path doesn't exist" );
107 $fileProps = File::getPropsFromPath( $path );
109 // we will be initializing from some tmpnam files that don't have extensions.
110 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
111 $extension = self::getExtensionForPath( $path );
112 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
113 $pathWithGoodExtension = "$path.$extension";
114 if ( ! rename( $path, $pathWithGoodExtension ) ) {
115 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
117 $path = $pathWithGoodExtension;
120 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
121 // uploaded this session, which could happen if uploads had failed.
122 if ( is_null( $key ) ) {
123 $key = $fileProps['sha1'] . "." . $extension;
126 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
127 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
131 // if not already in a temporary area, put it there
132 $status = $this->repo->storeTemp( basename( $path ), $path );
134 if( ! $status->isOK() ) {
135 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
136 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
137 // 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
138 // redesigning API errors significantly.
139 // $status->value just contains the virtual URL (if anything) which is probably useless to the caller
140 $error = reset( $status->getErrorsArray() );
141 if ( ! count( $error ) ) {
142 $error = reset( $status->getWarningsArray() );
143 if ( ! count( $error ) ) {
144 $error = array( 'unknown', 'no error recorded' );
147 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
149 $stashPath = $status->value;
151 // required info we always store. Must trump any other application info in $data
152 // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
153 // chosen for compatibility with UploadBase's way of doing this.
154 $requiredData = array(
155 'mTempPath' => $stashPath,
156 'mFileSize' => $fileProps['size'],
157 'mFileProps' => $fileProps,
158 'version' => UploadBase::SESSION_VERSION
161 // now, merge required info and extra data into the session. (The extra data changes from application to application.
162 // UploadWizard wants different things than say FirefoggChunkedUpload.)
163 wfDebug( __METHOD__ . " storing under $key\n" );
164 $_SESSION[UploadBase::SESSION_KEYNAME][$key] = array_merge( $data, $requiredData );
166 return $this->getFile( $key );
170 * Find or guess extension -- ensuring that our extension matches our mime type.
171 * Since these files are constructed from php tempnames they may not start off
173 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
174 * uploads versus the desired filename. Maybe we can get that passed to us...
176 public static function getExtensionForPath( $path ) {
177 // Does this have an extension?
178 $n = strrpos( $path, '.' );
180 if ( $n !== false ) {
181 $extension = $n ? substr( $path, $n + 1 ) : '';
183 // If not, assume that it should be related to the mime type of the original file.
184 $magic = MimeMagic::singleton();
185 $mimeType = $magic->guessMimeType( $path );
186 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
187 if ( count( $extensions ) ) {
188 $extension = $extensions[0];
192 if ( is_null( $extension ) ) {
193 throw new UploadStashFileException( "extension is null" );
196 return File::normalizeExtension( $extension );
201 class UploadStashFile extends UnregisteredLocalFile {
202 private $sessionStash;
204 private $sessionData;
208 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
209 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
211 * @param $stash UploadStash: useful for obtaining config, stashing transformed files
212 * @param $repo FileRepo: repository where we should find the path
213 * @param $path String: path to file
214 * @param $key String: key to store the path and any stashed data under
215 * @param $data String: any other data we want stored with this file
216 * @throws UploadStashBadPathException
217 * @throws UploadStashFileNotFoundException
219 public function __construct( $stash, $repo, $path, $key, $data ) {
220 $this->sessionStash = $stash;
221 $this->sessionKey = $key;
222 $this->sessionData = $data;
224 // resolve mwrepo:// urls
225 if ( $repo->isVirtualUrl( $path ) ) {
226 $path = $repo->resolveVirtualUrl( $path );
229 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
230 $repoTempPath = $repo->getZonePath( 'temp' );
231 if ( ( ! $repo->validateFilename( $path ) ) ||
232 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
233 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
234 throw new UploadStashBadPathException( 'path is not valid' );
237 // check if path exists! and is a plain file.
238 if ( ! $repo->fileExists( $path, FileRepo::FILES_ONLY ) ) {
239 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
240 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
245 parent::__construct( false, $repo, $path, false );
247 $this->name = basename( $this->path );
251 * A method needed by the file transforming and scaling routines in File.php
252 * We do not necessarily care about doing the description at this point
253 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
254 * convert require it to be there)
256 * @return String: dummy value
258 public function getDescriptionUrl() {
259 return $this->getUrl();
263 * Get the path for the thumbnail (actually any transformation of this file)
264 * The actual argument is the result of thumbName although we seem to have
265 * buggy code elsewhere that expects a boolean 'suffix'
267 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
268 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
270 public function getThumbPath( $thumbName = false ) {
271 $path = dirname( $this->path );
272 if ( $thumbName !== false ) {
273 $path .= "/$thumbName";
279 * Return the file/url base name of a thumbnail with the specified parameters
281 * @param $params Array: handler-specific parameters
282 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
284 function thumbName( $params ) {
285 return $this->getParamThumbName( $this->getUrlName(), $params );
290 * Given the name of the original, i.e. Foo.jpg, and scaling parameters, returns filename with appropriate extension
291 * This is abstracted from getThumbName because we also use it to calculate the thumbname the file should have on
292 * remote image scalers
294 * @param String $urlName: A filename, like MyMovie.ogx
295 * @param Array $parameters: scaling parameters, like array( 'width' => '120' );
296 * @return String|null parameterized thumb name, like 120px-MyMovie.ogx.jpg, or null if no handler found
298 function getParamThumbName( $urlName, $params ) {
299 if ( !$this->getHandler() ) {
302 $extension = $this->getExtension();
303 list( $thumbExt, ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
304 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $urlName;
305 if ( $thumbExt != $extension ) {
306 $thumbName .= ".$thumbExt";
312 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
313 * @param {String} $subPage
314 * @return {String} local URL for this subpage in the Special:UploadStash space.
316 private function getSpecialUrl( $subPage ) {
317 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
322 * Get a URL to access the thumbnail
323 * This is required because the model of how files work requires that
324 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
325 * (that's hidden in the session)
327 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
328 * @return String: URL to access thumbnail, or URL with partial path
330 public function getThumbUrl( $thumbName = false ) {
331 wfDebug( __METHOD__ . " getting for $thumbName \n" );
332 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
336 * The basename for the URL, which we want to not be related to the filename.
337 * Will also be used as the lookup key for a thumbnail file.
339 * @return String: base url name, like '120px-123456.jpg'
341 public function getUrlName() {
342 if ( ! $this->urlName ) {
343 $this->urlName = $this->sessionKey;
345 return $this->urlName;
349 * Return the URL of the file, if for some reason we wanted to download it
350 * We tend not to do this for the original file, but we do want thumb icons
352 * @return String: url
354 public function getUrl() {
355 if ( !isset( $this->url ) ) {
356 $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
362 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
363 * But with this class, the URL is unrelated to the path.
365 * @return String: url
367 public function getFullUrl() {
368 return $this->getUrl();
373 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
375 * @return String: session key
377 public function getSessionKey() {
378 return $this->sessionKey;
382 * Remove the associated temporary file
383 * @return Status: success
385 public function remove() {
386 return $this->repo->freeTemp( $this->path );
391 class UploadStashNotAvailableException extends MWException {};
392 class UploadStashFileNotFoundException extends MWException {};
393 class UploadStashBadPathException extends MWException {};
394 class UploadStashBadVersionException extends MWException {};
395 class UploadStashFileException extends MWException {};
396 class UploadStashZeroLengthFileException extends MWException {};