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 db table 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 using a database table, with ownership checking as you might expect. See SpecialUploadStash, which
11 * implements a web interface to some files stored this way.
13 * UploadStash represents the entire stash of temporary files.
14 * UploadStashFile is a filestore for the actual physical disk files.
15 * UploadFromStash extends UploadBase, and represents a single stashed file as it is moved from the stash to the regular file repository
19 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
20 const KEY_FORMAT_REGEX
= '/^[\w-]+\.\w*$/';
22 // When a given stashed file can't be loaded, wait for the slaves to catch up. If they're more than MAX_LAG
23 // behind, throw an exception instead. (at what point is broken better than slow?)
26 // Age of the repository in hours. That is, after how long will files be assumed abandoned and deleted?
30 * repository that this uses to store temp files
31 * public because we sometimes need to get a LocalFile within the same repo.
37 // array of initialized repo objects
38 protected $files = array();
40 // cache of the file metadata that's stored in the database
41 protected $fileMetadata = array();
44 protected $fileProps = array();
47 protected $user, $userId, $isLoggedIn;
50 * Represents a temporary filestore, with metadata in the database.
51 * Designed to be compatible with the session stashing code in UploadBase (should replace it eventually)
53 * @param $repo FileRepo
55 public function __construct( $repo, $user = null ) {
56 // this might change based on wiki's configuration.
59 // if a user was passed, use it. otherwise, attempt to use the global.
60 // this keeps FileRepo from breaking when it creates an UploadStash object
65 $this->user
= $wgUser;
68 if( is_object($this->user
) ) {
69 $this->userId
= $this->user
->getId();
70 $this->isLoggedIn
= $this->user
->isLoggedIn();
75 * Get a file and its metadata from the stash.
77 * @param $key String: key under which file information is stored
78 * @param $noAuth Boolean (optional) Don't check authentication. Used by maintenance scripts.
79 * @throws UploadStashFileNotFoundException
80 * @throws UploadStashNotLoggedInException
81 * @throws UploadStashWrongOwnerException
82 * @throws UploadStashBadPathException
83 * @return UploadStashFile
85 public function getFile( $key, $noAuth = false ) {
87 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
88 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
92 if( !$this->isLoggedIn
) {
93 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
97 $dbr = $this->repo
->getSlaveDb();
99 if ( !isset( $this->fileMetadata
[$key] ) ) {
100 // try this first. if it fails to find the row, check for lag, wait, try again. if its still missing, throw an exception.
101 // this more complex solution keeps things moving for page loads with many requests
102 // (ie. validating image ownership) when replag is high
103 if( !$this->fetchFileMetadata($key) ) {
104 $lag = $dbr->getLag();
105 if( $lag > 0 && $lag <= self
::MAX_LAG
) {
106 // if there's not too much replication lag, just wait for the slave to catch up to our last insert.
107 sleep( ceil( $lag ) );
108 } elseif($lag > self
::MAX_LAG
) {
109 // that's a lot of lag to introduce into the middle of the UI.
110 throw new UploadStashMaxLagExceededException(
111 'Couldn\'t load stashed file metadata, and replication lag is above threshold: (MAX_LAG=' . self
::MAX_LAG
. ')'
115 // now that the waiting has happened, try again
116 $this->fetchFileMetadata($key);
119 if ( !isset( $this->fileMetadata
[$key] ) ) {
120 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
123 // create $this->files[$key]
124 $this->initFile( $key );
127 $path = $this->fileMetadata
[$key]['us_path'];
128 if ( $this->repo
->isVirtualUrl( $path ) ) {
129 $path = $this->repo
->resolveVirtualUrl( $path );
131 $this->fileProps
[$key] = File
::getPropsFromPath( $path );
134 if ( ! $this->files
[$key]->exists() ) {
135 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
136 throw new UploadStashBadPathException( "path doesn't exist" );
140 if( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
141 throw new UploadStashWrongOwnerException( "This file ($key) doesn't belong to the current user." );
145 return $this->files
[$key];
149 * Getter for file metadata.
151 * @param key String: key under which file information is stored
154 public function getMetadata ( $key ) {
155 $this->getFile( $key );
156 return $this->fileMetadata
[$key];
160 * Getter for fileProps
162 * @param key String: key under which file information is stored
165 public function getFileProps ( $key ) {
166 $this->getFile( $key );
167 return $this->fileProps
[$key];
171 * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
173 * @param $path String: path to file you want stashed
174 * @param $sourceType String: the type of upload that generated this file (currently, I believe, 'file' or null)
175 * @param $key String: optional, unique key for this file. Used for directory hashing when storing, otherwise not important
176 * @throws UploadStashBadPathException
177 * @throws UploadStashFileException
178 * @throws UploadStashNotLoggedInException
179 * @return UploadStashFile: file, or null on failure
181 public function stashFile( $path, $sourceType = null, $key = null ) {
182 if ( ! file_exists( $path ) ) {
183 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
184 throw new UploadStashBadPathException( "path doesn't exist" );
186 $fileProps = File
::getPropsFromPath( $path );
188 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
190 // we will be initializing from some tmpnam files that don't have extensions.
191 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
192 $extension = self
::getExtensionForPath( $path );
193 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
194 $pathWithGoodExtension = "$path.$extension";
195 if ( ! rename( $path, $pathWithGoodExtension ) ) {
196 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
198 $path = $pathWithGoodExtension;
201 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
202 // uploaded this session, which could happen if uploads had failed.
203 if ( is_null( $key ) ) {
204 $key = $fileProps['sha1'] . "." . $extension;
207 $this->fileProps
[$key] = $fileProps;
209 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
210 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
213 wfDebug( __METHOD__
. " key for '$path': $key\n" );
215 // if not already in a temporary area, put it there
216 $storeResult = $this->repo
->storeTemp( basename( $path ), $path );
218 if( ! $storeResult->isOK() ) {
219 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
220 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
221 // This is a bit lame, as we may have more info in the $storeResult and we're throwing it away, but to fix it means
222 // redesigning API errors significantly.
223 // $storeResult->value just contains the virtual URL (if anything) which is probably useless to the caller
224 $error = $storeResult->getErrorsArray();
225 $error = reset( $error );
226 if ( ! count( $error ) ) {
227 $error = $storeResult->getWarningsArray();
228 $error = reset( $error );
229 if ( ! count( $error ) ) {
230 $error = array( 'unknown', 'no error recorded' );
233 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
235 $stashPath = $storeResult->value
;
237 // fetch the current user ID
238 if( !$this->isLoggedIn
) {
240 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
243 // insert the file metadata into the db.
244 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
245 $dbw = $this->repo
->getMasterDb();
247 // select happens on the master so this can all be in a transaction, which
248 // avoids a race condition that's likely with multiple people uploading from the same
251 // first, check to see if it's already there.
252 $row = $dbw->selectRow(
254 'us_user, us_timestamp',
255 array('us_key' => $key),
259 // The current user can't have this key if:
260 // - the key is owned by someone else and
261 // - the age of the key is less than REPO_AGE
262 if( is_object( $row ) ) {
263 if( $row->us_user
!= $this->userId
&&
264 $row->wfTimestamp( TS_UNIX
, $row->us_timestamp
) > time() - UploadStash
::REPO_AGE
* 3600
267 throw new UploadStashWrongOwnerException( "Attempting to upload a duplicate of a file that someone else has stashed" );
271 $this->fileMetadata
[$key] = array(
272 'us_user' => $this->userId
,
274 'us_orig_path' => $path,
275 'us_path' => $stashPath,
276 'us_size' => $fileProps['size'],
277 'us_sha1' => $fileProps['sha1'],
278 'us_mime' => $fileProps['mime'],
279 'us_media_type' => $fileProps['media_type'],
280 'us_image_width' => $fileProps['width'],
281 'us_image_height' => $fileProps['height'],
282 'us_image_bits' => $fileProps['bits'],
283 'us_source_type' => $sourceType,
284 'us_timestamp' => $dbw->timestamp(),
285 'us_status' => 'finished'
288 // if a row exists but previous checks on it passed, let the current user take over this key.
292 $this->fileMetadata
[$key],
297 // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
298 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
300 # create the UploadStashFile object for this file.
301 $this->initFile( $key );
303 return $this->getFile( $key );
307 * Remove all files from the stash.
308 * Does not clean up files in the repo, just the record of them.
310 * @throws UploadStashNotLoggedInException
311 * @return boolean: success
313 public function clear() {
314 if( !$this->isLoggedIn
) {
315 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
318 wfDebug( __METHOD__
. " clearing all rows for user $userId\n" );
319 $dbw = $this->repo
->getMasterDb();
322 array( 'us_user' => $this->userId
),
327 $this->files
= array();
328 $this->fileMetadata
= array();
334 * Remove a particular file from the stash. Also removes it from the repo.
336 * @throws UploadStashNotLoggedInException
337 * @throws UploadStashWrongOwnerException
338 * @return boolean: success
340 public function removeFile( $key ){
341 if( !$this->isLoggedIn
) {
342 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
345 $dbw = $this->repo
->getMasterDb();
347 // this is a cheap query. it runs on the master so that this function still works when there's lag.
348 // it won't be called all that often.
349 $row = $dbw->selectRow(
352 array('us_key' => $key),
356 if( $row->us_user
!= $this->userId
) {
357 throw new UploadStashWrongOwnerException( "Can't delete: the file ($key) doesn't belong to this user." );
360 return $this->removeFileNoAuth( $key );
365 * Remove a file (see removeFile), but doesn't check ownership first.
367 * @return boolean: success
369 public function removeFileNoAuth( $key ) {
370 wfDebug( __METHOD__
. " clearing row $key\n" );
372 $dbw = $this->repo
->getMasterDb();
374 // this gets its own transaction since it's called serially by the cleanupUploadStash maintenance script
378 array( 'us_key' => $key),
383 // TODO: look into UnregisteredLocalFile and find out why the rv here is sometimes wrong (false when file was removed)
385 $this->files
[$key]->remove();
387 unset( $this->files
[$key] );
388 unset( $this->fileMetadata
[$key] );
394 * List all files in the stash.
396 * @throws UploadStashNotLoggedInException
399 public function listFiles() {
400 if( !$this->isLoggedIn
) {
401 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
404 $dbr = $this->repo
->getSlaveDb();
408 array('us_key' => $key),
412 if( !is_object( $res ) ||
$res->numRows() == 0 ) {
417 // finish the read before starting writes.
419 foreach($res as $row) {
420 array_push( $keys, $row->us_key
);
427 * Find or guess extension -- ensuring that our extension matches our mime type.
428 * Since these files are constructed from php tempnames they may not start off
430 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
431 * uploads versus the desired filename. Maybe we can get that passed to us...
433 public static function getExtensionForPath( $path ) {
434 // Does this have an extension?
435 $n = strrpos( $path, '.' );
437 if ( $n !== false ) {
438 $extension = $n ?
substr( $path, $n +
1 ) : '';
440 // If not, assume that it should be related to the mime type of the original file.
441 $magic = MimeMagic
::singleton();
442 $mimeType = $magic->guessMimeType( $path );
443 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
444 if ( count( $extensions ) ) {
445 $extension = $extensions[0];
449 if ( is_null( $extension ) ) {
450 throw new UploadStashFileException( "extension is null" );
453 return File
::normalizeExtension( $extension );
457 * Helper function: do the actual database query to fetch file metadata.
459 * @param $key String: key
462 protected function fetchFileMetadata( $key ) {
463 // populate $fileMetadata[$key]
464 $dbr = $this->repo
->getSlaveDb();
465 $row = $dbr->selectRow(
468 array('us_key' => $key),
472 if( !is_object( $row ) ) {
473 // key wasn't present in the database. this will happen sometimes.
477 $this->fileMetadata
[$key] = array(
478 'us_user' => $row->us_user
,
479 'us_key' => $row->us_key
,
480 'us_orig_path' => $row->us_orig_path
,
481 'us_path' => $row->us_path
,
482 'us_size' => $row->us_size
,
483 'us_sha1' => $row->us_sha1
,
484 'us_mime' => $row->us_mime
,
485 'us_media_type' => $row->us_media_type
,
486 'us_image_width' => $row->us_image_width
,
487 'us_image_height' => $row->us_image_height
,
488 'us_image_bits' => $row->us_image_bits
,
489 'us_source_type' => $row->us_source_type
,
490 'us_timestamp' => $row->us_timestamp
,
491 'us_status' => $row->us_status
498 * Helper function: Initialize the UploadStashFile for a given file.
500 * @param $path String: path to file
501 * @param $key String: key under which to store the object
502 * @throws UploadStashZeroLengthFileException
505 protected function initFile( $key ) {
506 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
507 if ( $file->getSize() === 0 ) {
508 throw new UploadStashZeroLengthFileException( "File is zero length" );
510 $this->files
[$key] = $file;
515 class UploadStashFile
extends UnregisteredLocalFile
{
521 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
522 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
524 * @param $repo FSRepo: repository where we should find the path
525 * @param $path String: path to file
526 * @param $key String: key to store the path and any stashed data under
527 * @throws UploadStashBadPathException
528 * @throws UploadStashFileNotFoundException
530 public function __construct( $repo, $path, $key ) {
531 $this->fileKey
= $key;
533 // resolve mwrepo:// urls
534 if ( $repo->isVirtualUrl( $path ) ) {
535 $path = $repo->resolveVirtualUrl( $path );
538 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
539 $repoTempPath = $repo->getZonePath( 'temp' );
540 if ( ( ! $repo->validateFilename( $path ) ) ||
541 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
542 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
543 throw new UploadStashBadPathException( 'path is not valid' );
546 // check if path exists! and is a plain file.
547 if ( ! $repo->fileExists( $path, FileRepo
::FILES_ONLY
) ) {
548 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
549 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
553 parent
::__construct( false, $repo, $path, false );
555 $this->name
= basename( $this->path
);
559 * A method needed by the file transforming and scaling routines in File.php
560 * We do not necessarily care about doing the description at this point
561 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
562 * convert require it to be there)
564 * @return String: dummy value
566 public function getDescriptionUrl() {
567 return $this->getUrl();
571 * Get the path for the thumbnail (actually any transformation of this file)
572 * The actual argument is the result of thumbName although we seem to have
573 * buggy code elsewhere that expects a boolean 'suffix'
575 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
576 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
578 public function getThumbPath( $thumbName = false ) {
579 $path = dirname( $this->path
);
580 if ( $thumbName !== false ) {
581 $path .= "/$thumbName";
587 * Return the file/url base name of a thumbnail with the specified parameters.
588 * We override this because we want to use the pretty url name instead of the
591 * @param $params Array: handler-specific parameters
592 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
594 function thumbName( $params ) {
595 return $this->generateThumbName( $this->getUrlName(), $params );
599 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
600 * @param {String} $subPage
601 * @return {String} local URL for this subpage in the Special:UploadStash space.
603 private function getSpecialUrl( $subPage ) {
604 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
608 * Get a URL to access the thumbnail
609 * This is required because the model of how files work requires that
610 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
611 * (that's hidden in the db)
613 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
614 * @return String: URL to access thumbnail, or URL with partial path
616 public function getThumbUrl( $thumbName = false ) {
617 wfDebug( __METHOD__
. " getting for $thumbName \n" );
618 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
622 * The basename for the URL, which we want to not be related to the filename.
623 * Will also be used as the lookup key for a thumbnail file.
625 * @return String: base url name, like '120px-123456.jpg'
627 public function getUrlName() {
628 if ( ! $this->urlName
) {
629 $this->urlName
= $this->fileKey
;
631 return $this->urlName
;
635 * Return the URL of the file, if for some reason we wanted to download it
636 * We tend not to do this for the original file, but we do want thumb icons
638 * @return String: url
640 public function getUrl() {
641 if ( !isset( $this->url
) ) {
642 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
648 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
649 * But with this class, the URL is unrelated to the path.
651 * @return String: url
653 public function getFullUrl() {
654 return $this->getUrl();
658 * Getter for file key (the unique id by which this file's location & metadata is stored in the db)
660 * @return String: file key
662 public function getFileKey() {
663 return $this->fileKey
;
667 * Remove the associated temporary file
668 * @return Status: success
670 public function remove() {
671 if( !$this->repo
->fileExists( $this->path
, FileRepo
::FILES_ONLY
) ) {
672 // Maybe the file's already been removed? This could totally happen in UploadBase.
676 return $this->repo
->freeTemp( $this->path
);
679 public function exists() {
680 return $this->repo
->fileExists( $this->path
, FileRepo
::FILES_ONLY
);
685 class UploadStashNotAvailableException
extends MWException
{};
686 class UploadStashFileNotFoundException
extends MWException
{};
687 class UploadStashBadPathException
extends MWException
{};
688 class UploadStashFileException
extends MWException
{};
689 class UploadStashZeroLengthFileException
extends MWException
{};
690 class UploadStashNotLoggedInException
extends MWException
{};
691 class UploadStashWrongOwnerException
extends MWException
{};
692 class UploadStashMaxLagExceededException
extends MWException
{};