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
28 * - Several parts of MediaWiki do this in similar ways: UploadBase,
29 * UploadWizard, and FirefoggChunkedExtension.
30 * And there are several that reimplement stashing from scratch, in
31 * idiosyncratic ways. The idea is to unify them all here.
32 * Mostly all of them are the same except for storing some custom fields,
33 * which we subsume into the data array.
34 * - Enable applications to find said files later, as long as the db table or
35 * temp files haven't been purged.
36 * - Enable the uploading user (and *ONLY* the uploading user) to access said
37 * files, and thumbnails of said files, via a URL. We accomplish this using
38 * a database table, with ownership checking as you might expect. See
39 * SpecialUploadStash, which implements a web interface to some files stored
42 * UploadStash right now is *mostly* intended to show you one user's slice of
43 * the entire stash. The user parameter is only optional because there are few
44 * cases where we clean out the stash from an automated script. In the future we
45 * might refactor this.
47 * UploadStash represents the entire stash of temporary files.
48 * UploadStashFile is a filestore for the actual physical disk files.
49 * UploadFromStash extends UploadBase, and represents a single stashed file as
50 * it is moved from the stash to the regular file repository
55 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
56 const KEY_FORMAT_REGEX
= '/^[\w-\.]+\.\w*$/';
57 const MAX_US_PROPS_SIZE
= 65535;
60 * repository that this uses to store temp files
61 * public because we sometimes need to get a LocalFile within the same repo.
67 // array of initialized repo objects
68 protected $files = [];
70 // cache of the file metadata that's stored in the database
71 protected $fileMetadata = [];
74 protected $fileProps = [];
77 protected $user, $userId, $isLoggedIn;
80 * Represents a temporary filestore, with metadata in the database.
81 * Designed to be compatible with the session stashing code in UploadBase
82 * (should replace it eventually).
84 * @param FileRepo $repo
85 * @param User $user (default null)
87 public function __construct( FileRepo
$repo, $user = null ) {
88 // this might change based on wiki's configuration.
91 // if a user was passed, use it. otherwise, attempt to use the global.
92 // this keeps FileRepo from breaking when it creates an UploadStash object
97 $this->user
= $wgUser;
100 if ( is_object( $this->user
) ) {
101 $this->userId
= $this->user
->getId();
102 $this->isLoggedIn
= $this->user
->isLoggedIn();
107 * Get a file and its metadata from the stash.
108 * The noAuth param is a bit janky but is required for automated scripts
109 * which clean out the stash.
111 * @param string $key Key under which file information is stored
112 * @param bool $noAuth (optional) Don't check authentication. Used by maintenance scripts.
113 * @throws UploadStashFileNotFoundException
114 * @throws UploadStashNotLoggedInException
115 * @throws UploadStashWrongOwnerException
116 * @throws UploadStashBadPathException
117 * @return UploadStashFile
119 public function getFile( $key, $noAuth = false ) {
120 if ( !preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
121 throw new UploadStashBadPathException(
122 wfMessage( 'uploadstash-bad-path-bad-format', $key )
126 if ( !$noAuth && !$this->isLoggedIn
) {
127 throw new UploadStashNotLoggedInException(
128 wfMessage( 'uploadstash-not-logged-in' )
132 if ( !isset( $this->fileMetadata
[$key] ) ) {
133 if ( !$this->fetchFileMetadata( $key ) ) {
134 // If nothing was received, it's likely due to replication lag.
135 // Check the master to see if the record is there.
136 $this->fetchFileMetadata( $key, DB_MASTER
);
139 if ( !isset( $this->fileMetadata
[$key] ) ) {
140 throw new UploadStashFileNotFoundException(
141 wfMessage( 'uploadstash-file-not-found', $key )
145 // create $this->files[$key]
146 $this->initFile( $key );
149 if ( strlen( $this->fileMetadata
[$key]['us_props'] ) ) {
150 $this->fileProps
[$key] = unserialize( $this->fileMetadata
[$key]['us_props'] );
151 } else { // b/c for rows with no us_props
152 wfDebug( __METHOD__
. " fetched props for $key from file\n" );
153 $path = $this->fileMetadata
[$key]['us_path'];
154 $this->fileProps
[$key] = $this->repo
->getFileProps( $path );
158 if ( !$this->files
[$key]->exists() ) {
159 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
160 // @todo Is this not an UploadStashFileNotFoundException case?
161 throw new UploadStashBadPathException(
162 wfMessage( 'uploadstash-bad-path' )
167 if ( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
168 throw new UploadStashWrongOwnerException(
169 wfMessage( 'uploadstash-wrong-owner', $key )
174 return $this->files
[$key];
178 * Getter for file metadata.
180 * @param string $key Key under which file information is stored
183 public function getMetadata( $key ) {
184 $this->getFile( $key );
186 return $this->fileMetadata
[$key];
190 * Getter for fileProps
192 * @param string $key Key under which file information is stored
195 public function getFileProps( $key ) {
196 $this->getFile( $key );
198 return $this->fileProps
[$key];
202 * Stash a file in a temp directory and record that we did this in the
203 * database, along with other metadata.
205 * @param string $path Path to file you want stashed
206 * @param string $sourceType The type of upload that generated this file
207 * (currently, I believe, 'file' or null)
208 * @throws UploadStashBadPathException
209 * @throws UploadStashFileException
210 * @throws UploadStashNotLoggedInException
211 * @return UploadStashFile|null File, or null on failure
213 public function stashFile( $path, $sourceType = null ) {
214 if ( !is_file( $path ) ) {
215 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
216 throw new UploadStashBadPathException(
217 wfMessage( 'uploadstash-bad-path' )
221 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer() );
222 $fileProps = $mwProps->getPropsFromPath( $path, true );
223 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
225 // we will be initializing from some tmpnam files that don't have extensions.
226 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
227 $extension = self
::getExtensionForPath( $path );
228 if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
229 $pathWithGoodExtension = "$path.$extension";
231 $pathWithGoodExtension = $path;
234 // If no key was supplied, make one. a mysql insertid would be totally
235 // reasonable here, except that for historical reasons, the key is this
236 // random thing instead. At least it's not guessable.
237 // Some things that when combined will make a suitably unique key.
238 // see: http://www.jwz.org/doc/mid.html
239 list( $usec, $sec ) = explode( ' ', microtime() );
240 $usec = substr( $usec, 2 );
241 $key = Wikimedia\base_convert
( $sec . $usec, 10, 36 ) . '.' .
242 Wikimedia\base_convert
( mt_rand(), 10, 36 ) . '.' .
243 $this->userId
. '.' .
246 $this->fileProps
[$key] = $fileProps;
248 if ( !preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
249 throw new UploadStashBadPathException(
250 wfMessage( 'uploadstash-bad-path-bad-format', $key )
254 wfDebug( __METHOD__
. " key for '$path': $key\n" );
256 // if not already in a temporary area, put it there
257 $storeStatus = $this->repo
->storeTemp( basename( $pathWithGoodExtension ), $path );
259 if ( !$storeStatus->isOK() ) {
260 // It is a convention in MediaWiki to only return one error per API
261 // exception, even if multiple errors are available. We use reset()
262 // to pick the "first" thing that was wrong, preferring errors to
263 // warnings. This is a bit lame, as we may have more info in the
264 // $storeStatus and we're throwing it away, but to fix it means
265 // redesigning API errors significantly.
266 // $storeStatus->value just contains the virtual URL (if anything)
267 // which is probably useless to the caller.
268 $error = $storeStatus->getErrorsArray();
269 $error = reset( $error );
270 if ( !count( $error ) ) {
271 $error = $storeStatus->getWarningsArray();
272 $error = reset( $error );
273 if ( !count( $error ) ) {
274 $error = [ 'unknown', 'no error recorded' ];
277 // At this point, $error should contain the single "most important"
278 // error, plus any parameters.
279 $errorMsg = array_shift( $error );
280 throw new UploadStashFileException( wfMessage( $errorMsg, $error ) );
282 $stashPath = $storeStatus->value
;
284 // fetch the current user ID
285 if ( !$this->isLoggedIn
) {
286 throw new UploadStashNotLoggedInException(
287 wfMessage( 'uploadstash-not-logged-in' )
291 // insert the file metadata into the db.
292 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
293 $dbw = $this->repo
->getMasterDB();
295 $serializedFileProps = serialize( $fileProps );
296 if ( strlen( $serializedFileProps ) > self
::MAX_US_PROPS_SIZE
) {
297 // Database is going to truncate this and make the field invalid.
298 // Prioritize important metadata over file handler metadata.
299 // File handler should be prepared to regenerate invalid metadata if needed.
300 $fileProps['metadata'] = false;
301 $serializedFileProps = serialize( $fileProps );
304 $this->fileMetadata
[$key] = [
305 'us_user' => $this->userId
,
307 'us_orig_path' => $path,
308 'us_path' => $stashPath, // virtual URL
309 'us_props' => $dbw->encodeBlob( $serializedFileProps ),
310 'us_size' => $fileProps['size'],
311 'us_sha1' => $fileProps['sha1'],
312 'us_mime' => $fileProps['mime'],
313 'us_media_type' => $fileProps['media_type'],
314 'us_image_width' => $fileProps['width'],
315 'us_image_height' => $fileProps['height'],
316 'us_image_bits' => $fileProps['bits'],
317 'us_source_type' => $sourceType,
318 'us_timestamp' => $dbw->timestamp(),
319 'us_status' => 'finished'
324 $this->fileMetadata
[$key],
328 // store the insertid in the class variable so immediate retrieval
329 // (possibly laggy) isn't necesary.
330 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
332 # create the UploadStashFile object for this file.
333 $this->initFile( $key );
335 return $this->getFile( $key );
339 * Remove all files from the stash.
340 * Does not clean up files in the repo, just the record of them.
342 * @throws UploadStashNotLoggedInException
343 * @return bool Success
345 public function clear() {
346 if ( !$this->isLoggedIn
) {
347 throw new UploadStashNotLoggedInException(
348 wfMessage( 'uploadstash-not-logged-in' )
352 wfDebug( __METHOD__
. ' clearing all rows for user ' . $this->userId
. "\n" );
353 $dbw = $this->repo
->getMasterDB();
356 [ 'us_user' => $this->userId
],
362 $this->fileMetadata
= [];
368 * Remove a particular file from the stash. Also removes it from the repo.
371 * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException
372 * @throws UploadStashWrongOwnerException
373 * @return bool Success
375 public function removeFile( $key ) {
376 if ( !$this->isLoggedIn
) {
377 throw new UploadStashNotLoggedInException(
378 wfMessage( 'uploadstash-not-logged-in' )
382 $dbw = $this->repo
->getMasterDB();
384 // this is a cheap query. it runs on the master so that this function
385 // still works when there's lag. It won't be called all that often.
386 $row = $dbw->selectRow(
389 [ 'us_key' => $key ],
394 throw new UploadStashNoSuchKeyException(
395 wfMessage( 'uploadstash-no-such-key', $key )
399 if ( $row->us_user
!= $this->userId
) {
400 throw new UploadStashWrongOwnerException(
401 wfMessage( 'uploadstash-wrong-owner', $key )
405 return $this->removeFileNoAuth( $key );
409 * Remove a file (see removeFile), but doesn't check ownership first.
412 * @return bool Success
414 public function removeFileNoAuth( $key ) {
415 wfDebug( __METHOD__
. " clearing row $key\n" );
417 // Ensure we have the UploadStashFile loaded for this key
418 $this->getFile( $key, true );
420 $dbw = $this->repo
->getMasterDB();
424 [ 'us_key' => $key ],
428 /** @todo Look into UnregisteredLocalFile and find out why the rv here is
429 * sometimes wrong (false when file was removed). For now, ignore.
431 $this->files
[$key]->remove();
433 unset( $this->files
[$key] );
434 unset( $this->fileMetadata
[$key] );
440 * List all files in the stash.
442 * @throws UploadStashNotLoggedInException
445 public function listFiles() {
446 if ( !$this->isLoggedIn
) {
447 throw new UploadStashNotLoggedInException(
448 wfMessage( 'uploadstash-not-logged-in' )
452 $dbr = $this->repo
->getReplicaDB();
456 [ 'us_user' => $this->userId
],
460 if ( !is_object( $res ) ||
$res->numRows() == 0 ) {
465 // finish the read before starting writes.
467 foreach ( $res as $row ) {
468 array_push( $keys, $row->us_key
);
475 * Find or guess extension -- ensuring that our extension matches our MIME type.
476 * Since these files are constructed from php tempnames they may not start off
478 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
479 * uploads versus the desired filename. Maybe we can get that passed to us...
480 * @param string $path
481 * @throws UploadStashFileException
484 public static function getExtensionForPath( $path ) {
485 global $wgFileBlacklist;
486 // Does this have an extension?
487 $n = strrpos( $path, '.' );
489 if ( $n !== false ) {
490 $extension = $n ?
substr( $path, $n +
1 ) : '';
492 // If not, assume that it should be related to the MIME type of the original file.
493 $magic = MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer();
494 $mimeType = $magic->guessMimeType( $path );
495 $extensions = explode( ' ', $magic->getExtensionsForType( $mimeType ) );
496 if ( count( $extensions ) ) {
497 $extension = $extensions[0];
501 if ( is_null( $extension ) ) {
502 throw new UploadStashFileException(
503 wfMessage( 'uploadstash-no-extension' )
507 $extension = File
::normalizeExtension( $extension );
508 if ( in_array( $extension, $wgFileBlacklist ) ) {
509 // The file should already be checked for being evil.
510 // However, if somehow we got here, we definitely
511 // don't want to give it an extension of .php and
512 // put it in a web accesible directory.
520 * Helper function: do the actual database query to fetch file metadata.
523 * @param int $readFromDB Constant (default: DB_REPLICA)
526 protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA
) {
527 // populate $fileMetadata[$key]
529 if ( $readFromDB === DB_MASTER
) {
530 // sometimes reading from the master is necessary, if there's replication lag.
531 $dbr = $this->repo
->getMasterDB();
533 $dbr = $this->repo
->getReplicaDB();
536 $row = $dbr->selectRow(
539 'us_user', 'us_key', 'us_orig_path', 'us_path', 'us_props',
540 'us_size', 'us_sha1', 'us_mime', 'us_media_type',
541 'us_image_width', 'us_image_height', 'us_image_bits',
542 'us_source_type', 'us_timestamp', 'us_status',
544 [ 'us_key' => $key ],
548 if ( !is_object( $row ) ) {
549 // key wasn't present in the database. this will happen sometimes.
553 $this->fileMetadata
[$key] = (array)$row;
554 $this->fileMetadata
[$key]['us_props'] = $dbr->decodeBlob( $row->us_props
);
560 * Helper function: Initialize the UploadStashFile for a given file.
562 * @param string $key Key under which to store the object
563 * @throws UploadStashZeroLengthFileException
566 protected function initFile( $key ) {
567 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
568 if ( $file->getSize() === 0 ) {
569 throw new UploadStashZeroLengthFileException(
570 wfMessage( 'uploadstash-zero-length' )
573 $this->files
[$key] = $file;
579 class UploadStashFile
extends UnregisteredLocalFile
{
585 * A LocalFile wrapper around a file that has been temporarily stashed,
586 * so we can do things like create thumbnails for it. Arguably
587 * UnregisteredLocalFile should be handling its own file repo but that
588 * class is a bit retarded currently.
590 * @param FileRepo $repo Repository where we should find the path
591 * @param string $path Path to file
592 * @param string $key Key to store the path and any stashed data under
593 * @throws UploadStashBadPathException
594 * @throws UploadStashFileNotFoundException
596 public function __construct( $repo, $path, $key ) {
597 $this->fileKey
= $key;
599 // resolve mwrepo:// urls
600 if ( $repo->isVirtualUrl( $path ) ) {
601 $path = $repo->resolveVirtualUrl( $path );
603 // check if path appears to be sane, no parent traversals,
604 // and is in this repo's temp zone.
605 $repoTempPath = $repo->getZonePath( 'temp' );
606 if ( ( !$repo->validateFilename( $path ) ) ||
607 ( strpos( $path, $repoTempPath ) !== 0 )
609 wfDebug( "UploadStash: tried to construct an UploadStashFile "
610 . "from a file that should already exist at '$path', but path is not valid\n" );
611 throw new UploadStashBadPathException(
612 wfMessage( 'uploadstash-bad-path-invalid' )
616 // check if path exists! and is a plain file.
617 if ( !$repo->fileExists( $path ) ) {
618 wfDebug( "UploadStash: tried to construct an UploadStashFile from "
619 . "a file that should already exist at '$path', but path is not found\n" );
620 throw new UploadStashFileNotFoundException(
621 wfMessage( 'uploadstash-file-not-found-not-exists' )
626 parent
::__construct( false, $repo, $path, false );
628 $this->name
= basename( $this->path
);
632 * A method needed by the file transforming and scaling routines in File.php
633 * We do not necessarily care about doing the description at this point
634 * However, we also can't return the empty string, as the rest of MediaWiki
635 * demands this (and calls to imagemagick convert require it to be there)
637 * @return string Dummy value
639 public function getDescriptionUrl() {
640 return $this->getUrl();
644 * Get the path for the thumbnail (actually any transformation of this file)
645 * The actual argument is the result of thumbName although we seem to have
646 * buggy code elsewhere that expects a boolean 'suffix'
648 * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ),
649 * or false to just get the path
650 * @return string Path thumbnail should take on filesystem, or containing
651 * directory if thumbname is false
653 public function getThumbPath( $thumbName = false ) {
654 $path = dirname( $this->path
);
655 if ( $thumbName !== false ) {
656 $path .= "/$thumbName";
663 * Return the file/url base name of a thumbnail with the specified parameters.
664 * We override this because we want to use the pretty url name instead of the
667 * @param array $params Handler-specific parameters
668 * @param int $flags Bitfield that supports THUMB_* constants
669 * @return string|null Base name for URL, like '120px-12345.jpg', or null if there is no handler
671 function thumbName( $params, $flags = 0 ) {
672 return $this->generateThumbName( $this->getUrlName(), $params );
676 * Helper function -- given a 'subpage', return the local URL,
677 * e.g. /wiki/Special:UploadStash/subpage
678 * @param string $subPage
679 * @return string Local URL for this subpage in the Special:UploadStash space.
681 private function getSpecialUrl( $subPage ) {
682 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
686 * Get a URL to access the thumbnail
687 * This is required because the model of how files work requires that
688 * the thumbnail urls be predictable. However, in our model the URL is
689 * not based on the filename (that's hidden in the db)
691 * @param string $thumbName Basename of thumbnail file -- however, we don't
692 * want to use the file exactly
693 * @return string URL to access thumbnail, or URL with partial path
695 public function getThumbUrl( $thumbName = false ) {
696 wfDebug( __METHOD__
. " getting for $thumbName \n" );
698 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
702 * The basename for the URL, which we want to not be related to the filename.
703 * Will also be used as the lookup key for a thumbnail file.
705 * @return string Base url name, like '120px-123456.jpg'
707 public function getUrlName() {
708 if ( !$this->urlName
) {
709 $this->urlName
= $this->fileKey
;
712 return $this->urlName
;
716 * Return the URL of the file, if for some reason we wanted to download it
717 * We tend not to do this for the original file, but we do want thumb icons
721 public function getUrl() {
722 if ( !isset( $this->url
) ) {
723 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
730 * Parent classes use this method, for no obvious reason, to return the path
731 * (relative to wiki root, I assume). But with this class, the URL is
732 * unrelated to the path.
736 public function getFullUrl() {
737 return $this->getUrl();
741 * Getter for file key (the unique id by which this file's location &
742 * metadata is stored in the db)
744 * @return string File key
746 public function getFileKey() {
747 return $this->fileKey
;
751 * Remove the associated temporary file
752 * @return status Success
754 public function remove() {
755 if ( !$this->repo
->fileExists( $this->path
) ) {
756 // Maybe the file's already been removed? This could totally happen in UploadBase.
760 return $this->repo
->freeTemp( $this->path
);
763 public function exists() {
764 return $this->repo
->fileExists( $this->path
);
768 class UploadStashException
extends MWException
implements ILocalizedException
{
769 /** @var string|array|MessageSpecifier */
770 protected $messageSpec;
773 * @param string|array|MessageSpecifier $messageSpec See Message::newFromSpecifier
774 * @param int $code Exception code
775 * @param Exception|Throwable $previous The previous exception used for the exception chaining.
777 public function __construct( $messageSpec, $code = 0, $previous = null ) {
778 $this->messageSpec
= $messageSpec;
780 $msg = $this->getMessageObject()->text();
781 $msg = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $msg );
782 $msg = Sanitizer
::stripAllTags( $msg );
783 parent
::__construct( $msg, $code, $previous );
786 public function getMessageObject() {
787 return Message
::newFromSpecifier( $this->messageSpec
);
791 class UploadStashFileNotFoundException
extends UploadStashException
{
794 class UploadStashBadPathException
extends UploadStashException
{
797 class UploadStashFileException
extends UploadStashException
{
800 class UploadStashZeroLengthFileException
extends UploadStashException
{
803 class UploadStashNotLoggedInException
extends UploadStashException
{
806 class UploadStashWrongOwnerException
extends UploadStashException
{
809 class UploadStashNoSuchKeyException
extends UploadStashException
{