3 * Temporary storage for uploaded files.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * UploadStash is intended to accomplish a few things:
26 * - enable applications to temporarily stash files without publishing them to the wiki.
27 * - Several parts of MediaWiki do this in similar ways: UploadBase, UploadWizard, and FirefoggChunkedExtension
28 * And there are several that reimplement stashing from scratch, in idiosyncratic ways. The idea is to unify them all here.
29 * Mostly all of them are the same except for storing some custom fields, which we subsume into the data array.
30 * - enable applications to find said files later, as long as the db table or temp files haven't been purged.
31 * - enable the uploading user (and *ONLY* the uploading user) to access said files, and thumbnails of said files, via a URL.
32 * We accomplish this using a database table, with ownership checking as you might expect. See SpecialUploadStash, which
33 * implements a web interface to some files stored this way.
35 * UploadStash right now is *mostly* intended to show you one user's slice of the entire stash. The user parameter is only optional
36 * because there are few cases where we clean out the stash from an automated script. In the future we might refactor this.
38 * UploadStash represents the entire stash of temporary files.
39 * UploadStashFile is a filestore for the actual physical disk files.
40 * UploadFromStash extends UploadBase, and represents a single stashed file as it is moved from the stash to the regular file repository
46 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
47 const KEY_FORMAT_REGEX
= '/^[\w-\.]+\.\w*$/';
50 * repository that this uses to store temp files
51 * public because we sometimes need to get a LocalFile within the same repo.
57 // array of initialized repo objects
58 protected $files = array();
60 // cache of the file metadata that's stored in the database
61 protected $fileMetadata = array();
64 protected $fileProps = array();
67 protected $user, $userId, $isLoggedIn;
70 * Represents a temporary filestore, with metadata in the database.
71 * Designed to be compatible with the session stashing code in UploadBase
72 * (should replace it eventually).
74 * @param $repo FileRepo
75 * @param $user User (default null)
77 public function __construct( FileRepo
$repo, $user = null ) {
78 // this might change based on wiki's configuration.
81 // if a user was passed, use it. otherwise, attempt to use the global.
82 // this keeps FileRepo from breaking when it creates an UploadStash object
87 $this->user
= $wgUser;
90 if ( is_object( $this->user
) ) {
91 $this->userId
= $this->user
->getId();
92 $this->isLoggedIn
= $this->user
->isLoggedIn();
97 * Get a file and its metadata from the stash.
98 * The noAuth param is a bit janky but is required for automated scripts which clean out the stash.
100 * @param $key String: key under which file information is stored
101 * @param $noAuth Boolean (optional) Don't check authentication. Used by maintenance scripts.
102 * @throws UploadStashFileNotFoundException
103 * @throws UploadStashNotLoggedInException
104 * @throws UploadStashWrongOwnerException
105 * @throws UploadStashBadPathException
106 * @return UploadStashFile
108 public function getFile( $key, $noAuth = false ) {
110 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
111 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
115 if ( !$this->isLoggedIn
) {
116 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
120 if ( !isset( $this->fileMetadata
[$key] ) ) {
121 if ( !$this->fetchFileMetadata( $key ) ) {
122 // If nothing was received, it's likely due to replication lag. Check the master to see if the record is there.
123 $this->fetchFileMetadata( $key, DB_MASTER
);
126 if ( !isset( $this->fileMetadata
[$key] ) ) {
127 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
130 // create $this->files[$key]
131 $this->initFile( $key );
134 $path = $this->fileMetadata
[$key]['us_path'];
135 $this->fileProps
[$key] = $this->repo
->getFileProps( $path );
138 if ( ! $this->files
[$key]->exists() ) {
139 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
140 throw new UploadStashBadPathException( "path doesn't exist" );
144 if ( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
145 throw new UploadStashWrongOwnerException( "This file ($key) doesn't belong to the current user." );
149 return $this->files
[$key];
153 * Getter for file metadata.
155 * @param key String: key under which file information is stored
158 public function getMetadata ( $key ) {
159 $this->getFile( $key );
160 return $this->fileMetadata
[$key];
164 * Getter for fileProps
166 * @param key String: key under which file information is stored
169 public function getFileProps ( $key ) {
170 $this->getFile( $key );
171 return $this->fileProps
[$key];
175 * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
177 * @param $path String: path to file you want stashed
178 * @param $sourceType String: the type of upload that generated this file (currently, I believe, 'file' or null)
179 * @throws UploadStashBadPathException
180 * @throws UploadStashFileException
181 * @throws UploadStashNotLoggedInException
182 * @return UploadStashFile: file, or null on failure
184 public function stashFile( $path, $sourceType = null ) {
185 if ( ! file_exists( $path ) ) {
186 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
187 throw new UploadStashBadPathException( "path doesn't exist" );
189 $fileProps = FSFile
::getPropsFromPath( $path );
190 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
192 // we will be initializing from some tmpnam files that don't have extensions.
193 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
194 $extension = self
::getExtensionForPath( $path );
195 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
196 $pathWithGoodExtension = "$path.$extension";
197 if ( ! rename( $path, $pathWithGoodExtension ) ) {
198 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
200 $path = $pathWithGoodExtension;
203 // If no key was supplied, make one. a mysql insertid would be totally reasonable here, except
204 // that for historical reasons, the key is this random thing instead. At least it's not guessable.
206 // some things that when combined will make a suitably unique key.
207 // see: http://www.jwz.org/doc/mid.html
208 list ($usec, $sec) = explode( ' ', microtime() );
209 $usec = substr($usec, 2);
210 $key = wfBaseConvert( $sec . $usec, 10, 36 ) . '.' .
211 wfBaseConvert( mt_rand(), 10, 36 ) . '.'.
212 $this->userId
. '.' .
215 $this->fileProps
[$key] = $fileProps;
217 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
218 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
221 wfDebug( __METHOD__
. " key for '$path': $key\n" );
223 // if not already in a temporary area, put it there
224 $storeStatus = $this->repo
->storeTemp( basename( $path ), $path );
226 if ( ! $storeStatus->isOK() ) {
227 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
228 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
229 // This is a bit lame, as we may have more info in the $storeStatus and we're throwing it away, but to fix it means
230 // redesigning API errors significantly.
231 // $storeStatus->value just contains the virtual URL (if anything) which is probably useless to the caller
232 $error = $storeStatus->getErrorsArray();
233 $error = reset( $error );
234 if ( ! count( $error ) ) {
235 $error = $storeStatus->getWarningsArray();
236 $error = reset( $error );
237 if ( ! count( $error ) ) {
238 $error = array( 'unknown', 'no error recorded' );
241 // at this point, $error should contain the single "most important" error, plus any parameters.
242 throw new UploadStashFileException( "Error storing file in '$path': " . wfMessage( $error )->text() );
244 $stashPath = $storeStatus->value
;
246 // fetch the current user ID
247 if ( !$this->isLoggedIn
) {
248 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
251 // insert the file metadata into the db.
252 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
253 $dbw = $this->repo
->getMasterDb();
255 $this->fileMetadata
[$key] = array(
256 'us_id' => $dbw->nextSequenceValue( 'uploadstash_us_id_seq' ),
257 'us_user' => $this->userId
,
259 'us_orig_path' => $path,
260 'us_path' => $stashPath, // virtual URL
261 'us_size' => $fileProps['size'],
262 'us_sha1' => $fileProps['sha1'],
263 'us_mime' => $fileProps['mime'],
264 'us_media_type' => $fileProps['media_type'],
265 'us_image_width' => $fileProps['width'],
266 'us_image_height' => $fileProps['height'],
267 'us_image_bits' => $fileProps['bits'],
268 'us_source_type' => $sourceType,
269 'us_timestamp' => $dbw->timestamp(),
270 'us_status' => 'finished'
275 $this->fileMetadata
[$key],
279 // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
280 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
282 # create the UploadStashFile object for this file.
283 $this->initFile( $key );
285 return $this->getFile( $key );
289 * Remove all files from the stash.
290 * Does not clean up files in the repo, just the record of them.
292 * @throws UploadStashNotLoggedInException
293 * @return boolean: success
295 public function clear() {
296 if ( !$this->isLoggedIn
) {
297 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
300 wfDebug( __METHOD__
. ' clearing all rows for user ' . $this->userId
. "\n" );
301 $dbw = $this->repo
->getMasterDb();
304 array( 'us_user' => $this->userId
),
309 $this->files
= array();
310 $this->fileMetadata
= array();
316 * Remove a particular file from the stash. Also removes it from the repo.
318 * @throws UploadStashNotLoggedInException
319 * @throws UploadStashWrongOwnerException
320 * @return boolean: success
322 public function removeFile( $key ) {
323 if ( !$this->isLoggedIn
) {
324 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
327 $dbw = $this->repo
->getMasterDb();
329 // this is a cheap query. it runs on the master so that this function still works when there's lag.
330 // it won't be called all that often.
331 $row = $dbw->selectRow(
334 array( 'us_key' => $key ),
339 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
342 if ( $row->us_user
!= $this->userId
) {
343 throw new UploadStashWrongOwnerException( "Can't delete: the file ($key) doesn't belong to this user." );
346 return $this->removeFileNoAuth( $key );
351 * Remove a file (see removeFile), but doesn't check ownership first.
353 * @return boolean: success
355 public function removeFileNoAuth( $key ) {
356 wfDebug( __METHOD__
. " clearing row $key\n" );
358 $dbw = $this->repo
->getMasterDb();
360 // this gets its own transaction since it's called serially by the cleanupUploadStash maintenance script
361 $dbw->begin( __METHOD__
);
364 array( 'us_key' => $key ),
367 $dbw->commit( __METHOD__
);
369 // TODO: look into UnregisteredLocalFile and find out why the rv here is sometimes wrong (false when file was removed)
371 $this->files
[$key]->remove();
373 unset( $this->files
[$key] );
374 unset( $this->fileMetadata
[$key] );
380 * List all files in the stash.
382 * @throws UploadStashNotLoggedInException
385 public function listFiles() {
386 if ( !$this->isLoggedIn
) {
387 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
390 $dbr = $this->repo
->getSlaveDb();
394 array( 'us_user' => $this->userId
),
398 if ( !is_object( $res ) ||
$res->numRows() == 0 ) {
403 // finish the read before starting writes.
405 foreach ( $res as $row ) {
406 array_push( $keys, $row->us_key
);
413 * Find or guess extension -- ensuring that our extension matches our mime type.
414 * Since these files are constructed from php tempnames they may not start off
416 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
417 * uploads versus the desired filename. Maybe we can get that passed to us...
420 public static function getExtensionForPath( $path ) {
421 // Does this have an extension?
422 $n = strrpos( $path, '.' );
424 if ( $n !== false ) {
425 $extension = $n ?
substr( $path, $n +
1 ) : '';
427 // If not, assume that it should be related to the mime type of the original file.
428 $magic = MimeMagic
::singleton();
429 $mimeType = $magic->guessMimeType( $path );
430 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
431 if ( count( $extensions ) ) {
432 $extension = $extensions[0];
436 if ( is_null( $extension ) ) {
437 throw new UploadStashFileException( "extension is null" );
440 return File
::normalizeExtension( $extension );
444 * Helper function: do the actual database query to fetch file metadata.
446 * @param $key String: key
447 * @param $readFromDB: constant (default: DB_SLAVE)
450 protected function fetchFileMetadata( $key, $readFromDB = DB_SLAVE
) {
451 // populate $fileMetadata[$key]
453 if( $readFromDB === DB_MASTER
) {
454 // sometimes reading from the master is necessary, if there's replication lag.
455 $dbr = $this->repo
->getMasterDb();
457 $dbr = $this->repo
->getSlaveDb();
460 $row = $dbr->selectRow(
463 array( 'us_key' => $key ),
467 if ( !is_object( $row ) ) {
468 // key wasn't present in the database. this will happen sometimes.
472 $this->fileMetadata
[$key] = (array)$row;
478 * Helper function: Initialize the UploadStashFile for a given file.
480 * @param $key String: key under which to store the object
481 * @throws UploadStashZeroLengthFileException
484 protected function initFile( $key ) {
485 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
486 if ( $file->getSize() === 0 ) {
487 throw new UploadStashZeroLengthFileException( "File is zero length" );
489 $this->files
[$key] = $file;
494 class UploadStashFile
extends UnregisteredLocalFile
{
500 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
501 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
503 * @param $repo FileRepo: repository where we should find the path
504 * @param $path String: path to file
505 * @param $key String: key to store the path and any stashed data under
506 * @throws UploadStashBadPathException
507 * @throws UploadStashFileNotFoundException
509 public function __construct( $repo, $path, $key ) {
510 $this->fileKey
= $key;
512 // resolve mwrepo:// urls
513 if ( $repo->isVirtualUrl( $path ) ) {
514 $path = $repo->resolveVirtualUrl( $path );
517 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
518 $repoTempPath = $repo->getZonePath( 'temp' );
519 if ( ( ! $repo->validateFilename( $path ) ) ||
520 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
521 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
522 throw new UploadStashBadPathException( 'path is not valid' );
525 // check if path exists! and is a plain file.
526 if ( ! $repo->fileExists( $path ) ) {
527 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
528 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
532 parent
::__construct( false, $repo, $path, false );
534 $this->name
= basename( $this->path
);
538 * A method needed by the file transforming and scaling routines in File.php
539 * We do not necessarily care about doing the description at this point
540 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
541 * convert require it to be there)
543 * @return String: dummy value
545 public function getDescriptionUrl() {
546 return $this->getUrl();
550 * Get the path for the thumbnail (actually any transformation of this file)
551 * The actual argument is the result of thumbName although we seem to have
552 * buggy code elsewhere that expects a boolean 'suffix'
554 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
555 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
557 public function getThumbPath( $thumbName = false ) {
558 $path = dirname( $this->path
);
559 if ( $thumbName !== false ) {
560 $path .= "/$thumbName";
566 * Return the file/url base name of a thumbnail with the specified parameters.
567 * We override this because we want to use the pretty url name instead of the
570 * @param $params Array: handler-specific parameters
571 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
573 function thumbName( $params ) {
574 return $this->generateThumbName( $this->getUrlName(), $params );
578 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
579 * @param $subPage String
580 * @return String: local URL for this subpage in the Special:UploadStash space.
582 private function getSpecialUrl( $subPage ) {
583 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
587 * Get a URL to access the thumbnail
588 * This is required because the model of how files work requires that
589 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
590 * (that's hidden in the db)
592 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
593 * @return String: URL to access thumbnail, or URL with partial path
595 public function getThumbUrl( $thumbName = false ) {
596 wfDebug( __METHOD__
. " getting for $thumbName \n" );
597 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
601 * The basename for the URL, which we want to not be related to the filename.
602 * Will also be used as the lookup key for a thumbnail file.
604 * @return String: base url name, like '120px-123456.jpg'
606 public function getUrlName() {
607 if ( ! $this->urlName
) {
608 $this->urlName
= $this->fileKey
;
610 return $this->urlName
;
614 * Return the URL of the file, if for some reason we wanted to download it
615 * We tend not to do this for the original file, but we do want thumb icons
617 * @return String: url
619 public function getUrl() {
620 if ( !isset( $this->url
) ) {
621 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
627 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
628 * But with this class, the URL is unrelated to the path.
630 * @return String: url
632 public function getFullUrl() {
633 return $this->getUrl();
637 * Getter for file key (the unique id by which this file's location & metadata is stored in the db)
639 * @return String: file key
641 public function getFileKey() {
642 return $this->fileKey
;
646 * Remove the associated temporary file
647 * @return Status: success
649 public function remove() {
650 if ( !$this->repo
->fileExists( $this->path
) ) {
651 // Maybe the file's already been removed? This could totally happen in UploadBase.
655 return $this->repo
->freeTemp( $this->path
);
658 public function exists() {
659 return $this->repo
->fileExists( $this->path
);
664 class UploadStashNotAvailableException
extends MWException
{};
665 class UploadStashFileNotFoundException
extends MWException
{};
666 class UploadStashBadPathException
extends MWException
{};
667 class UploadStashFileException
extends MWException
{};
668 class UploadStashZeroLengthFileException
extends MWException
{};
669 class UploadStashNotLoggedInException
extends MWException
{};
670 class UploadStashWrongOwnerException
extends MWException
{};
671 class UploadStashNoSuchKeyException
extends MWException
{};