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 = null ) {
38 if ( is_null( $repo ) ) {
39 $repo = RepoGroup
::singleton()->getLocalRepo();
44 if ( ! isset( $_SESSION ) ) {
45 throw new UploadStashNotAvailableException( 'no session variable' );
48 if ( !isset( $_SESSION[UploadBase
::SESSION_KEYNAME
] ) ) {
49 $_SESSION[UploadBase
::SESSION_KEYNAME
] = array();
55 * Get a file and its metadata from the stash.
56 * May throw exception if session data cannot be parsed due to schema change, or key not found.
58 * @param $key Integer: key
59 * @throws UploadStashFileNotFoundException
60 * @throws UploadStashBadVersionException
61 * @return UploadStashFile
63 public function getFile( $key ) {
64 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
65 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
68 if ( !isset( $this->files
[$key] ) ) {
69 if ( !isset( $_SESSION[UploadBase
::SESSION_KEYNAME
][$key] ) ) {
70 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
73 $data = $_SESSION[UploadBase
::SESSION_KEYNAME
][$key];
74 // guards against PHP class changing while session data doesn't
75 if ($data['version'] !== UploadBase
::SESSION_VERSION
) {
76 throw new UploadStashBadVersionException( $data['version'] . " does not match current version " . UploadBase
::SESSION_VERSION
);
79 // separate the stashData into the path, and then the rest of the data
80 $path = $data['mTempPath'];
81 unset( $data['mTempPath'] );
83 $file = new UploadStashFile( $this, $this->repo
, $path, $key, $data );
84 if ( $file->getSize
=== 0 ) {
85 throw new UploadStashZeroLengthFileException( "File is zero length" );
87 $this->files
[$key] = $file;
90 return $this->files
[$key];
94 * Stash a file in a temp directory and record that we did this in the session, along with other metadata.
95 * We store data in a flat key-val namespace because that's how UploadBase did it. This also means we have to
96 * ensure that the key-val pairs in $data do not overwrite other required fields.
98 * @param $path String: path to file you want stashed
99 * @param $data Array: optional, other data you want associated with the file. Do not use 'mTempPath', 'mFileProps', 'mFileSize', or 'version' as keys here
100 * @param $key String: optional, unique key for this file in this session. Used for directory hashing when storing, otherwise not important
101 * @throws UploadStashBadPathException
102 * @throws UploadStashFileException
103 * @return UploadStashFile: file, or null on failure
105 public function stashFile( $path, $data = array(), $key = null ) {
106 if ( ! file_exists( $path ) ) {
107 wfDebug( "UploadStash: tried to stash file at '$path', but it doesn't exist\n" );
108 throw new UploadStashBadPathException( "path doesn't exist" );
110 $fileProps = File
::getPropsFromPath( $path );
112 // we will be initializing from some tmpnam files that don't have extensions.
113 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
114 $extension = self
::getExtensionForPath( $path );
115 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
116 $pathWithGoodExtension = "$path.$extension";
117 if ( ! rename( $path, $pathWithGoodExtension ) ) {
118 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
120 $path = $pathWithGoodExtension;
123 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
124 // uploaded this session, which could happen if uploads had failed.
125 if ( is_null( $key ) ) {
126 $key = $fileProps['sha1'] . "." . $extension;
129 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
130 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
134 // if not already in a temporary area, put it there
135 $status = $this->repo
->storeTemp( basename( $path ), $path );
137 if( ! $status->isOK() ) {
138 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
139 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
140 // 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
141 // redesigning API errors significantly.
142 // $status->value just contains the virtual URL (if anything) which is probably useless to the caller
143 $error = reset( $status->getErrorsArray() );
144 if ( ! count( $error ) ) {
145 $error = reset( $status->getWarningsArray() );
146 if ( ! count( $error ) ) {
147 $error = array( 'unknown', 'no error recorded' );
150 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
152 $stashPath = $status->value
;
154 // required info we always store. Must trump any other application info in $data
155 // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
156 // chosen for compatibility with UploadBase's way of doing this.
157 $requiredData = array(
158 'mTempPath' => $stashPath,
159 'mFileSize' => $fileProps['size'],
160 'mFileProps' => $fileProps,
161 'version' => UploadBase
::SESSION_VERSION
164 // now, merge required info and extra data into the session. (The extra data changes from application to application.
165 // UploadWizard wants different things than say FirefoggChunkedUpload.)
166 wfDebug( __METHOD__
. " storing under $key\n" );
167 $_SESSION[UploadBase
::SESSION_KEYNAME
][$key] = array_merge( $data, $requiredData );
169 return $this->getFile( $key );
173 * Find or guess extension -- ensuring that our extension matches our mime type.
174 * Since these files are constructed from php tempnames they may not start off
176 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
177 * uploads versus the desired filename. Maybe we can get that passed to us...
179 public static function getExtensionForPath( $path ) {
180 // Does this have an extension?
181 $n = strrpos( $path, '.' );
183 if ( $n !== false ) {
184 $extension = $n ?
substr( $path, $n +
1 ) : '';
186 // If not, assume that it should be related to the mime type of the original file.
187 $magic = MimeMagic
::singleton();
188 $mimeType = $magic->guessMimeType( $path );
189 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
190 if ( count( $extensions ) ) {
191 $extension = $extensions[0];
195 if ( is_null( $extension ) ) {
196 throw new UploadStashFileException( "extension is null" );
199 return File
::normalizeExtension( $extension );
204 class UploadStashFile
extends UnregisteredLocalFile
{
205 private $sessionStash;
207 private $sessionData;
211 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
212 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
214 * @param $stash UploadStash: useful for obtaining config, stashing transformed files
215 * @param $repo FileRepo: repository where we should find the path
216 * @param $path String: path to file
217 * @param $key String: key to store the path and any stashed data under
218 * @param $data String: any other data we want stored with this file
219 * @throws UploadStashBadPathException
220 * @throws UploadStashFileNotFoundException
222 public function __construct( $stash, $repo, $path, $key, $data ) {
223 $this->sessionStash
= $stash;
224 $this->sessionKey
= $key;
225 $this->sessionData
= $data;
227 // resolve mwrepo:// urls
228 if ( $repo->isVirtualUrl( $path ) ) {
229 $path = $repo->resolveVirtualUrl( $path );
232 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
233 $repoTempPath = $repo->getZonePath( 'temp' );
234 if ( ( ! $repo->validateFilename( $path ) ) ||
235 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
236 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
237 throw new UploadStashBadPathException( 'path is not valid' );
240 // check if path exists! and is a plain file.
241 if ( ! $repo->fileExists( $path, FileRepo
::FILES_ONLY
) ) {
242 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
243 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
248 parent
::__construct( false, $repo, $path, false );
250 $this->name
= basename( $this->path
);
254 * A method needed by the file transforming and scaling routines in File.php
255 * We do not necessarily care about doing the description at this point
256 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
257 * convert require it to be there)
259 * @return String: dummy value
261 public function getDescriptionUrl() {
262 return $this->getUrl();
266 * Get the path for the thumbnail (actually any transformation of this file)
267 * The actual argument is the result of thumbName although we seem to have
268 * buggy code elsewhere that expects a boolean 'suffix'
270 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
271 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
273 public function getThumbPath( $thumbName = false ) {
274 $path = dirname( $this->path
);
275 if ( $thumbName !== false ) {
276 $path .= "/$thumbName";
282 * Return the file/url base name of a thumbnail with the specified parameters
284 * @param $params Array: handler-specific parameters
285 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
287 function thumbName( $params ) {
288 return $this->getParamThumbName( $this->getUrlName(), $params );
293 * Given the name of the original, i.e. Foo.jpg, and scaling parameters, returns filename with appropriate extension
294 * This is abstracted from getThumbName because we also use it to calculate the thumbname the file should have on
295 * remote image scalers
297 * @param String $urlName: A filename, like MyMovie.ogx
298 * @param Array $parameters: scaling parameters, like array( 'width' => '120' );
299 * @return String|null parameterized thumb name, like 120px-MyMovie.ogx.jpg, or null if no handler found
301 function getParamThumbName( $urlName, $params ) {
302 if ( !$this->getHandler() ) {
305 $extension = $this->getExtension();
306 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
307 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $urlName;
308 if ( $thumbExt != $extension ) {
309 $thumbName .= ".$thumbExt";
315 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
316 * @param {String} $subPage
317 * @return {String} local URL for this subpage in the Special:UploadStash space.
319 private function getSpecialUrl( $subPage ) {
320 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
325 * Get a URL to access the thumbnail
326 * This is required because the model of how files work requires that
327 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
328 * (that's hidden in the session)
330 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
331 * @return String: URL to access thumbnail, or URL with partial path
333 public function getThumbUrl( $thumbName = false ) {
334 wfDebug( __METHOD__
. " getting for $thumbName \n" );
335 return $this->getSpecialUrl( $thumbName );
339 * The basename for the URL, which we want to not be related to the filename.
340 * Will also be used as the lookup key for a thumbnail file.
342 * @return String: base url name, like '120px-123456.jpg'
344 public function getUrlName() {
345 if ( ! $this->urlName
) {
346 $this->urlName
= $this->sessionKey
;
348 return $this->urlName
;
352 * Return the URL of the file, if for some reason we wanted to download it
353 * We tend not to do this for the original file, but we do want thumb icons
355 * @return String: url
357 public function getUrl() {
358 if ( !isset( $this->url
) ) {
359 $this->url
= $this->getSpecialUrl( $this->getUrlName() );
365 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
366 * But with this class, the URL is unrelated to the path.
368 * @return String: url
370 public function getFullUrl() {
371 return $this->getUrl();
376 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
378 * @return String: session key
380 public function getSessionKey() {
381 return $this->sessionKey
;
385 * Remove the associated temporary file
386 * @return Status: success
388 public function remove() {
389 return $this->repo
->freeTemp( $this->path
);
394 class UploadStashNotAvailableException
extends MWException
{};
395 class UploadStashFileNotFoundException
extends MWException
{};
396 class UploadStashBadPathException
extends MWException
{};
397 class UploadStashBadVersionException
extends MWException
{};
398 class UploadStashFileException
extends MWException
{};
399 class UploadStashZeroLengthFileException
extends MWException
{};