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 * Represents a temporary filestore, with metadata in the database.
48 * Designed to be compatible with the session stashing code in UploadBase (should replace it eventually)
50 * @param $repo FileRepo
52 public function __construct( $repo ) {
53 // this might change based on wiki's configuration.
58 * Get a file and its metadata from the stash.
60 * @param $key String: key under which file information is stored
61 * @param $noauth Boolean (optional) Don't check authentication. Used by maintenance scripts.
62 * @throws UploadStashFileNotFoundException
63 * @throws UploadStashNotLoggedInException
64 * @throws UploadStashWrongOwnerException
65 * @throws UploadStashBadPathException
66 * @return UploadStashFile
68 public function getFile( $key, $noAuth = false ) {
71 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
72 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
76 $userId = $wgUser->getId();
78 throw new UploadStashNotLoggedInException( 'No user is logged in, files must belong to users' );
82 if ( !isset( $this->fileMetadata
[$key] ) ) {
83 // try this first. if it fails to find the row, check for lag, wait, try again. if its still missing, throw an exception.
84 // this more complex solution keeps things moving for page loads with many requests
85 // (ie. validating image ownership) when replag is high
86 if( !$this->fetchFileMetadata($key) ) {
87 $lag = $dbr->getLag();
88 if( $lag > 0 && $lag <= self
::MAX_LAG
) {
89 // if there's not too much replication lag, just wait for the slave to catch up to our last insert.
90 sleep( ceil( $lag ) );
91 } elseif($lag > self
::MAX_LAG
) {
92 // that's a lot of lag to introduce into the middle of the UI.
93 throw new UploadStashMaxLagExceededException(
94 'Couldn\'t load stashed file metadata, and replication lag is above threshold: (MAX_LAG=' . self
::MAX_LAG
. ')'
98 // now that the waiting has happened, try again
99 $this->fetchFileMetadata($key);
102 if ( !isset( $this->fileMetadata
[$key] ) ) {
103 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
106 // create $this->files[$key]
107 $this->initFile( $key );
110 $path = $this->fileMetadata
[$key]['us_path'];
111 if ( $this->repo
->isVirtualUrl( $path ) ) {
112 $path = $this->repo
->resolveVirtualUrl( $path );
114 $this->fileProps
[$key] = File
::getPropsFromPath( $path );
118 if( $this->fileMetadata
[$key]['us_user'] != $userId ) {
119 throw new UploadStashWrongOwnerException( "This file ($key) doesn't belong to the current user." );
123 return $this->files
[$key];
127 * Getter for file metadata.
129 * @param key String: key under which file information is stored
132 public function getMetadata ( $key ) {
133 $this->getFile( $key );
134 return $this->fileMetadata
[$key];
138 * Getter for fileProps
140 * @param key String: key under which file information is stored
143 public function getFileProps ( $key ) {
144 $this->getFile( $key );
145 return $this->fileProps
[$key];
149 * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
151 * @param $path String: path to file you want stashed
152 * @param $sourceType String: the type of upload that generated this file (currently, I believe, 'file' or null)
153 * @param $key String: optional, unique key for this file. Used for directory hashing when storing, otherwise not important
154 * @throws UploadStashBadPathException
155 * @throws UploadStashFileException
156 * @throws UploadStashNotLoggedInException
157 * @return UploadStashFile: file, or null on failure
159 public function stashFile( $path, $sourceType = null, $key = null ) {
161 if ( ! file_exists( $path ) ) {
162 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
163 throw new UploadStashBadPathException( "path doesn't exist" );
165 $fileProps = File
::getPropsFromPath( $path );
167 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
169 // we will be initializing from some tmpnam files that don't have extensions.
170 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
171 $extension = self
::getExtensionForPath( $path );
172 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
173 $pathWithGoodExtension = "$path.$extension";
174 if ( ! rename( $path, $pathWithGoodExtension ) ) {
175 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
177 $path = $pathWithGoodExtension;
180 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
181 // uploaded this session, which could happen if uploads had failed.
182 if ( is_null( $key ) ) {
183 $key = $fileProps['sha1'] . "." . $extension;
186 $this->fileProps
[$key] = $fileProps;
188 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
189 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
192 wfDebug( __METHOD__
. " key for '$path': $key\n" );
194 // if not already in a temporary area, put it there
195 $storeResult = $this->repo
->storeTemp( basename( $path ), $path );
197 if( ! $storeResult->isOK() ) {
198 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
199 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
200 // 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
201 // redesigning API errors significantly.
202 // $storeResult->value just contains the virtual URL (if anything) which is probably useless to the caller
203 $error = $storeResult->getErrorsArray();
204 $error = reset( $error );
205 if ( ! count( $error ) ) {
206 $error = $storeResult->getWarningsArray();
207 $error = reset( $error );
208 if ( ! count( $error ) ) {
209 $error = array( 'unknown', 'no error recorded' );
212 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
214 $stashPath = $storeResult->value
;
216 // fetch the current user ID
217 $userId = $wgUser->getId();
219 throw new UploadStashNotLoggedInException( "No user is logged in, files must belong to users" );
222 $this->fileMetadata
[$key] = array(
223 'us_user' => $userId,
225 'us_orig_path' => $path,
226 'us_path' => $stashPath,
227 'us_size' => $fileProps['size'],
228 'us_sha1' => $fileProps['sha1'],
229 'us_mime' => $fileProps['mime'],
230 'us_media_type' => $fileProps['media_type'],
231 'us_image_width' => $fileProps['width'],
232 'us_image_height' => $fileProps['height'],
233 'us_image_bits' => $fileProps['bits'],
234 'us_source_type' => $sourceType,
235 'us_timestamp' => wfTimestamp( TS_MW
)
238 // insert the file metadata into the db.
239 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
240 $dbw = wfGetDB( DB_MASTER
);
243 $this->fileMetadata
[$key],
247 // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
248 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
250 # create the UploadStashFile object for this file.
251 $this->initFile( $key );
253 return $this->getFile( $key );
257 * Remove all files from the stash.
258 * Does not clean up files in the repo, just the record of them.
260 * @throws UploadStashNotLoggedInException
261 * @return boolean: success
263 public function clear() {
266 $userId = $wgUser->getId();
268 throw new UploadStashNotLoggedInException( 'No user is logged in, files must belong to users' );
271 wfDebug( __METHOD__
. " clearing all rows for user $userId\n" );
272 $dbw = wfGetDB( DB_MASTER
);
275 array( 'us_user' => $userId ),
280 $this->files
= array();
281 $this->fileMetadata
= array();
287 * Remove a particular file from the stash. Also removes it from the repo.
289 * @throws UploadStashNotLoggedInException
290 * @throws UploadStashWrongOwnerException
291 * @return boolean: success
293 public function removeFile( $key ){
296 $userId = $wgUser->getId();
298 throw new UploadStashNotLoggedInException( 'No user is logged in, files must belong to users' );
301 $dbw = wfGetDB( DB_MASTER
);
303 // this is a cheap query. it runs on the master so that this function still works when there's lag.
304 // it won't be called all that often.
305 $row = $dbw->selectRow(
308 array('us_key' => $key),
312 if( $row->us_user
!= $userId ) {
313 throw new UploadStashWrongOwnerException( "Can't delete: the file ($key) doesn't belong to this user." );
316 return $this->removeFileNoAuth( $key );
321 * Remove a file (see removeFile), but doesn't check ownership first.
323 * @return boolean: success
325 public function removeFileNoAuth( $key ) {
326 wfDebug( __METHOD__
. " clearing row $key\n" );
328 $dbw = wfGetDB( DB_MASTER
);
330 // this gets its own transaction since it's called serially by the cleanupUploadStash maintenance script
334 array( 'us_key' => $key),
339 // TODO: look into UnregisteredLocalFile and find out why the rv here is sometimes wrong (false when file was removed)
341 $this->files
[$key]->remove();
343 unset( $this->files
[$key] );
344 unset( $this->fileMetadata
[$key] );
350 * List all files in the stash.
352 * @throws UploadStashNotLoggedInException
355 public function listFiles() {
358 $userId = $wgUser->getId();
360 throw new UploadStashNotLoggedInException( 'No user is logged in, files must belong to users' );
363 $dbw = wfGetDB( DB_SLAVE
);
367 array('us_key' => $key),
371 if( !is_object( $res ) ) {
377 while( $row = $dbr->fetchRow( $res ) ) {
378 array_push( $keys, $row['us_key'] );
385 * Find or guess extension -- ensuring that our extension matches our mime type.
386 * Since these files are constructed from php tempnames they may not start off
388 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
389 * uploads versus the desired filename. Maybe we can get that passed to us...
391 public static function getExtensionForPath( $path ) {
392 // Does this have an extension?
393 $n = strrpos( $path, '.' );
395 if ( $n !== false ) {
396 $extension = $n ?
substr( $path, $n +
1 ) : '';
398 // If not, assume that it should be related to the mime type of the original file.
399 $magic = MimeMagic
::singleton();
400 $mimeType = $magic->guessMimeType( $path );
401 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
402 if ( count( $extensions ) ) {
403 $extension = $extensions[0];
407 if ( is_null( $extension ) ) {
408 throw new UploadStashFileException( "extension is null" );
411 return File
::normalizeExtension( $extension );
415 * Helper function: do the actual database query to fetch file metadata.
417 * @param $key String: key
420 protected function fetchFileMetadata( $key ) {
421 // populate $fileMetadata[$key]
422 $dbr = wfGetDB( DB_SLAVE
);
423 $row = $dbr->selectRow(
426 array('us_key' => $key),
430 if( !is_object( $row ) ) {
431 // key wasn't present in the database. this will happen sometimes.
435 $this->fileMetadata
[$key] = array(
436 'us_user' => $row->us_user
,
437 'us_key' => $row->us_key
,
438 'us_orig_path' => $row->us_orig_path
,
439 'us_path' => $row->us_path
,
440 'us_size' => $row->us_size
,
441 'us_sha1' => $row->us_sha1
,
442 'us_mime' => $row->us_mime
,
443 'us_media_type' => $row->us_media_type
,
444 'us_image_width' => $row->us_image_width
,
445 'us_image_height' => $row->us_image_height
,
446 'us_image_bits' => $row->us_image_bits
,
447 'us_source_type' => $row->us_source_type
454 * Helper function: Initialize the UploadStashFile for a given file.
456 * @param $path String: path to file
457 * @param $key String: key under which to store the object
458 * @throws UploadStashZeroLengthFileException
461 protected function initFile( $key ) {
462 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
463 if ( $file->getSize() === 0 ) {
464 throw new UploadStashZeroLengthFileException( "File is zero length" );
466 $this->files
[$key] = $file;
471 class UploadStashFile
extends UnregisteredLocalFile
{
477 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
478 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
480 * @param $repo FSRepo: repository where we should find the path
481 * @param $path String: path to file
482 * @param $key String: key to store the path and any stashed data under
483 * @throws UploadStashBadPathException
484 * @throws UploadStashFileNotFoundException
486 public function __construct( $repo, $path, $key ) {
487 $this->fileKey
= $key;
489 // resolve mwrepo:// urls
490 if ( $repo->isVirtualUrl( $path ) ) {
491 $path = $repo->resolveVirtualUrl( $path );
494 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
495 $repoTempPath = $repo->getZonePath( 'temp' );
496 if ( ( ! $repo->validateFilename( $path ) ) ||
497 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
498 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
499 throw new UploadStashBadPathException( 'path is not valid' );
502 // check if path exists! and is a plain file.
503 if ( ! $repo->fileExists( $path, FileRepo
::FILES_ONLY
) ) {
504 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
505 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
509 parent
::__construct( false, $repo, $path, false );
511 $this->name
= basename( $this->path
);
515 * A method needed by the file transforming and scaling routines in File.php
516 * We do not necessarily care about doing the description at this point
517 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
518 * convert require it to be there)
520 * @return String: dummy value
522 public function getDescriptionUrl() {
523 return $this->getUrl();
527 * Get the path for the thumbnail (actually any transformation of this file)
528 * The actual argument is the result of thumbName although we seem to have
529 * buggy code elsewhere that expects a boolean 'suffix'
531 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
532 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
534 public function getThumbPath( $thumbName = false ) {
535 $path = dirname( $this->path
);
536 if ( $thumbName !== false ) {
537 $path .= "/$thumbName";
543 * Return the file/url base name of a thumbnail with the specified parameters.
544 * We override this because we want to use the pretty url name instead of the
547 * @param $params Array: handler-specific parameters
548 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
550 function thumbName( $params ) {
551 return $this->generateThumbName( $this->getUrlName(), $params );
555 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
556 * @param {String} $subPage
557 * @return {String} local URL for this subpage in the Special:UploadStash space.
559 private function getSpecialUrl( $subPage ) {
560 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
564 * Get a URL to access the thumbnail
565 * This is required because the model of how files work requires that
566 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
567 * (that's hidden in the db)
569 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
570 * @return String: URL to access thumbnail, or URL with partial path
572 public function getThumbUrl( $thumbName = false ) {
573 wfDebug( __METHOD__
. " getting for $thumbName \n" );
574 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
578 * The basename for the URL, which we want to not be related to the filename.
579 * Will also be used as the lookup key for a thumbnail file.
581 * @return String: base url name, like '120px-123456.jpg'
583 public function getUrlName() {
584 if ( ! $this->urlName
) {
585 $this->urlName
= $this->fileKey
;
587 return $this->urlName
;
591 * Return the URL of the file, if for some reason we wanted to download it
592 * We tend not to do this for the original file, but we do want thumb icons
594 * @return String: url
596 public function getUrl() {
597 if ( !isset( $this->url
) ) {
598 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
604 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
605 * But with this class, the URL is unrelated to the path.
607 * @return String: url
609 public function getFullUrl() {
610 return $this->getUrl();
614 * Getter for file key (the unique id by which this file's location & metadata is stored in the db)
616 * @return String: file key
618 public function getFileKey() {
619 return $this->fileKey
;
623 * Remove the associated temporary file
624 * @return Status: success
626 public function remove() {
627 if( !$this->repo
->fileExists( $this->path
, FileRepo
::FILES_ONLY
) ) {
628 // Maybe the file's already been removed? This could totally happen in UploadBase.
632 return $this->repo
->freeTemp( $this->path
);
637 class UploadStashNotAvailableException
extends MWException
{};
638 class UploadStashFileNotFoundException
extends MWException
{};
639 class UploadStashBadPathException
extends MWException
{};
640 class UploadStashFileException
extends MWException
{};
641 class UploadStashZeroLengthFileException
extends MWException
{};
642 class UploadStashNotLoggedInException
extends MWException
{};
643 class UploadStashWrongOwnerException
extends MWException
{};
644 class UploadStashMaxLagExceededException
extends MWException
{};