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 right now is *mostly* intended to show you one user's slice of the entire stash. The user parameter is only optional
14 * because there are few cases where we clean out the stash from an automated script. In the future we might refactor this.
16 * UploadStash represents the entire stash of temporary files.
17 * UploadStashFile is a filestore for the actual physical disk files.
18 * UploadFromStash extends UploadBase, and represents a single stashed file as it is moved from the stash to the regular file repository
22 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
23 const KEY_FORMAT_REGEX
= '/^[\w-\.]+\.\w*$/';
25 // When a given stashed file can't be loaded, wait for the slaves to catch up. If they're more than MAX_LAG
26 // behind, throw an exception instead. (at what point is broken better than slow?)
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();
73 // Age of the repository in seconds. That is, after how long will files be assumed abandoned and deleted?
74 global $wgUploadStashMaxAge;
75 if( $wgUploadStashMaxAge === null ) {
76 $wgUploadStashMaxAge = 6 * 3600; // default: 6 hours.
81 * Get a file and its metadata from the stash.
82 * The noAuth param is a bit janky but is required for automated scripts which clean out the stash.
84 * @param $key String: key under which file information is stored
85 * @param $noAuth Boolean (optional) Don't check authentication. Used by maintenance scripts.
86 * @throws UploadStashFileNotFoundException
87 * @throws UploadStashNotLoggedInException
88 * @throws UploadStashWrongOwnerException
89 * @throws UploadStashBadPathException
90 * @return UploadStashFile
92 public function getFile( $key, $noAuth = false ) {
94 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
95 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
99 if ( !$this->isLoggedIn
) {
100 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
104 $dbr = $this->repo
->getSlaveDb();
106 if ( !isset( $this->fileMetadata
[$key] ) ) {
107 // try this first. if it fails to find the row, check for lag, wait, try again. if its still missing, throw an exception.
108 // this more complex solution keeps things moving for page loads with many requests
109 // (ie. validating image ownership) when replag is high
110 if ( !$this->fetchFileMetadata( $key ) ) {
111 $lag = $dbr->getLag();
112 if ( $lag > 0 && $lag <= self
::MAX_LAG
) {
113 // if there's not too much replication lag, just wait for the slave to catch up to our last insert.
114 sleep( ceil( $lag ) );
115 } elseif ( $lag > self
::MAX_LAG
) {
116 // that's a lot of lag to introduce into the middle of the UI.
117 throw new UploadStashMaxLagExceededException(
118 'Couldn\'t load stashed file metadata, and replication lag is above threshold: (MAX_LAG=' . self
::MAX_LAG
. ')'
122 // now that the waiting has happened, try again
123 $this->fetchFileMetadata( $key );
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 if ( $this->repo
->isVirtualUrl( $path ) ) {
136 $path = $this->repo
->resolveVirtualUrl( $path );
138 $this->fileProps
[$key] = File
::getPropsFromPath( $path );
141 if ( ! $this->files
[$key]->exists() ) {
142 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
143 throw new UploadStashBadPathException( "path doesn't exist" );
147 if ( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
148 throw new UploadStashWrongOwnerException( "This file ($key) doesn't belong to the current user." );
152 return $this->files
[$key];
156 * Getter for file metadata.
158 * @param key String: key under which file information is stored
161 public function getMetadata ( $key ) {
162 $this->getFile( $key );
163 return $this->fileMetadata
[$key];
167 * Getter for fileProps
169 * @param key String: key under which file information is stored
172 public function getFileProps ( $key ) {
173 $this->getFile( $key );
174 return $this->fileProps
[$key];
178 * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
180 * @param $path String: path to file you want stashed
181 * @param $sourceType String: the type of upload that generated this file (currently, I believe, 'file' or null)
182 * @param $key String: optional, unique key for this file. Used for directory hashing when storing, otherwise not important
183 * @throws UploadStashBadPathException
184 * @throws UploadStashFileException
185 * @throws UploadStashNotLoggedInException
186 * @return UploadStashFile: file, or null on failure
188 public function stashFile( $path, $sourceType = null, $key = null ) {
189 if ( ! file_exists( $path ) ) {
190 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
191 throw new UploadStashBadPathException( "path doesn't exist" );
193 $fileProps = File
::getPropsFromPath( $path );
194 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
196 // we will be initializing from some tmpnam files that don't have extensions.
197 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
198 $extension = self
::getExtensionForPath( $path );
199 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
200 $pathWithGoodExtension = "$path.$extension";
201 if ( ! rename( $path, $pathWithGoodExtension ) ) {
202 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
204 $path = $pathWithGoodExtension;
207 // If no key was supplied, make one. a mysql insertid would be totally reasonable here, except
208 // that some users of this function might expect to supply the key instead of using the generated one.
209 if ( is_null( $key ) ) {
210 // some things that when combined will make a suitably unique key.
211 // see: http://www.jwz.org/doc/mid.html
212 list ($usec, $sec) = explode( ' ', microtime() );
213 $usec = substr($usec, 2);
214 $key = wfBaseConvert( $sec . $usec, 10, 36 ) . '.' .
215 wfBaseConvert( mt_rand(), 10, 36 ) . '.'.
216 $this->userId
. '.' .
220 $this->fileProps
[$key] = $fileProps;
222 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
223 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
226 wfDebug( __METHOD__
. " key for '$path': $key\n" );
228 // if not already in a temporary area, put it there
229 $storeStatus = $this->repo
->storeTemp( basename( $path ), $path );
231 if ( ! $storeStatus->isOK() ) {
232 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
233 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
234 // 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
235 // redesigning API errors significantly.
236 // $storeStatus->value just contains the virtual URL (if anything) which is probably useless to the caller
237 $error = $storeStatus->getErrorsArray();
238 $error = reset( $error );
239 if ( ! count( $error ) ) {
240 $error = $storeStatus->getWarningsArray();
241 $error = reset( $error );
242 if ( ! count( $error ) ) {
243 $error = array( 'unknown', 'no error recorded' );
246 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
248 $stashPath = $storeStatus->value
;
250 // fetch the current user ID
251 if ( !$this->isLoggedIn
) {
252 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
255 // insert the file metadata into the db.
256 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
257 $dbw = $this->repo
->getMasterDb();
259 // select happens on the master so this can all be in a transaction, which
260 // avoids a race condition that's likely with multiple people uploading from the same
263 // first, check to see if it's already there.
264 $row = $dbw->selectRow(
266 'us_user, us_timestamp',
267 array( 'us_key' => $key ),
271 // The current user can't have this key if:
272 // - the key is owned by someone else and
273 // - the age of the key is less than $wgUploadStashMaxAge
274 if ( is_object( $row ) ) {
275 if ( $row->us_user
!= $this->userId
&&
276 $row->wfTimestamp( TS_UNIX
, $row->us_timestamp
) > time() - $wgUploadStashMaxAge
279 throw new UploadStashWrongOwnerException( "Attempting to upload a duplicate of a file that someone else has stashed" );
283 $this->fileMetadata
[$key] = array(
284 'us_user' => $this->userId
,
286 'us_orig_path' => $path,
287 'us_path' => $stashPath,
288 'us_size' => $fileProps['size'],
289 'us_sha1' => $fileProps['sha1'],
290 'us_mime' => $fileProps['mime'],
291 'us_media_type' => $fileProps['media_type'],
292 'us_image_width' => $fileProps['width'],
293 'us_image_height' => $fileProps['height'],
294 'us_image_bits' => $fileProps['bits'],
295 'us_source_type' => $sourceType,
296 'us_timestamp' => $dbw->timestamp(),
297 'us_status' => 'finished'
300 // if a row exists but previous checks on it passed, let the current user take over this key.
304 $this->fileMetadata
[$key],
309 // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
310 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
312 # create the UploadStashFile object for this file.
313 $this->initFile( $key );
315 return $this->getFile( $key );
319 * Remove all files from the stash.
320 * Does not clean up files in the repo, just the record of them.
322 * @throws UploadStashNotLoggedInException
323 * @return boolean: success
325 public function clear() {
326 if ( !$this->isLoggedIn
) {
327 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
330 wfDebug( __METHOD__
. " clearing all rows for user $userId\n" );
331 $dbw = $this->repo
->getMasterDb();
334 array( 'us_user' => $this->userId
),
339 $this->files
= array();
340 $this->fileMetadata
= array();
346 * Remove a particular file from the stash. Also removes it from the repo.
348 * @throws UploadStashNotLoggedInException
349 * @throws UploadStashWrongOwnerException
350 * @return boolean: success
352 public function removeFile( $key ) {
353 if ( !$this->isLoggedIn
) {
354 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
357 $dbw = $this->repo
->getMasterDb();
359 // this is a cheap query. it runs on the master so that this function still works when there's lag.
360 // it won't be called all that often.
361 $row = $dbw->selectRow(
364 array( 'us_key' => $key ),
369 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
372 if ( $row->us_user
!= $this->userId
) {
373 throw new UploadStashWrongOwnerException( "Can't delete: the file ($key) doesn't belong to this user." );
376 return $this->removeFileNoAuth( $key );
381 * Remove a file (see removeFile), but doesn't check ownership first.
383 * @return boolean: success
385 public function removeFileNoAuth( $key ) {
386 wfDebug( __METHOD__
. " clearing row $key\n" );
388 $dbw = $this->repo
->getMasterDb();
390 // this gets its own transaction since it's called serially by the cleanupUploadStash maintenance script
394 array( 'us_key' => $key ),
399 // TODO: look into UnregisteredLocalFile and find out why the rv here is sometimes wrong (false when file was removed)
401 $this->files
[$key]->remove();
403 unset( $this->files
[$key] );
404 unset( $this->fileMetadata
[$key] );
410 * List all files in the stash.
412 * @throws UploadStashNotLoggedInException
415 public function listFiles() {
416 if ( !$this->isLoggedIn
) {
417 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
420 $dbr = $this->repo
->getSlaveDb();
424 array( 'us_key' => $key ),
428 if ( !is_object( $res ) ||
$res->numRows() == 0 ) {
433 // finish the read before starting writes.
435 foreach ( $res as $row ) {
436 array_push( $keys, $row->us_key
);
443 * Find or guess extension -- ensuring that our extension matches our mime type.
444 * Since these files are constructed from php tempnames they may not start off
446 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
447 * uploads versus the desired filename. Maybe we can get that passed to us...
449 public static function getExtensionForPath( $path ) {
450 // Does this have an extension?
451 $n = strrpos( $path, '.' );
453 if ( $n !== false ) {
454 $extension = $n ?
substr( $path, $n +
1 ) : '';
456 // If not, assume that it should be related to the mime type of the original file.
457 $magic = MimeMagic
::singleton();
458 $mimeType = $magic->guessMimeType( $path );
459 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
460 if ( count( $extensions ) ) {
461 $extension = $extensions[0];
465 if ( is_null( $extension ) ) {
466 throw new UploadStashFileException( "extension is null" );
469 return File
::normalizeExtension( $extension );
473 * Helper function: do the actual database query to fetch file metadata.
475 * @param $key String: key
478 protected function fetchFileMetadata( $key ) {
479 // populate $fileMetadata[$key]
480 $dbr = $this->repo
->getSlaveDb();
481 $row = $dbr->selectRow(
484 array( 'us_key' => $key ),
488 if ( !is_object( $row ) ) {
489 // key wasn't present in the database. this will happen sometimes.
493 $this->fileMetadata
[$key] = array(
494 'us_user' => $row->us_user
,
495 'us_key' => $row->us_key
,
496 'us_orig_path' => $row->us_orig_path
,
497 'us_path' => $row->us_path
,
498 'us_size' => $row->us_size
,
499 'us_sha1' => $row->us_sha1
,
500 'us_mime' => $row->us_mime
,
501 'us_media_type' => $row->us_media_type
,
502 'us_image_width' => $row->us_image_width
,
503 'us_image_height' => $row->us_image_height
,
504 'us_image_bits' => $row->us_image_bits
,
505 'us_source_type' => $row->us_source_type
,
506 'us_timestamp' => $row->us_timestamp
,
507 'us_status' => $row->us_status
514 * Helper function: Initialize the UploadStashFile for a given file.
516 * @param $path String: path to file
517 * @param $key String: key under which to store the object
518 * @throws UploadStashZeroLengthFileException
521 protected function initFile( $key ) {
522 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
523 if ( $file->getSize() === 0 ) {
524 throw new UploadStashZeroLengthFileException( "File is zero length" );
526 $this->files
[$key] = $file;
531 class UploadStashFile
extends UnregisteredLocalFile
{
537 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
538 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
540 * @param $repo FSRepo: repository where we should find the path
541 * @param $path String: path to file
542 * @param $key String: key to store the path and any stashed data under
543 * @throws UploadStashBadPathException
544 * @throws UploadStashFileNotFoundException
546 public function __construct( $repo, $path, $key ) {
547 $this->fileKey
= $key;
549 // resolve mwrepo:// urls
550 if ( $repo->isVirtualUrl( $path ) ) {
551 $path = $repo->resolveVirtualUrl( $path );
554 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
555 $repoTempPath = $repo->getZonePath( 'temp' );
556 if ( ( ! $repo->validateFilename( $path ) ) ||
557 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
558 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
559 throw new UploadStashBadPathException( 'path is not valid' );
562 // check if path exists! and is a plain file.
563 if ( ! $repo->fileExists( $path, FileRepo
::FILES_ONLY
) ) {
564 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
565 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
569 parent
::__construct( false, $repo, $path, false );
571 $this->name
= basename( $this->path
);
575 * A method needed by the file transforming and scaling routines in File.php
576 * We do not necessarily care about doing the description at this point
577 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
578 * convert require it to be there)
580 * @return String: dummy value
582 public function getDescriptionUrl() {
583 return $this->getUrl();
587 * Get the path for the thumbnail (actually any transformation of this file)
588 * The actual argument is the result of thumbName although we seem to have
589 * buggy code elsewhere that expects a boolean 'suffix'
591 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
592 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
594 public function getThumbPath( $thumbName = false ) {
595 $path = dirname( $this->path
);
596 if ( $thumbName !== false ) {
597 $path .= "/$thumbName";
603 * Return the file/url base name of a thumbnail with the specified parameters.
604 * We override this because we want to use the pretty url name instead of the
607 * @param $params Array: handler-specific parameters
608 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
610 function thumbName( $params ) {
611 return $this->generateThumbName( $this->getUrlName(), $params );
615 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
616 * @param {String} $subPage
617 * @return {String} local URL for this subpage in the Special:UploadStash space.
619 private function getSpecialUrl( $subPage ) {
620 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
624 * Get a URL to access the thumbnail
625 * This is required because the model of how files work requires that
626 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
627 * (that's hidden in the db)
629 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
630 * @return String: URL to access thumbnail, or URL with partial path
632 public function getThumbUrl( $thumbName = false ) {
633 wfDebug( __METHOD__
. " getting for $thumbName \n" );
634 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
638 * The basename for the URL, which we want to not be related to the filename.
639 * Will also be used as the lookup key for a thumbnail file.
641 * @return String: base url name, like '120px-123456.jpg'
643 public function getUrlName() {
644 if ( ! $this->urlName
) {
645 $this->urlName
= $this->fileKey
;
647 return $this->urlName
;
651 * Return the URL of the file, if for some reason we wanted to download it
652 * We tend not to do this for the original file, but we do want thumb icons
654 * @return String: url
656 public function getUrl() {
657 if ( !isset( $this->url
) ) {
658 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
664 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
665 * But with this class, the URL is unrelated to the path.
667 * @return String: url
669 public function getFullUrl() {
670 return $this->getUrl();
674 * Getter for file key (the unique id by which this file's location & metadata is stored in the db)
676 * @return String: file key
678 public function getFileKey() {
679 return $this->fileKey
;
683 * Remove the associated temporary file
684 * @return Status: success
686 public function remove() {
687 if ( !$this->repo
->fileExists( $this->path
, FileRepo
::FILES_ONLY
) ) {
688 // Maybe the file's already been removed? This could totally happen in UploadBase.
692 return $this->repo
->freeTemp( $this->path
);
695 public function exists() {
696 return $this->repo
->fileExists( $this->path
, FileRepo
::FILES_ONLY
);
701 class UploadStashNotAvailableException
extends MWException
{};
702 class UploadStashFileNotFoundException
extends MWException
{};
703 class UploadStashBadPathException
extends MWException
{};
704 class UploadStashFileException
extends MWException
{};
705 class UploadStashZeroLengthFileException
extends MWException
{};
706 class UploadStashNotLoggedInException
extends MWException
{};
707 class UploadStashWrongOwnerException
extends MWException
{};
708 class UploadStashMaxLagExceededException
extends MWException
{};
709 class UploadStashNoSuchKeyException
extends MWException
{};