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
24 * UploadStash is intended to accomplish a few things:
25 * - Enable applications to temporarily stash files without publishing them to
27 * - Several parts of MediaWiki do this in similar ways: UploadBase,
28 * UploadWizard, and FirefoggChunkedExtension.
29 * And there are several that reimplement stashing from scratch, in
30 * idiosyncratic ways. The idea is to unify them all here.
31 * Mostly all of them are the same except for storing some custom fields,
32 * which we subsume into the data array.
33 * - Enable applications to find said files later, as long as the db table or
34 * temp files haven't been purged.
35 * - Enable the uploading user (and *ONLY* the uploading user) to access said
36 * files, and thumbnails of said files, via a URL. We accomplish this using
37 * a database table, with ownership checking as you might expect. See
38 * SpecialUploadStash, which implements a web interface to some files stored
41 * UploadStash right now is *mostly* intended to show you one user's slice of
42 * the entire stash. The user parameter is only optional because there are few
43 * cases where we clean out the stash from an automated script. In the future we
44 * might refactor this.
46 * UploadStash represents the entire stash of temporary files.
47 * UploadStashFile is a filestore for the actual physical disk files.
48 * UploadFromStash extends UploadBase, and represents a single stashed file as
49 * it is moved from the stash to the regular file repository
54 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
55 const KEY_FORMAT_REGEX
= '/^[\w\-\.]+\.\w*$/';
56 const MAX_US_PROPS_SIZE
= 65535;
59 * repository that this uses to store temp files
60 * public because we sometimes need to get a LocalFile within the same repo.
66 // array of initialized repo objects
67 protected $files = [];
69 // cache of the file metadata that's stored in the database
70 protected $fileMetadata = [];
73 protected $fileProps = [];
76 protected $user, $userId, $isLoggedIn;
79 * Represents a temporary filestore, with metadata in the database.
80 * Designed to be compatible with the session stashing code in UploadBase
81 * (should replace it eventually).
83 * @param FileRepo $repo
84 * @param User $user (default null)
86 public function __construct( FileRepo
$repo, $user = null ) {
87 // this might change based on wiki's configuration.
90 // if a user was passed, use it. otherwise, attempt to use the global.
91 // this keeps FileRepo from breaking when it creates an UploadStash object
96 $this->user
= $wgUser;
99 if ( is_object( $this->user
) ) {
100 $this->userId
= $this->user
->getId();
101 $this->isLoggedIn
= $this->user
->isLoggedIn();
106 * Get a file and its metadata from the stash.
107 * The noAuth param is a bit janky but is required for automated scripts
108 * which clean out the stash.
110 * @param string $key Key under which file information is stored
111 * @param bool $noAuth (optional) Don't check authentication. Used by maintenance scripts.
112 * @throws UploadStashFileNotFoundException
113 * @throws UploadStashNotLoggedInException
114 * @throws UploadStashWrongOwnerException
115 * @throws UploadStashBadPathException
116 * @return UploadStashFile
118 public function getFile( $key, $noAuth = false ) {
119 if ( !preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
120 throw new UploadStashBadPathException(
121 wfMessage( 'uploadstash-bad-path-bad-format', $key )
125 if ( !$noAuth && !$this->isLoggedIn
) {
126 throw new UploadStashNotLoggedInException(
127 wfMessage( 'uploadstash-not-logged-in' )
131 if ( !isset( $this->fileMetadata
[$key] ) ) {
132 if ( !$this->fetchFileMetadata( $key ) ) {
133 // If nothing was received, it's likely due to replication lag.
134 // Check the master to see if the record is there.
135 $this->fetchFileMetadata( $key, DB_MASTER
);
138 if ( !isset( $this->fileMetadata
[$key] ) ) {
139 throw new UploadStashFileNotFoundException(
140 wfMessage( 'uploadstash-file-not-found', $key )
144 // create $this->files[$key]
145 $this->initFile( $key );
148 if ( strlen( $this->fileMetadata
[$key]['us_props'] ) ) {
149 $this->fileProps
[$key] = unserialize( $this->fileMetadata
[$key]['us_props'] );
150 } else { // b/c for rows with no us_props
151 wfDebug( __METHOD__
. " fetched props for $key from file\n" );
152 $path = $this->fileMetadata
[$key]['us_path'];
153 $this->fileProps
[$key] = $this->repo
->getFileProps( $path );
157 if ( !$this->files
[$key]->exists() ) {
158 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
159 // @todo Is this not an UploadStashFileNotFoundException case?
160 throw new UploadStashBadPathException(
161 wfMessage( 'uploadstash-bad-path' )
166 if ( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
167 throw new UploadStashWrongOwnerException(
168 wfMessage( 'uploadstash-wrong-owner', $key )
173 return $this->files
[$key];
177 * Getter for file metadata.
179 * @param string $key Key under which file information is stored
182 public function getMetadata( $key ) {
183 $this->getFile( $key );
185 return $this->fileMetadata
[$key];
189 * Getter for fileProps
191 * @param string $key Key under which file information is stored
194 public function getFileProps( $key ) {
195 $this->getFile( $key );
197 return $this->fileProps
[$key];
201 * Stash a file in a temp directory and record that we did this in the
202 * database, along with other metadata.
204 * @param string $path Path to file you want stashed
205 * @param string $sourceType The type of upload that generated this file
206 * (currently, I believe, 'file' or null)
207 * @throws UploadStashBadPathException
208 * @throws UploadStashFileException
209 * @throws UploadStashNotLoggedInException
210 * @return UploadStashFile|null File, or null on failure
212 public function stashFile( $path, $sourceType = null ) {
213 if ( !is_file( $path ) ) {
214 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
215 throw new UploadStashBadPathException(
216 wfMessage( 'uploadstash-bad-path' )
220 $mwProps = new MWFileProps( MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer() );
221 $fileProps = $mwProps->getPropsFromPath( $path, true );
222 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
224 // we will be initializing from some tmpnam files that don't have extensions.
225 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
226 $extension = self
::getExtensionForPath( $path );
227 if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
228 $pathWithGoodExtension = "$path.$extension";
230 $pathWithGoodExtension = $path;
233 // If no key was supplied, make one. a mysql insertid would be totally
234 // reasonable here, except that for historical reasons, the key is this
235 // random thing instead. At least it's not guessable.
236 // Some things that when combined will make a suitably unique key.
237 // see: http://www.jwz.org/doc/mid.html
238 list( $usec, $sec ) = explode( ' ', microtime() );
239 $usec = substr( $usec, 2 );
240 $key = Wikimedia\base_convert
( $sec . $usec, 10, 36 ) . '.' .
241 Wikimedia\base_convert
( mt_rand(), 10, 36 ) . '.' .
242 $this->userId
. '.' .
245 $this->fileProps
[$key] = $fileProps;
247 if ( !preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
248 throw new UploadStashBadPathException(
249 wfMessage( 'uploadstash-bad-path-bad-format', $key )
253 wfDebug( __METHOD__
. " key for '$path': $key\n" );
255 // if not already in a temporary area, put it there
256 $storeStatus = $this->repo
->storeTemp( basename( $pathWithGoodExtension ), $path );
258 if ( !$storeStatus->isOK() ) {
259 // It is a convention in MediaWiki to only return one error per API
260 // exception, even if multiple errors are available. We use reset()
261 // to pick the "first" thing that was wrong, preferring errors to
262 // warnings. This is a bit lame, as we may have more info in the
263 // $storeStatus and we're throwing it away, but to fix it means
264 // redesigning API errors significantly.
265 // $storeStatus->value just contains the virtual URL (if anything)
266 // which is probably useless to the caller.
267 $error = $storeStatus->getErrorsArray();
268 $error = reset( $error );
269 if ( !count( $error ) ) {
270 $error = $storeStatus->getWarningsArray();
271 $error = reset( $error );
272 if ( !count( $error ) ) {
273 $error = [ 'unknown', 'no error recorded' ];
276 // At this point, $error should contain the single "most important"
277 // error, plus any parameters.
278 $errorMsg = array_shift( $error );
279 throw new UploadStashFileException( wfMessage( $errorMsg, $error ) );
281 $stashPath = $storeStatus->value
;
283 // fetch the current user ID
284 if ( !$this->isLoggedIn
) {
285 throw new UploadStashNotLoggedInException(
286 wfMessage( 'uploadstash-not-logged-in' )
290 // insert the file metadata into the db.
291 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
292 $dbw = $this->repo
->getMasterDB();
294 $serializedFileProps = serialize( $fileProps );
295 if ( strlen( $serializedFileProps ) > self
::MAX_US_PROPS_SIZE
) {
296 // Database is going to truncate this and make the field invalid.
297 // Prioritize important metadata over file handler metadata.
298 // File handler should be prepared to regenerate invalid metadata if needed.
299 $fileProps['metadata'] = false;
300 $serializedFileProps = serialize( $fileProps );
303 $this->fileMetadata
[$key] = [
304 'us_user' => $this->userId
,
306 'us_orig_path' => $path,
307 'us_path' => $stashPath, // virtual URL
308 'us_props' => $dbw->encodeBlob( $serializedFileProps ),
309 'us_size' => $fileProps['size'],
310 'us_sha1' => $fileProps['sha1'],
311 'us_mime' => $fileProps['mime'],
312 'us_media_type' => $fileProps['media_type'],
313 'us_image_width' => $fileProps['width'],
314 'us_image_height' => $fileProps['height'],
315 'us_image_bits' => $fileProps['bits'],
316 'us_source_type' => $sourceType,
317 'us_timestamp' => $dbw->timestamp(),
318 'us_status' => 'finished'
323 $this->fileMetadata
[$key],
327 // store the insertid in the class variable so immediate retrieval
328 // (possibly laggy) isn't necesary.
329 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
331 # create the UploadStashFile object for this file.
332 $this->initFile( $key );
334 return $this->getFile( $key );
338 * Remove all files from the stash.
339 * Does not clean up files in the repo, just the record of them.
341 * @throws UploadStashNotLoggedInException
342 * @return bool Success
344 public function clear() {
345 if ( !$this->isLoggedIn
) {
346 throw new UploadStashNotLoggedInException(
347 wfMessage( 'uploadstash-not-logged-in' )
351 wfDebug( __METHOD__
. ' clearing all rows for user ' . $this->userId
. "\n" );
352 $dbw = $this->repo
->getMasterDB();
355 [ 'us_user' => $this->userId
],
361 $this->fileMetadata
= [];
367 * Remove a particular file from the stash. Also removes it from the repo.
370 * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException
371 * @throws UploadStashWrongOwnerException
372 * @return bool Success
374 public function removeFile( $key ) {
375 if ( !$this->isLoggedIn
) {
376 throw new UploadStashNotLoggedInException(
377 wfMessage( 'uploadstash-not-logged-in' )
381 $dbw = $this->repo
->getMasterDB();
383 // this is a cheap query. it runs on the master so that this function
384 // still works when there's lag. It won't be called all that often.
385 $row = $dbw->selectRow(
388 [ 'us_key' => $key ],
393 throw new UploadStashNoSuchKeyException(
394 wfMessage( 'uploadstash-no-such-key', $key )
398 if ( $row->us_user
!= $this->userId
) {
399 throw new UploadStashWrongOwnerException(
400 wfMessage( 'uploadstash-wrong-owner', $key )
404 return $this->removeFileNoAuth( $key );
408 * Remove a file (see removeFile), but doesn't check ownership first.
411 * @return bool Success
413 public function removeFileNoAuth( $key ) {
414 wfDebug( __METHOD__
. " clearing row $key\n" );
416 // Ensure we have the UploadStashFile loaded for this key
417 $this->getFile( $key, true );
419 $dbw = $this->repo
->getMasterDB();
423 [ 'us_key' => $key ],
427 /** @todo Look into UnregisteredLocalFile and find out why the rv here is
428 * sometimes wrong (false when file was removed). For now, ignore.
430 $this->files
[$key]->remove();
432 unset( $this->files
[$key] );
433 unset( $this->fileMetadata
[$key] );
439 * List all files in the stash.
441 * @throws UploadStashNotLoggedInException
444 public function listFiles() {
445 if ( !$this->isLoggedIn
) {
446 throw new UploadStashNotLoggedInException(
447 wfMessage( 'uploadstash-not-logged-in' )
451 $dbr = $this->repo
->getReplicaDB();
455 [ 'us_user' => $this->userId
],
459 if ( !is_object( $res ) ||
$res->numRows() == 0 ) {
464 // finish the read before starting writes.
466 foreach ( $res as $row ) {
467 array_push( $keys, $row->us_key
);
474 * Find or guess extension -- ensuring that our extension matches our MIME type.
475 * Since these files are constructed from php tempnames they may not start off
477 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
478 * uploads versus the desired filename. Maybe we can get that passed to us...
479 * @param string $path
480 * @throws UploadStashFileException
483 public static function getExtensionForPath( $path ) {
484 global $wgFileBlacklist;
485 // Does this have an extension?
486 $n = strrpos( $path, '.' );
488 if ( $n !== false ) {
489 $extension = $n ?
substr( $path, $n +
1 ) : '';
491 // If not, assume that it should be related to the MIME type of the original file.
492 $magic = MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer();
493 $mimeType = $magic->guessMimeType( $path );
494 $extensions = explode( ' ', $magic->getExtensionsForType( $mimeType ) );
495 if ( count( $extensions ) ) {
496 $extension = $extensions[0];
500 if ( is_null( $extension ) ) {
501 throw new UploadStashFileException(
502 wfMessage( 'uploadstash-no-extension' )
506 $extension = File
::normalizeExtension( $extension );
507 if ( in_array( $extension, $wgFileBlacklist ) ) {
508 // The file should already be checked for being evil.
509 // However, if somehow we got here, we definitely
510 // don't want to give it an extension of .php and
511 // put it in a web accesible directory.
519 * Helper function: do the actual database query to fetch file metadata.
522 * @param int $readFromDB Constant (default: DB_REPLICA)
525 protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA
) {
526 // populate $fileMetadata[$key]
528 if ( $readFromDB === DB_MASTER
) {
529 // sometimes reading from the master is necessary, if there's replication lag.
530 $dbr = $this->repo
->getMasterDB();
532 $dbr = $this->repo
->getReplicaDB();
535 $row = $dbr->selectRow(
538 'us_user', 'us_key', 'us_orig_path', 'us_path', 'us_props',
539 'us_size', 'us_sha1', 'us_mime', 'us_media_type',
540 'us_image_width', 'us_image_height', 'us_image_bits',
541 'us_source_type', 'us_timestamp', 'us_status',
543 [ 'us_key' => $key ],
547 if ( !is_object( $row ) ) {
548 // key wasn't present in the database. this will happen sometimes.
552 $this->fileMetadata
[$key] = (array)$row;
553 $this->fileMetadata
[$key]['us_props'] = $dbr->decodeBlob( $row->us_props
);
559 * Helper function: Initialize the UploadStashFile for a given file.
561 * @param string $key Key under which to store the object
562 * @throws UploadStashZeroLengthFileException
565 protected function initFile( $key ) {
566 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
567 if ( $file->getSize() === 0 ) {
568 throw new UploadStashZeroLengthFileException(
569 wfMessage( 'uploadstash-zero-length' )
572 $this->files
[$key] = $file;
581 class UploadStashFile
extends UnregisteredLocalFile
{
587 * A LocalFile wrapper around a file that has been temporarily stashed,
588 * so we can do things like create thumbnails for it. Arguably
589 * UnregisteredLocalFile should be handling its own file repo but that
590 * class is a bit retarded currently.
592 * @param FileRepo $repo Repository where we should find the path
593 * @param string $path Path to file
594 * @param string $key Key to store the path and any stashed data under
595 * @throws UploadStashBadPathException
596 * @throws UploadStashFileNotFoundException
598 public function __construct( $repo, $path, $key ) {
599 $this->fileKey
= $key;
601 // resolve mwrepo:// urls
602 if ( $repo->isVirtualUrl( $path ) ) {
603 $path = $repo->resolveVirtualUrl( $path );
605 // check if path appears to be sane, no parent traversals,
606 // and is in this repo's temp zone.
607 $repoTempPath = $repo->getZonePath( 'temp' );
608 if ( ( !$repo->validateFilename( $path ) ) ||
609 ( strpos( $path, $repoTempPath ) !== 0 )
611 wfDebug( "UploadStash: tried to construct an UploadStashFile "
612 . "from a file that should already exist at '$path', but path is not valid\n" );
613 throw new UploadStashBadPathException(
614 wfMessage( 'uploadstash-bad-path-invalid' )
618 // check if path exists! and is a plain file.
619 if ( !$repo->fileExists( $path ) ) {
620 wfDebug( "UploadStash: tried to construct an UploadStashFile from "
621 . "a file that should already exist at '$path', but path is not found\n" );
622 throw new UploadStashFileNotFoundException(
623 wfMessage( 'uploadstash-file-not-found-not-exists' )
628 parent
::__construct( false, $repo, $path, false );
630 $this->name
= basename( $this->path
);
634 * A method needed by the file transforming and scaling routines in File.php
635 * We do not necessarily care about doing the description at this point
636 * However, we also can't return the empty string, as the rest of MediaWiki
637 * demands this (and calls to imagemagick convert require it to be there)
639 * @return string Dummy value
641 public function getDescriptionUrl() {
642 return $this->getUrl();
646 * Get the path for the thumbnail (actually any transformation of this file)
647 * The actual argument is the result of thumbName although we seem to have
648 * buggy code elsewhere that expects a boolean 'suffix'
650 * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ),
651 * or false to just get the path
652 * @return string Path thumbnail should take on filesystem, or containing
653 * directory if thumbname is false
655 public function getThumbPath( $thumbName = false ) {
656 $path = dirname( $this->path
);
657 if ( $thumbName !== false ) {
658 $path .= "/$thumbName";
665 * Return the file/url base name of a thumbnail with the specified parameters.
666 * We override this because we want to use the pretty url name instead of the
669 * @param array $params Handler-specific parameters
670 * @param int $flags Bitfield that supports THUMB_* constants
671 * @return string|null Base name for URL, like '120px-12345.jpg', or null if there is no handler
673 function thumbName( $params, $flags = 0 ) {
674 return $this->generateThumbName( $this->getUrlName(), $params );
678 * Helper function -- given a 'subpage', return the local URL,
679 * e.g. /wiki/Special:UploadStash/subpage
680 * @param string $subPage
681 * @return string Local URL for this subpage in the Special:UploadStash space.
683 private function getSpecialUrl( $subPage ) {
684 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
688 * Get a URL to access the thumbnail
689 * This is required because the model of how files work requires that
690 * the thumbnail urls be predictable. However, in our model the URL is
691 * not based on the filename (that's hidden in the db)
693 * @param string $thumbName Basename of thumbnail file -- however, we don't
694 * want to use the file exactly
695 * @return string URL to access thumbnail, or URL with partial path
697 public function getThumbUrl( $thumbName = false ) {
698 wfDebug( __METHOD__
. " getting for $thumbName \n" );
700 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
704 * The basename for the URL, which we want to not be related to the filename.
705 * Will also be used as the lookup key for a thumbnail file.
707 * @return string Base url name, like '120px-123456.jpg'
709 public function getUrlName() {
710 if ( !$this->urlName
) {
711 $this->urlName
= $this->fileKey
;
714 return $this->urlName
;
718 * Return the URL of the file, if for some reason we wanted to download it
719 * We tend not to do this for the original file, but we do want thumb icons
723 public function getUrl() {
724 if ( !isset( $this->url
) ) {
725 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
732 * Parent classes use this method, for no obvious reason, to return the path
733 * (relative to wiki root, I assume). But with this class, the URL is
734 * unrelated to the path.
738 public function getFullUrl() {
739 return $this->getUrl();
743 * Getter for file key (the unique id by which this file's location &
744 * metadata is stored in the db)
746 * @return string File key
748 public function getFileKey() {
749 return $this->fileKey
;
753 * Remove the associated temporary file
754 * @return status Success
756 public function remove() {
757 if ( !$this->repo
->fileExists( $this->path
) ) {
758 // Maybe the file's already been removed? This could totally happen in UploadBase.
762 return $this->repo
->freeTemp( $this->path
);
765 public function exists() {
766 return $this->repo
->fileExists( $this->path
);
773 class UploadStashException
extends MWException
implements ILocalizedException
{
774 /** @var string|array|MessageSpecifier */
775 protected $messageSpec;
778 * @param string|array|MessageSpecifier $messageSpec See Message::newFromSpecifier
779 * @param int $code Exception code
780 * @param Exception|Throwable $previous The previous exception used for the exception chaining.
782 public function __construct( $messageSpec, $code = 0, $previous = null ) {
783 $this->messageSpec
= $messageSpec;
785 $msg = $this->getMessageObject()->text();
786 $msg = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $msg );
787 $msg = Sanitizer
::stripAllTags( $msg );
788 parent
::__construct( $msg, $code, $previous );
791 public function getMessageObject() {
792 return Message
::newFromSpecifier( $this->messageSpec
);
799 class UploadStashFileNotFoundException
extends UploadStashException
{
805 class UploadStashBadPathException
extends UploadStashException
{
811 class UploadStashFileException
extends UploadStashException
{
817 class UploadStashZeroLengthFileException
extends UploadStashException
{
823 class UploadStashNotLoggedInException
extends UploadStashException
{
829 class UploadStashWrongOwnerException
extends UploadStashException
{
835 class UploadStashNoSuchKeyException
extends UploadStashException
{