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 the wiki.
27 * - Several parts of MediaWiki do this in similar ways: UploadBase, UploadWizard, and FirefoggChunkedExtension
28 * And there are several that reimplement stashing from scratch, in idiosyncratic ways. The idea is to unify them all here.
29 * Mostly all of them are the same except for storing some custom fields, which we subsume into the data array.
30 * - enable applications to find said files later, as long as the db table or temp files haven't been purged.
31 * - enable the uploading user (and *ONLY* the uploading user) to access said files, and thumbnails of said files, via a URL.
32 * We accomplish this using a database table, with ownership checking as you might expect. See SpecialUploadStash, which
33 * implements a web interface to some files stored this way.
35 * UploadStash right now is *mostly* intended to show you one user's slice of the entire stash. The user parameter is only optional
36 * because there are few cases where we clean out the stash from an automated script. In the future we might refactor this.
38 * UploadStash represents the entire stash of temporary files.
39 * UploadStashFile is a filestore for the actual physical disk files.
40 * UploadFromStash extends UploadBase, and represents a single stashed file as it is moved from the stash to the regular file repository
45 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
46 const KEY_FORMAT_REGEX
= '/^[\w-\.]+\.\w*$/';
49 * repository that this uses to store temp files
50 * public because we sometimes need to get a LocalFile within the same repo.
56 // array of initialized repo objects
57 protected $files = array();
59 // cache of the file metadata that's stored in the database
60 protected $fileMetadata = array();
63 protected $fileProps = array();
66 protected $user, $userId, $isLoggedIn;
69 * Represents a temporary filestore, with metadata in the database.
70 * Designed to be compatible with the session stashing code in UploadBase
71 * (should replace it eventually).
73 * @param FileRepo $repo
74 * @param User $user (default null)
76 public function __construct( FileRepo
$repo, $user = null ) {
77 // this might change based on wiki's configuration.
80 // if a user was passed, use it. otherwise, attempt to use the global.
81 // this keeps FileRepo from breaking when it creates an UploadStash object
86 $this->user
= $wgUser;
89 if ( is_object( $this->user
) ) {
90 $this->userId
= $this->user
->getId();
91 $this->isLoggedIn
= $this->user
->isLoggedIn();
96 * Get a file and its metadata from the stash.
97 * The noAuth param is a bit janky but is required for automated scripts which clean out the stash.
99 * @param string $key Key under which file information is stored
100 * @param bool $noAuth (optional) Don't check authentication. Used by maintenance scripts.
101 * @throws UploadStashFileNotFoundException
102 * @throws UploadStashNotLoggedInException
103 * @throws UploadStashWrongOwnerException
104 * @throws UploadStashBadPathException
105 * @return UploadStashFile
107 public function getFile( $key, $noAuth = false ) {
108 if ( !preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
109 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
112 if ( !$noAuth && !$this->isLoggedIn
) {
113 throw new UploadStashNotLoggedInException( __METHOD__
.
114 ' No user is logged in, files must belong to users' );
117 if ( !isset( $this->fileMetadata
[$key] ) ) {
118 if ( !$this->fetchFileMetadata( $key ) ) {
119 // If nothing was received, it's likely due to replication lag. Check the master to see if the record is there.
120 $this->fetchFileMetadata( $key, DB_MASTER
);
123 if ( !isset( $this->fileMetadata
[$key] ) ) {
124 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
127 // create $this->files[$key]
128 $this->initFile( $key );
131 if ( strlen( $this->fileMetadata
[$key]['us_props'] ) ) {
132 $this->fileProps
[$key] = unserialize( $this->fileMetadata
[$key]['us_props'] );
133 } else { // b/c for rows with no us_props
134 wfDebug( __METHOD__
. " fetched props for $key from file\n" );
135 $path = $this->fileMetadata
[$key]['us_path'];
136 $this->fileProps
[$key] = $this->repo
->getFileProps( $path );
140 if ( !$this->files
[$key]->exists() ) {
141 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
142 throw new UploadStashBadPathException( "path doesn't exist" );
146 if ( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
147 throw new UploadStashWrongOwnerException( "This file ($key) doesn't belong to the current user." );
151 return $this->files
[$key];
155 * Getter for file metadata.
157 * @param string $key key under which file information is stored
160 public function getMetadata( $key ) {
161 $this->getFile( $key );
163 return $this->fileMetadata
[$key];
167 * Getter for fileProps
169 * @param string $key key under which file information is stored
172 public function getFileProps( $key ) {
173 $this->getFile( $key );
175 return $this->fileProps
[$key];
179 * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
181 * @param string $path Path to file you want stashed
182 * @param string $sourceType The type of upload that generated this file (currently, I believe, 'file' or null)
183 * @throws UploadStashBadPathException
184 * @throws UploadStashFileException
185 * @throws UploadStashNotLoggedInException
186 * @return UploadStashFile|null File, or null on failure
188 public function stashFile( $path, $sourceType = null ) {
189 if ( !is_file( $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 = FSFile
::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";
202 $pathWithGoodExtension = $path;
205 // If no key was supplied, make one. a mysql insertid would be totally reasonable here, except
206 // that for historical reasons, the key is this random thing instead. At least it's not guessable.
208 // some things that when combined will make a suitably unique key.
209 // see: http://www.jwz.org/doc/mid.html
210 list( $usec, $sec ) = explode( ' ', microtime() );
211 $usec = substr( $usec, 2 );
212 $key = wfBaseConvert( $sec . $usec, 10, 36 ) . '.' .
213 wfBaseConvert( mt_rand(), 10, 36 ) . '.' .
214 $this->userId
. '.' .
217 $this->fileProps
[$key] = $fileProps;
219 if ( !preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
220 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
223 wfDebug( __METHOD__
. " key for '$path': $key\n" );
225 // if not already in a temporary area, put it there
226 $storeStatus = $this->repo
->storeTemp( basename( $pathWithGoodExtension ), $path );
228 if ( !$storeStatus->isOK() ) {
229 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
230 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
231 // 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
232 // redesigning API errors significantly.
233 // $storeStatus->value just contains the virtual URL (if anything) which is probably useless to the caller
234 $error = $storeStatus->getErrorsArray();
235 $error = reset( $error );
236 if ( !count( $error ) ) {
237 $error = $storeStatus->getWarningsArray();
238 $error = reset( $error );
239 if ( !count( $error ) ) {
240 $error = array( 'unknown', 'no error recorded' );
243 // at this point, $error should contain the single "most important" error, plus any parameters.
244 $errorMsg = array_shift( $error );
245 throw new UploadStashFileException( "Error storing file in '$path': " . wfMessage( $errorMsg, $error )->text() );
247 $stashPath = $storeStatus->value
;
249 // fetch the current user ID
250 if ( !$this->isLoggedIn
) {
251 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
254 // insert the file metadata into the db.
255 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
256 $dbw = $this->repo
->getMasterDb();
258 $this->fileMetadata
[$key] = array(
259 'us_id' => $dbw->nextSequenceValue( 'uploadstash_us_id_seq' ),
260 'us_user' => $this->userId
,
262 'us_orig_path' => $path,
263 'us_path' => $stashPath, // virtual URL
264 'us_props' => $dbw->encodeBlob( serialize( $fileProps ) ),
265 'us_size' => $fileProps['size'],
266 'us_sha1' => $fileProps['sha1'],
267 'us_mime' => $fileProps['mime'],
268 'us_media_type' => $fileProps['media_type'],
269 'us_image_width' => $fileProps['width'],
270 'us_image_height' => $fileProps['height'],
271 'us_image_bits' => $fileProps['bits'],
272 'us_source_type' => $sourceType,
273 'us_timestamp' => $dbw->timestamp(),
274 'us_status' => 'finished'
279 $this->fileMetadata
[$key],
283 // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
284 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
286 # create the UploadStashFile object for this file.
287 $this->initFile( $key );
289 return $this->getFile( $key );
293 * Remove all files from the stash.
294 * Does not clean up files in the repo, just the record of them.
296 * @throws UploadStashNotLoggedInException
297 * @return bool Success
299 public function clear() {
300 if ( !$this->isLoggedIn
) {
301 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
304 wfDebug( __METHOD__
. ' clearing all rows for user ' . $this->userId
. "\n" );
305 $dbw = $this->repo
->getMasterDb();
308 array( 'us_user' => $this->userId
),
313 $this->files
= array();
314 $this->fileMetadata
= array();
320 * Remove a particular file from the stash. Also removes it from the repo.
323 * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException|UploadStashWrongOwnerException
324 * @return bool Success
326 public function removeFile( $key ) {
327 if ( !$this->isLoggedIn
) {
328 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
331 $dbw = $this->repo
->getMasterDb();
333 // this is a cheap query. it runs on the master so that this function still works when there's lag.
334 // it won't be called all that often.
335 $row = $dbw->selectRow(
338 array( 'us_key' => $key ),
343 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
346 if ( $row->us_user
!= $this->userId
) {
347 throw new UploadStashWrongOwnerException( "Can't delete: the file ($key) doesn't belong to this user." );
350 return $this->removeFileNoAuth( $key );
354 * Remove a file (see removeFile), but doesn't check ownership first.
357 * @return bool Success
359 public function removeFileNoAuth( $key ) {
360 wfDebug( __METHOD__
. " clearing row $key\n" );
362 // Ensure we have the UploadStashFile loaded for this key
363 $this->getFile( $key, true );
365 $dbw = $this->repo
->getMasterDb();
369 array( 'us_key' => $key ),
373 // TODO: look into UnregisteredLocalFile and find out why the rv here is sometimes wrong (false when file was removed)
375 $this->files
[$key]->remove();
377 unset( $this->files
[$key] );
378 unset( $this->fileMetadata
[$key] );
384 * List all files in the stash.
386 * @throws UploadStashNotLoggedInException
389 public function listFiles() {
390 if ( !$this->isLoggedIn
) {
391 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
394 $dbr = $this->repo
->getSlaveDb();
398 array( 'us_user' => $this->userId
),
402 if ( !is_object( $res ) ||
$res->numRows() == 0 ) {
407 // finish the read before starting writes.
409 foreach ( $res as $row ) {
410 array_push( $keys, $row->us_key
);
417 * Find or guess extension -- ensuring that our extension matches our mime type.
418 * Since these files are constructed from php tempnames they may not start off
420 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
421 * uploads versus the desired filename. Maybe we can get that passed to us...
422 * @param string $path
423 * @throws UploadStashFileException
426 public static function getExtensionForPath( $path ) {
427 global $wgFileBlacklist;
428 // Does this have an extension?
429 $n = strrpos( $path, '.' );
431 if ( $n !== false ) {
432 $extension = $n ?
substr( $path, $n +
1 ) : '';
434 // If not, assume that it should be related to the mime type of the original file.
435 $magic = MimeMagic
::singleton();
436 $mimeType = $magic->guessMimeType( $path );
437 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
438 if ( count( $extensions ) ) {
439 $extension = $extensions[0];
443 if ( is_null( $extension ) ) {
444 throw new UploadStashFileException( "extension is null" );
447 $extension = File
::normalizeExtension( $extension );
448 if ( in_array( $extension, $wgFileBlacklist ) ) {
449 // The file should already be checked for being evil.
450 // However, if somehow we got here, we definitely
451 // don't want to give it an extension of .php and
452 // put it in a web accesible directory.
460 * Helper function: do the actual database query to fetch file metadata.
463 * @param int $readFromDB Constant (default: DB_SLAVE)
466 protected function fetchFileMetadata( $key, $readFromDB = DB_SLAVE
) {
467 // populate $fileMetadata[$key]
469 if ( $readFromDB === DB_MASTER
) {
470 // sometimes reading from the master is necessary, if there's replication lag.
471 $dbr = $this->repo
->getMasterDb();
473 $dbr = $this->repo
->getSlaveDb();
476 $row = $dbr->selectRow(
479 array( 'us_key' => $key ),
483 if ( !is_object( $row ) ) {
484 // key wasn't present in the database. this will happen sometimes.
488 $this->fileMetadata
[$key] = (array)$row;
489 $this->fileMetadata
[$key]['us_props'] = $dbr->decodeBlob( $row->us_props
);
495 * Helper function: Initialize the UploadStashFile for a given file.
497 * @param string $key key under which to store the object
498 * @throws UploadStashZeroLengthFileException
501 protected function initFile( $key ) {
502 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
503 if ( $file->getSize() === 0 ) {
504 throw new UploadStashZeroLengthFileException( "File is zero length" );
506 $this->files
[$key] = $file;
512 class UploadStashFile
extends UnregisteredLocalFile
{
518 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
519 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
521 * @param FileRepo $repo Repository where we should find the path
522 * @param string $path Path to file
523 * @param string $key Key to store the path and any stashed data under
524 * @throws UploadStashBadPathException
525 * @throws UploadStashFileNotFoundException
527 public function __construct( $repo, $path, $key ) {
528 $this->fileKey
= $key;
530 // resolve mwrepo:// urls
531 if ( $repo->isVirtualUrl( $path ) ) {
532 $path = $repo->resolveVirtualUrl( $path );
534 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
535 $repoTempPath = $repo->getZonePath( 'temp' );
536 if ( ( !$repo->validateFilename( $path ) ) ||
537 ( strpos( $path, $repoTempPath ) !== 0 )
539 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
540 throw new UploadStashBadPathException( 'path is not valid' );
543 // check if path exists! and is a plain file.
544 if ( !$repo->fileExists( $path ) ) {
545 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
546 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
550 parent
::__construct( false, $repo, $path, false );
552 $this->name
= basename( $this->path
);
556 * A method needed by the file transforming and scaling routines in File.php
557 * We do not necessarily care about doing the description at this point
558 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
559 * convert require it to be there)
561 * @return string Dummy value
563 public function getDescriptionUrl() {
564 return $this->getUrl();
568 * Get the path for the thumbnail (actually any transformation of this file)
569 * The actual argument is the result of thumbName although we seem to have
570 * buggy code elsewhere that expects a boolean 'suffix'
572 * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
573 * @return string Path thumbnail should take on filesystem, or containing directory if thumbname is false
575 public function getThumbPath( $thumbName = false ) {
576 $path = dirname( $this->path
);
577 if ( $thumbName !== false ) {
578 $path .= "/$thumbName";
585 * Return the file/url base name of a thumbnail with the specified parameters.
586 * We override this because we want to use the pretty url name instead of the
589 * @param array $params Handler-specific parameters
590 * @param int $flags Bitfield that supports THUMB_* constants
591 * @return string Base name for URL, like '120px-12345.jpg', or null if there is no handler
593 function thumbName( $params, $flags = 0 ) {
594 return $this->generateThumbName( $this->getUrlName(), $params );
598 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
599 * @param string $subPage
600 * @return string Local URL for this subpage in the Special:UploadStash space.
602 private function getSpecialUrl( $subPage ) {
603 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
607 * Get a URL to access the thumbnail
608 * This is required because the model of how files work requires that
609 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
610 * (that's hidden in the db)
612 * @param string $thumbName Basename of thumbnail file -- however, we don't want to use the file exactly
613 * @return string URL to access thumbnail, or URL with partial path
615 public function getThumbUrl( $thumbName = false ) {
616 wfDebug( __METHOD__
. " getting for $thumbName \n" );
618 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
622 * The basename for the URL, which we want to not be related to the filename.
623 * Will also be used as the lookup key for a thumbnail file.
625 * @return string Base url name, like '120px-123456.jpg'
627 public function getUrlName() {
628 if ( !$this->urlName
) {
629 $this->urlName
= $this->fileKey
;
632 return $this->urlName
;
636 * Return the URL of the file, if for some reason we wanted to download it
637 * We tend not to do this for the original file, but we do want thumb icons
641 public function getUrl() {
642 if ( !isset( $this->url
) ) {
643 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
650 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
651 * But with this class, the URL is unrelated to the path.
655 public function getFullUrl() {
656 return $this->getUrl();
660 * Getter for file key (the unique id by which this file's location & metadata is stored in the db)
662 * @return string File key
664 public function getFileKey() {
665 return $this->fileKey
;
669 * Remove the associated temporary file
670 * @return status Success
672 public function remove() {
673 if ( !$this->repo
->fileExists( $this->path
) ) {
674 // Maybe the file's already been removed? This could totally happen in UploadBase.
678 return $this->repo
->freeTemp( $this->path
);
681 public function exists() {
682 return $this->repo
->fileExists( $this->path
);
686 class UploadStashException
extends MWException
{
689 class UploadStashNotAvailableException
extends UploadStashException
{
692 class UploadStashFileNotFoundException
extends UploadStashException
{
695 class UploadStashBadPathException
extends UploadStashException
{
698 class UploadStashFileException
extends UploadStashException
{
701 class UploadStashZeroLengthFileException
extends UploadStashException
{
704 class UploadStashNotLoggedInException
extends UploadStashException
{
707 class UploadStashWrongOwnerException
extends UploadStashException
{
710 class UploadStashNoSuchKeyException
extends UploadStashException
{