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( "key '$key' is not in a proper format" );
124 if ( !$noAuth && !$this->isLoggedIn
) {
125 throw new UploadStashNotLoggedInException( __METHOD__
.
126 ' No user is logged in, files must belong to users' );
129 if ( !isset( $this->fileMetadata
[$key] ) ) {
130 if ( !$this->fetchFileMetadata( $key ) ) {
131 // If nothing was received, it's likely due to replication lag.
132 // Check the master to see if the record is there.
133 $this->fetchFileMetadata( $key, DB_MASTER
);
136 if ( !isset( $this->fileMetadata
[$key] ) ) {
137 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
140 // create $this->files[$key]
141 $this->initFile( $key );
144 if ( strlen( $this->fileMetadata
[$key]['us_props'] ) ) {
145 $this->fileProps
[$key] = unserialize( $this->fileMetadata
[$key]['us_props'] );
146 } else { // b/c for rows with no us_props
147 wfDebug( __METHOD__
. " fetched props for $key from file\n" );
148 $path = $this->fileMetadata
[$key]['us_path'];
149 $this->fileProps
[$key] = $this->repo
->getFileProps( $path );
153 if ( !$this->files
[$key]->exists() ) {
154 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
155 // @todo Is this not an UploadStashFileNotFoundException case?
156 throw new UploadStashBadPathException( "path doesn't exist" );
160 if ( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
161 throw new UploadStashWrongOwnerException( "This file ($key) doesn't "
162 . "belong to the current user." );
166 return $this->files
[$key];
170 * Getter for file metadata.
172 * @param string $key Key under which file information is stored
175 public function getMetadata( $key ) {
176 $this->getFile( $key );
178 return $this->fileMetadata
[$key];
182 * Getter for fileProps
184 * @param string $key Key under which file information is stored
187 public function getFileProps( $key ) {
188 $this->getFile( $key );
190 return $this->fileProps
[$key];
194 * Stash a file in a temp directory and record that we did this in the
195 * database, along with other metadata.
197 * @param string $path Path to file you want stashed
198 * @param string $sourceType The type of upload that generated this file
199 * (currently, I believe, 'file' or null)
200 * @throws UploadStashBadPathException
201 * @throws UploadStashFileException
202 * @throws UploadStashNotLoggedInException
203 * @return UploadStashFile|null File, or null on failure
205 public function stashFile( $path, $sourceType = null ) {
206 if ( !is_file( $path ) ) {
207 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
208 throw new UploadStashBadPathException( "path doesn't exist" );
210 $fileProps = FSFile
::getPropsFromPath( $path );
211 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
213 // we will be initializing from some tmpnam files that don't have extensions.
214 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
215 $extension = self
::getExtensionForPath( $path );
216 if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
217 $pathWithGoodExtension = "$path.$extension";
219 $pathWithGoodExtension = $path;
222 // If no key was supplied, make one. a mysql insertid would be totally
223 // reasonable here, except that for historical reasons, the key is this
224 // random thing instead. At least it's not guessable.
225 // Some things that when combined will make a suitably unique key.
226 // see: http://www.jwz.org/doc/mid.html
227 list( $usec, $sec ) = explode( ' ', microtime() );
228 $usec = substr( $usec, 2 );
229 $key = Wikimedia\base_convert
( $sec . $usec, 10, 36 ) . '.' .
230 Wikimedia\base_convert
( mt_rand(), 10, 36 ) . '.' .
231 $this->userId
. '.' .
234 $this->fileProps
[$key] = $fileProps;
236 if ( !preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
237 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
240 wfDebug( __METHOD__
. " key for '$path': $key\n" );
242 // if not already in a temporary area, put it there
243 $storeStatus = $this->repo
->storeTemp( basename( $pathWithGoodExtension ), $path );
245 if ( !$storeStatus->isOK() ) {
246 // It is a convention in MediaWiki to only return one error per API
247 // exception, even if multiple errors are available. We use reset()
248 // to pick the "first" thing that was wrong, preferring errors to
249 // warnings. This is a bit lame, as we may have more info in the
250 // $storeStatus and we're throwing it away, but to fix it means
251 // redesigning API errors significantly.
252 // $storeStatus->value just contains the virtual URL (if anything)
253 // which is probably useless to the caller.
254 $error = $storeStatus->getErrorsArray();
255 $error = reset( $error );
256 if ( !count( $error ) ) {
257 $error = $storeStatus->getWarningsArray();
258 $error = reset( $error );
259 if ( !count( $error ) ) {
260 $error = [ 'unknown', 'no error recorded' ];
263 // At this point, $error should contain the single "most important"
264 // error, plus any parameters.
265 $errorMsg = array_shift( $error );
266 throw new UploadStashFileException( "Error storing file in '$path': "
267 . wfMessage( $errorMsg, $error )->text() );
269 $stashPath = $storeStatus->value
;
271 // fetch the current user ID
272 if ( !$this->isLoggedIn
) {
273 throw new UploadStashNotLoggedInException( __METHOD__
274 . ' No user is logged in, files must belong to users' );
277 // insert the file metadata into the db.
278 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
279 $dbw = $this->repo
->getMasterDB();
281 $serializedFileProps = serialize( $fileProps );
282 if ( strlen( $serializedFileProps ) > self
::MAX_US_PROPS_SIZE
) {
283 // Database is going to truncate this and make the field invalid.
284 // Prioritize important metadata over file handler metadata.
285 // File handler should be prepared to regenerate invalid metadata if needed.
286 $fileProps['metadata'] = false;
287 $serializedFileProps = serialize( $fileProps );
290 $this->fileMetadata
[$key] = [
291 'us_id' => $dbw->nextSequenceValue( 'uploadstash_us_id_seq' ),
292 'us_user' => $this->userId
,
294 'us_orig_path' => $path,
295 'us_path' => $stashPath, // virtual URL
296 'us_props' => $dbw->encodeBlob( $serializedFileProps ),
297 'us_size' => $fileProps['size'],
298 'us_sha1' => $fileProps['sha1'],
299 'us_mime' => $fileProps['mime'],
300 'us_media_type' => $fileProps['media_type'],
301 'us_image_width' => $fileProps['width'],
302 'us_image_height' => $fileProps['height'],
303 'us_image_bits' => $fileProps['bits'],
304 'us_source_type' => $sourceType,
305 'us_timestamp' => $dbw->timestamp(),
306 'us_status' => 'finished'
311 $this->fileMetadata
[$key],
315 // store the insertid in the class variable so immediate retrieval
316 // (possibly laggy) isn't necesary.
317 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
319 # create the UploadStashFile object for this file.
320 $this->initFile( $key );
322 return $this->getFile( $key );
326 * Remove all files from the stash.
327 * Does not clean up files in the repo, just the record of them.
329 * @throws UploadStashNotLoggedInException
330 * @return bool Success
332 public function clear() {
333 if ( !$this->isLoggedIn
) {
334 throw new UploadStashNotLoggedInException( __METHOD__
335 . ' No user is logged in, files must belong to users' );
338 wfDebug( __METHOD__
. ' clearing all rows for user ' . $this->userId
. "\n" );
339 $dbw = $this->repo
->getMasterDB();
342 [ 'us_user' => $this->userId
],
348 $this->fileMetadata
= [];
354 * Remove a particular file from the stash. Also removes it from the repo.
357 * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException
358 * @throws UploadStashWrongOwnerException
359 * @return bool Success
361 public function removeFile( $key ) {
362 if ( !$this->isLoggedIn
) {
363 throw new UploadStashNotLoggedInException( __METHOD__
364 . ' No user is logged in, files must belong to users' );
367 $dbw = $this->repo
->getMasterDB();
369 // this is a cheap query. it runs on the master so that this function
370 // still works when there's lag. It won't be called all that often.
371 $row = $dbw->selectRow(
374 [ 'us_key' => $key ],
379 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
382 if ( $row->us_user
!= $this->userId
) {
383 throw new UploadStashWrongOwnerException( "Can't delete: "
384 . "the file ($key) doesn't belong to this user." );
387 return $this->removeFileNoAuth( $key );
391 * Remove a file (see removeFile), but doesn't check ownership first.
394 * @return bool Success
396 public function removeFileNoAuth( $key ) {
397 wfDebug( __METHOD__
. " clearing row $key\n" );
399 // Ensure we have the UploadStashFile loaded for this key
400 $this->getFile( $key, true );
402 $dbw = $this->repo
->getMasterDB();
406 [ 'us_key' => $key ],
410 /** @todo Look into UnregisteredLocalFile and find out why the rv here is
411 * sometimes wrong (false when file was removed). For now, ignore.
413 $this->files
[$key]->remove();
415 unset( $this->files
[$key] );
416 unset( $this->fileMetadata
[$key] );
422 * List all files in the stash.
424 * @throws UploadStashNotLoggedInException
427 public function listFiles() {
428 if ( !$this->isLoggedIn
) {
429 throw new UploadStashNotLoggedInException( __METHOD__
430 . ' No user is logged in, files must belong to users' );
433 $dbr = $this->repo
->getSlaveDB();
437 [ 'us_user' => $this->userId
],
441 if ( !is_object( $res ) ||
$res->numRows() == 0 ) {
446 // finish the read before starting writes.
448 foreach ( $res as $row ) {
449 array_push( $keys, $row->us_key
);
456 * Find or guess extension -- ensuring that our extension matches our MIME type.
457 * Since these files are constructed from php tempnames they may not start off
459 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
460 * uploads versus the desired filename. Maybe we can get that passed to us...
461 * @param string $path
462 * @throws UploadStashFileException
465 public static function getExtensionForPath( $path ) {
466 global $wgFileBlacklist;
467 // Does this have an extension?
468 $n = strrpos( $path, '.' );
470 if ( $n !== false ) {
471 $extension = $n ?
substr( $path, $n +
1 ) : '';
473 // If not, assume that it should be related to the MIME type of the original file.
474 $magic = MimeMagic
::singleton();
475 $mimeType = $magic->guessMimeType( $path );
476 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
477 if ( count( $extensions ) ) {
478 $extension = $extensions[0];
482 if ( is_null( $extension ) ) {
483 throw new UploadStashFileException( "extension is null" );
486 $extension = File
::normalizeExtension( $extension );
487 if ( in_array( $extension, $wgFileBlacklist ) ) {
488 // The file should already be checked for being evil.
489 // However, if somehow we got here, we definitely
490 // don't want to give it an extension of .php and
491 // put it in a web accesible directory.
499 * Helper function: do the actual database query to fetch file metadata.
502 * @param int $readFromDB Constant (default: DB_SLAVE)
505 protected function fetchFileMetadata( $key, $readFromDB = DB_SLAVE
) {
506 // populate $fileMetadata[$key]
508 if ( $readFromDB === DB_MASTER
) {
509 // sometimes reading from the master is necessary, if there's replication lag.
510 $dbr = $this->repo
->getMasterDB();
512 $dbr = $this->repo
->getSlaveDB();
515 $row = $dbr->selectRow(
518 [ 'us_key' => $key ],
522 if ( !is_object( $row ) ) {
523 // key wasn't present in the database. this will happen sometimes.
527 $this->fileMetadata
[$key] = (array)$row;
528 $this->fileMetadata
[$key]['us_props'] = $dbr->decodeBlob( $row->us_props
);
534 * Helper function: Initialize the UploadStashFile for a given file.
536 * @param string $key Key under which to store the object
537 * @throws UploadStashZeroLengthFileException
540 protected function initFile( $key ) {
541 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
542 if ( $file->getSize() === 0 ) {
543 throw new UploadStashZeroLengthFileException( "File is zero length" );
545 $this->files
[$key] = $file;
551 class UploadStashFile
extends UnregisteredLocalFile
{
557 * A LocalFile wrapper around a file that has been temporarily stashed,
558 * so we can do things like create thumbnails for it. Arguably
559 * UnregisteredLocalFile should be handling its own file repo but that
560 * class is a bit retarded currently.
562 * @param FileRepo $repo Repository where we should find the path
563 * @param string $path Path to file
564 * @param string $key Key to store the path and any stashed data under
565 * @throws UploadStashBadPathException
566 * @throws UploadStashFileNotFoundException
568 public function __construct( $repo, $path, $key ) {
569 $this->fileKey
= $key;
571 // resolve mwrepo:// urls
572 if ( $repo->isVirtualUrl( $path ) ) {
573 $path = $repo->resolveVirtualUrl( $path );
575 // check if path appears to be sane, no parent traversals,
576 // and is in this repo's temp zone.
577 $repoTempPath = $repo->getZonePath( 'temp' );
578 if ( ( !$repo->validateFilename( $path ) ) ||
579 ( strpos( $path, $repoTempPath ) !== 0 )
581 wfDebug( "UploadStash: tried to construct an UploadStashFile "
582 . "from a file that should already exist at '$path', but path is not valid\n" );
583 throw new UploadStashBadPathException( 'path is not valid' );
586 // check if path exists! and is a plain file.
587 if ( !$repo->fileExists( $path ) ) {
588 wfDebug( "UploadStash: tried to construct an UploadStashFile from "
589 . "a file that should already exist at '$path', but path is not found\n" );
590 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
594 parent
::__construct( false, $repo, $path, false );
596 $this->name
= basename( $this->path
);
600 * A method needed by the file transforming and scaling routines in File.php
601 * We do not necessarily care about doing the description at this point
602 * However, we also can't return the empty string, as the rest of MediaWiki
603 * demands this (and calls to imagemagick convert require it to be there)
605 * @return string Dummy value
607 public function getDescriptionUrl() {
608 return $this->getUrl();
612 * Get the path for the thumbnail (actually any transformation of this file)
613 * The actual argument is the result of thumbName although we seem to have
614 * buggy code elsewhere that expects a boolean 'suffix'
616 * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ),
617 * or false to just get the path
618 * @return string Path thumbnail should take on filesystem, or containing
619 * directory if thumbname is false
621 public function getThumbPath( $thumbName = false ) {
622 $path = dirname( $this->path
);
623 if ( $thumbName !== false ) {
624 $path .= "/$thumbName";
631 * Return the file/url base name of a thumbnail with the specified parameters.
632 * We override this because we want to use the pretty url name instead of the
635 * @param array $params Handler-specific parameters
636 * @param int $flags Bitfield that supports THUMB_* constants
637 * @return string|null Base name for URL, like '120px-12345.jpg', or null if there is no handler
639 function thumbName( $params, $flags = 0 ) {
640 return $this->generateThumbName( $this->getUrlName(), $params );
644 * Helper function -- given a 'subpage', return the local URL,
645 * e.g. /wiki/Special:UploadStash/subpage
646 * @param string $subPage
647 * @return string Local URL for this subpage in the Special:UploadStash space.
649 private function getSpecialUrl( $subPage ) {
650 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
654 * Get a URL to access the thumbnail
655 * This is required because the model of how files work requires that
656 * the thumbnail urls be predictable. However, in our model the URL is
657 * not based on the filename (that's hidden in the db)
659 * @param string $thumbName Basename of thumbnail file -- however, we don't
660 * want to use the file exactly
661 * @return string URL to access thumbnail, or URL with partial path
663 public function getThumbUrl( $thumbName = false ) {
664 wfDebug( __METHOD__
. " getting for $thumbName \n" );
666 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
670 * The basename for the URL, which we want to not be related to the filename.
671 * Will also be used as the lookup key for a thumbnail file.
673 * @return string Base url name, like '120px-123456.jpg'
675 public function getUrlName() {
676 if ( !$this->urlName
) {
677 $this->urlName
= $this->fileKey
;
680 return $this->urlName
;
684 * Return the URL of the file, if for some reason we wanted to download it
685 * We tend not to do this for the original file, but we do want thumb icons
689 public function getUrl() {
690 if ( !isset( $this->url
) ) {
691 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
698 * Parent classes use this method, for no obvious reason, to return the path
699 * (relative to wiki root, I assume). But with this class, the URL is
700 * unrelated to the path.
704 public function getFullUrl() {
705 return $this->getUrl();
709 * Getter for file key (the unique id by which this file's location &
710 * metadata is stored in the db)
712 * @return string File key
714 public function getFileKey() {
715 return $this->fileKey
;
719 * Remove the associated temporary file
720 * @return status Success
722 public function remove() {
723 if ( !$this->repo
->fileExists( $this->path
) ) {
724 // Maybe the file's already been removed? This could totally happen in UploadBase.
728 return $this->repo
->freeTemp( $this->path
);
731 public function exists() {
732 return $this->repo
->fileExists( $this->path
);
736 class UploadStashException
extends MWException
{
739 class UploadStashFileNotFoundException
extends UploadStashException
{
742 class UploadStashBadPathException
extends UploadStashException
{
745 class UploadStashFileException
extends UploadStashException
{
748 class UploadStashZeroLengthFileException
extends UploadStashException
{
751 class UploadStashNotLoggedInException
extends UploadStashException
{
754 class UploadStashWrongOwnerException
extends UploadStashException
{
757 class UploadStashNoSuchKeyException
extends UploadStashException
{