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
46 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
47 const KEY_FORMAT_REGEX
= '/^[\w-\.]+\.\w*$/';
50 * repository that this uses to store temp files
51 * public because we sometimes need to get a LocalFile within the same repo.
57 // array of initialized repo objects
58 protected $files = array();
60 // cache of the file metadata that's stored in the database
61 protected $fileMetadata = array();
64 protected $fileProps = array();
67 protected $user, $userId, $isLoggedIn;
70 * Represents a temporary filestore, with metadata in the database.
71 * Designed to be compatible with the session stashing code in UploadBase
72 * (should replace it eventually).
74 * @param FileRepo $repo
75 * @param User $user (default null)
77 public function __construct( FileRepo
$repo, $user = null ) {
78 // this might change based on wiki's configuration.
81 // if a user was passed, use it. otherwise, attempt to use the global.
82 // this keeps FileRepo from breaking when it creates an UploadStash object
87 $this->user
= $wgUser;
90 if ( is_object( $this->user
) ) {
91 $this->userId
= $this->user
->getId();
92 $this->isLoggedIn
= $this->user
->isLoggedIn();
97 * Get a file and its metadata from the stash.
98 * The noAuth param is a bit janky but is required for automated scripts which clean out the stash.
100 * @param string $key Key under which file information is stored
101 * @param bool $noAuth (optional) Don't check authentication. Used by maintenance scripts.
102 * @throws UploadStashFileNotFoundException
103 * @throws UploadStashNotLoggedInException
104 * @throws UploadStashWrongOwnerException
105 * @throws UploadStashBadPathException
106 * @return UploadStashFile
108 public function getFile( $key, $noAuth = false ) {
109 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
110 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
113 if ( !$noAuth && !$this->isLoggedIn
) {
114 throw new UploadStashNotLoggedInException( __METHOD__
.
115 ' No user is logged in, files must belong to users' );
118 if ( !isset( $this->fileMetadata
[$key] ) ) {
119 if ( !$this->fetchFileMetadata( $key ) ) {
120 // If nothing was received, it's likely due to replication lag. Check the master to see if the record is there.
121 $this->fetchFileMetadata( $key, DB_MASTER
);
124 if ( !isset( $this->fileMetadata
[$key] ) ) {
125 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
128 // create $this->files[$key]
129 $this->initFile( $key );
132 if ( strlen( $this->fileMetadata
[$key]['us_props'] ) ) {
133 $this->fileProps
[$key] = unserialize( $this->fileMetadata
[$key]['us_props'] );
134 } else { // b/c for rows with no us_props
135 wfDebug( __METHOD__
. " fetched props for $key from file\n" );
136 $path = $this->fileMetadata
[$key]['us_path'];
137 $this->fileProps
[$key] = $this->repo
->getFileProps( $path );
141 if ( ! $this->files
[$key]->exists() ) {
142 wfDebug( __METHOD__
. " tried to get file at $key, but it doesn't exist\n" );
143 throw new UploadStashBadPathException( "path doesn't exist" );
147 if ( $this->fileMetadata
[$key]['us_user'] != $this->userId
) {
148 throw new UploadStashWrongOwnerException( "This file ($key) doesn't belong to the current user." );
152 return $this->files
[$key];
156 * Getter for file metadata.
158 * @param string $key key under which file information is stored
161 public function getMetadata( $key ) {
162 $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 );
174 return $this->fileProps
[$key];
178 * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
180 * @param string $path Path to file you want stashed
181 * @param string $sourceType The type of upload that generated this file (currently, I believe, 'file' or null)
182 * @throws UploadStashBadPathException
183 * @throws UploadStashFileException
184 * @throws UploadStashNotLoggedInException
185 * @return UploadStashFile|null File, or null on failure
187 public function stashFile( $path, $sourceType = null ) {
188 if ( !is_file( $path ) ) {
189 wfDebug( __METHOD__
. " tried to stash file at '$path', but it doesn't exist\n" );
190 throw new UploadStashBadPathException( "path doesn't exist" );
192 $fileProps = FSFile
::getPropsFromPath( $path );
193 wfDebug( __METHOD__
. " stashing file at '$path'\n" );
195 // we will be initializing from some tmpnam files that don't have extensions.
196 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
197 $extension = self
::getExtensionForPath( $path );
198 if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
199 $pathWithGoodExtension = "$path.$extension";
201 $pathWithGoodExtension = $path;
204 // If no key was supplied, make one. a mysql insertid would be totally reasonable here, except
205 // that for historical reasons, the key is this random thing instead. At least it's not guessable.
207 // some things that when combined will make a suitably unique key.
208 // see: http://www.jwz.org/doc/mid.html
209 list( $usec, $sec ) = explode( ' ', microtime() );
210 $usec = substr( $usec, 2 );
211 $key = wfBaseConvert( $sec . $usec, 10, 36 ) . '.' .
212 wfBaseConvert( mt_rand(), 10, 36 ) . '.' .
213 $this->userId
. '.' .
216 $this->fileProps
[$key] = $fileProps;
218 if ( ! preg_match( self
::KEY_FORMAT_REGEX
, $key ) ) {
219 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
222 wfDebug( __METHOD__
. " key for '$path': $key\n" );
224 // if not already in a temporary area, put it there
225 $storeStatus = $this->repo
->storeTemp( basename( $pathWithGoodExtension ), $path );
227 if ( ! $storeStatus->isOK() ) {
228 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
229 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
230 // 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
231 // redesigning API errors significantly.
232 // $storeStatus->value just contains the virtual URL (if anything) which is probably useless to the caller
233 $error = $storeStatus->getErrorsArray();
234 $error = reset( $error );
235 if ( ! count( $error ) ) {
236 $error = $storeStatus->getWarningsArray();
237 $error = reset( $error );
238 if ( ! count( $error ) ) {
239 $error = array( 'unknown', 'no error recorded' );
242 // at this point, $error should contain the single "most important" error, plus any parameters.
243 $errorMsg = array_shift( $error );
244 throw new UploadStashFileException( "Error storing file in '$path': " . wfMessage( $errorMsg, $error )->text() );
246 $stashPath = $storeStatus->value
;
248 // fetch the current user ID
249 if ( !$this->isLoggedIn
) {
250 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
253 // insert the file metadata into the db.
254 wfDebug( __METHOD__
. " inserting $stashPath under $key\n" );
255 $dbw = $this->repo
->getMasterDb();
257 $this->fileMetadata
[$key] = array(
258 'us_id' => $dbw->nextSequenceValue( 'uploadstash_us_id_seq' ),
259 'us_user' => $this->userId
,
261 'us_orig_path' => $path,
262 'us_path' => $stashPath, // virtual URL
263 'us_props' => $dbw->encodeBlob( serialize( $fileProps ) ),
264 'us_size' => $fileProps['size'],
265 'us_sha1' => $fileProps['sha1'],
266 'us_mime' => $fileProps['mime'],
267 'us_media_type' => $fileProps['media_type'],
268 'us_image_width' => $fileProps['width'],
269 'us_image_height' => $fileProps['height'],
270 'us_image_bits' => $fileProps['bits'],
271 'us_source_type' => $sourceType,
272 'us_timestamp' => $dbw->timestamp(),
273 'us_status' => 'finished'
278 $this->fileMetadata
[$key],
282 // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
283 $this->fileMetadata
[$key]['us_id'] = $dbw->insertId();
285 # create the UploadStashFile object for this file.
286 $this->initFile( $key );
288 return $this->getFile( $key );
292 * Remove all files from the stash.
293 * Does not clean up files in the repo, just the record of them.
295 * @throws UploadStashNotLoggedInException
296 * @return bool Success
298 public function clear() {
299 if ( !$this->isLoggedIn
) {
300 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
303 wfDebug( __METHOD__
. ' clearing all rows for user ' . $this->userId
. "\n" );
304 $dbw = $this->repo
->getMasterDb();
307 array( 'us_user' => $this->userId
),
312 $this->files
= array();
313 $this->fileMetadata
= array();
319 * Remove a particular file from the stash. Also removes it from the repo.
322 * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException|UploadStashWrongOwnerException
323 * @return bool Success
325 public function removeFile( $key ) {
326 if ( !$this->isLoggedIn
) {
327 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
330 $dbw = $this->repo
->getMasterDb();
332 // this is a cheap query. it runs on the master so that this function still works when there's lag.
333 // it won't be called all that often.
334 $row = $dbw->selectRow(
337 array( 'us_key' => $key ),
342 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
345 if ( $row->us_user
!= $this->userId
) {
346 throw new UploadStashWrongOwnerException( "Can't delete: the file ($key) doesn't belong to this user." );
349 return $this->removeFileNoAuth( $key );
353 * Remove a file (see removeFile), but doesn't check ownership first.
356 * @return bool Success
358 public function removeFileNoAuth( $key ) {
359 wfDebug( __METHOD__
. " clearing row $key\n" );
361 // Ensure we have the UploadStashFile loaded for this key
362 $this->getFile( $key, true );
364 $dbw = $this->repo
->getMasterDb();
368 array( 'us_key' => $key ),
372 // TODO: look into UnregisteredLocalFile and find out why the rv here is sometimes wrong (false when file was removed)
374 $this->files
[$key]->remove();
376 unset( $this->files
[$key] );
377 unset( $this->fileMetadata
[$key] );
383 * List all files in the stash.
385 * @throws UploadStashNotLoggedInException
388 public function listFiles() {
389 if ( !$this->isLoggedIn
) {
390 throw new UploadStashNotLoggedInException( __METHOD__
. ' No user is logged in, files must belong to users' );
393 $dbr = $this->repo
->getSlaveDb();
397 array( 'us_user' => $this->userId
),
401 if ( !is_object( $res ) ||
$res->numRows() == 0 ) {
406 // finish the read before starting writes.
408 foreach ( $res as $row ) {
409 array_push( $keys, $row->us_key
);
416 * Find or guess extension -- ensuring that our extension matches our mime type.
417 * Since these files are constructed from php tempnames they may not start off
419 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
420 * uploads versus the desired filename. Maybe we can get that passed to us...
421 * @param string $path
422 * @throws UploadStashFileException
425 public static function getExtensionForPath( $path ) {
426 global $wgFileBlacklist;
427 // Does this have an extension?
428 $n = strrpos( $path, '.' );
430 if ( $n !== false ) {
431 $extension = $n ?
substr( $path, $n +
1 ) : '';
433 // If not, assume that it should be related to the mime type of the original file.
434 $magic = MimeMagic
::singleton();
435 $mimeType = $magic->guessMimeType( $path );
436 $extensions = explode( ' ', MimeMagic
::singleton()->getExtensionsForType( $mimeType ) );
437 if ( count( $extensions ) ) {
438 $extension = $extensions[0];
442 if ( is_null( $extension ) ) {
443 throw new UploadStashFileException( "extension is null" );
446 $extension = File
::normalizeExtension( $extension );
447 if ( in_array( $extension, $wgFileBlacklist ) ) {
448 // The file should already be checked for being evil.
449 // However, if somehow we got here, we definitely
450 // don't want to give it an extension of .php and
451 // put it in a web accesible directory.
458 * Helper function: do the actual database query to fetch file metadata.
461 * @param int $readFromDB Constant (default: DB_SLAVE)
464 protected function fetchFileMetadata( $key, $readFromDB = DB_SLAVE
) {
465 // populate $fileMetadata[$key]
467 if ( $readFromDB === DB_MASTER
) {
468 // sometimes reading from the master is necessary, if there's replication lag.
469 $dbr = $this->repo
->getMasterDb();
471 $dbr = $this->repo
->getSlaveDb();
474 $row = $dbr->selectRow(
477 array( 'us_key' => $key ),
481 if ( !is_object( $row ) ) {
482 // key wasn't present in the database. this will happen sometimes.
486 $this->fileMetadata
[$key] = (array)$row;
487 $this->fileMetadata
[$key]['us_props'] = $dbr->decodeBlob( $row->us_props
);
493 * Helper function: Initialize the UploadStashFile for a given file.
495 * @param string $key key under which to store the object
496 * @throws UploadStashZeroLengthFileException
499 protected function initFile( $key ) {
500 $file = new UploadStashFile( $this->repo
, $this->fileMetadata
[$key]['us_path'], $key );
501 if ( $file->getSize() === 0 ) {
502 throw new UploadStashZeroLengthFileException( "File is zero length" );
504 $this->files
[$key] = $file;
509 class UploadStashFile
extends UnregisteredLocalFile
{
515 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
516 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
518 * @param FileRepo $repo Repository where we should find the path
519 * @param string $path Path to file
520 * @param string $key Key to store the path and any stashed data under
521 * @throws UploadStashBadPathException
522 * @throws UploadStashFileNotFoundException
524 public function __construct( $repo, $path, $key ) {
525 $this->fileKey
= $key;
527 // resolve mwrepo:// urls
528 if ( $repo->isVirtualUrl( $path ) ) {
529 $path = $repo->resolveVirtualUrl( $path );
532 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
533 $repoTempPath = $repo->getZonePath( 'temp' );
534 if ( ( ! $repo->validateFilename( $path ) ) ||
535 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
536 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
537 throw new UploadStashBadPathException( 'path is not valid' );
540 // check if path exists! and is a plain file.
541 if ( ! $repo->fileExists( $path ) ) {
542 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
543 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
547 parent
::__construct( false, $repo, $path, false );
549 $this->name
= basename( $this->path
);
553 * A method needed by the file transforming and scaling routines in File.php
554 * We do not necessarily care about doing the description at this point
555 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
556 * convert require it to be there)
558 * @return string Dummy value
560 public function getDescriptionUrl() {
561 return $this->getUrl();
565 * Get the path for the thumbnail (actually any transformation of this file)
566 * The actual argument is the result of thumbName although we seem to have
567 * buggy code elsewhere that expects a boolean 'suffix'
569 * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
570 * @return string Path thumbnail should take on filesystem, or containing directory if thumbname is false
572 public function getThumbPath( $thumbName = false ) {
573 $path = dirname( $this->path
);
574 if ( $thumbName !== false ) {
575 $path .= "/$thumbName";
581 * Return the file/url base name of a thumbnail with the specified parameters.
582 * We override this because we want to use the pretty url name instead of the
585 * @param array $params Handler-specific parameters
586 * @param int $flags Bitfield that supports THUMB_* constants
587 * @return string Base name for URL, like '120px-12345.jpg', or null if there is no handler
589 function thumbName( $params, $flags = 0 ) {
590 return $this->generateThumbName( $this->getUrlName(), $params );
594 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
595 * @param string $subPage
596 * @return string Local URL for this subpage in the Special:UploadStash space.
598 private function getSpecialUrl( $subPage ) {
599 return SpecialPage
::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
603 * Get a URL to access the thumbnail
604 * This is required because the model of how files work requires that
605 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
606 * (that's hidden in the db)
608 * @param string $thumbName Basename of thumbnail file -- however, we don't want to use the file exactly
609 * @return string URL to access thumbnail, or URL with partial path
611 public function getThumbUrl( $thumbName = false ) {
612 wfDebug( __METHOD__
. " getting for $thumbName \n" );
613 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
617 * The basename for the URL, which we want to not be related to the filename.
618 * Will also be used as the lookup key for a thumbnail file.
620 * @return string Base url name, like '120px-123456.jpg'
622 public function getUrlName() {
623 if ( ! $this->urlName
) {
624 $this->urlName
= $this->fileKey
;
626 return $this->urlName
;
630 * Return the URL of the file, if for some reason we wanted to download it
631 * We tend not to do this for the original file, but we do want thumb icons
635 public function getUrl() {
636 if ( !isset( $this->url
) ) {
637 $this->url
= $this->getSpecialUrl( 'file/' . $this->getUrlName() );
643 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
644 * But with this class, the URL is unrelated to the path.
648 public function getFullUrl() {
649 return $this->getUrl();
653 * Getter for file key (the unique id by which this file's location & metadata is stored in the db)
655 * @return string File key
657 public function getFileKey() {
658 return $this->fileKey
;
662 * Remove the associated temporary file
663 * @return status Success
665 public function remove() {
666 if ( !$this->repo
->fileExists( $this->path
) ) {
667 // Maybe the file's already been removed? This could totally happen in UploadBase.
671 return $this->repo
->freeTemp( $this->path
);
674 public function exists() {
675 return $this->repo
->fileExists( $this->path
);
680 class UploadStashException
extends MWException
{};
681 class UploadStashNotAvailableException
extends UploadStashException
{};
682 class UploadStashFileNotFoundException
extends UploadStashException
{};
683 class UploadStashBadPathException
extends UploadStashException
{};
684 class UploadStashFileException
extends UploadStashException
{};
685 class UploadStashZeroLengthFileException
extends UploadStashException
{};
686 class UploadStashNotLoggedInException
extends UploadStashException
{};
687 class UploadStashWrongOwnerException
extends UploadStashException
{};
688 class UploadStashNoSuchKeyException
extends UploadStashException
{};