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.
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+$/';
18 // repository that this uses to store temp files
19 // public because we sometimes need to get a LocalFile within the same repo.
22 // array of initialized objects obtained from session (lazily initialized upon getFile())
23 private $files = array();
28 // Cache to store stash metadata in
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';
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)
39 * @param $repo FileRepo: optional -- repo in which to store files. Will choose LocalRepo if not supplied.
41 public function __construct( $repo = null ) {
43 if ( is_null( $repo ) ) {
44 $repo = RepoGroup
::singleton()->getLocalRepo();
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' );
54 $this->sessionID
= '';
55 $this->cache
= wfGetCache( CACHE_ANYTHING
);
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.
62 * @param $key Integer: key
63 * @throws UploadStashFileNotFoundException
64 * @throws UploadStashBadVersionException
65 * @return UploadStashFile
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" );
72 if ( !isset( $this->files
[$key] ) ) {
73 $cacheKey = wfMemcKey( 'uploadstash', $this->sessionID
, $key );
74 $data = $this->cache
->get( $cacheKey );
76 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
79 $this->files
[$key] = $this->getFileFromData( $data );
82 return $this->files
[$key];
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
);
91 // separate the stashData into the path, and then the rest of the data
92 $path = $data['mTempPath'];
93 unset( $data['mTempPath'] );
95 $file = new UploadStashFile( $this, $this->repo
, $path, $key, $data );
96 if ( $file->getSize() === 0 ) {
97 throw new UploadStashZeroLengthFileException( "File is zero length" );
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.
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
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" );
119 $fileProps = File
::getPropsFromPath( $path );
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" );
129 $path = $pathWithGoodExtension;
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;
138 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
139 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
143 // if not already in a temporary area, put it there
144 $status = $this->repo
->storeTemp( basename( $path ), $path );
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' );
159 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
161 $stashPath = $status->value
;
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
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 );
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 );
182 $this->files
[$key] = $this->getFileFromData( $data );
183 return $this->files
[$key];
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
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...
193 public static function getExtensionForPath( $path ) {
194 // Does this have an extension?
195 $n = strrpos( $path, '.' );
197 if ( $n !== false ) {
198 $extension = $n ?
substr( $path, $n +
1 ) : '';
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];
209 if ( is_null( $extension ) ) {
210 throw new UploadStashFileException( "extension is null" );
213 return File
::normalizeExtension( $extension );
218 class UploadStashFile
extends UnregisteredLocalFile
{
219 private $sessionStash;
221 private $sessionData;
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
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
236 public function __construct( $stash, $repo, $path, $key, $data ) {
237 $this->sessionStash
= $stash;
238 $this->sessionKey
= $key;
239 $this->sessionData
= $data;
241 // resolve mwrepo:// urls
242 if ( $repo->isVirtualUrl( $path ) ) {
243 $path = $repo->resolveVirtualUrl( $path );
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' );
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' );
262 parent
::__construct( false, $repo, $path, false );
264 $this->name
= basename( $this->path
);
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)
273 * @return String: dummy value
275 public function getDescriptionUrl() {
276 return $this->getUrl();
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'
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
287 public function getThumbPath( $thumbName = false ) {
288 $path = dirname( $this->path
);
289 if ( $thumbName !== false ) {
290 $path .= "/$thumbName";
296 * Return the file/url base name of a thumbnail with the specified parameters
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
301 function thumbName( $params ) {
302 return $this->getParamThumbName( $this->getUrlName(), $params );
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
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
315 function getParamThumbName( $urlName, $params ) {
316 if ( !$this->getHandler() ) {
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";
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.
333 private function getSpecialUrl( $subPage ) {
334 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
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)
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
347 public function getThumbUrl( $thumbName = false ) {
348 wfDebug( __METHOD__
. " getting for $thumbName \n" );
349 return $this->getSpecialUrl( $thumbName );
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.
356 * @return String: base url name, like '120px-123456.jpg'
358 public function getUrlName() {
359 if ( ! $this->urlName
) {
360 $this->urlName
= $this->sessionKey
;
362 return $this->urlName
;
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
369 * @return String: url
371 public function getUrl() {
372 if ( !isset( $this->url
) ) {
373 $this->url
= $this->getSpecialUrl( $this->getUrlName() );
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.
382 * @return String: url
384 public function getFullUrl() {
385 return $this->getUrl();
390 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
392 * @return String: session key
394 public function getSessionKey() {
395 return $this->sessionKey
;
399 * Remove the associated temporary file
400 * @return Status: success
402 public function remove() {
403 return $this->repo
->freeTemp( $this->path
);
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
{};