Merge "Don't let LinkCache grow indefinitely"
[mediawiki.git] / includes / upload / UploadStash.php
blobc07665a06cf70bd58591fa28689b49fee187a6d6
1 <?php
2 /**
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
20 * @file
21 * @ingroup Upload
24 /**
25 * UploadStash is intended to accomplish a few things:
26 * - Enable applications to temporarily stash files without publishing them to
27 * the wiki.
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
40 * this way.
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
52 * @ingroup Upload
54 class UploadStash {
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*$/';
58 /**
59 * repository that this uses to store temp files
60 * public because we sometimes need to get a LocalFile within the same repo.
62 * @var LocalRepo
64 public $repo;
66 // array of initialized repo objects
67 protected $files = array();
69 // cache of the file metadata that's stored in the database
70 protected $fileMetadata = array();
72 // fileprops cache
73 protected $fileProps = array();
75 // current user
76 protected $user, $userId, $isLoggedIn;
78 /**
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.
88 $this->repo = $repo;
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
92 if ( $user ) {
93 $this->user = $user;
94 } else {
95 global $wgUser;
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( "key '$key' is not in a proper format" );
123 if ( !$noAuth && !$this->isLoggedIn ) {
124 throw new UploadStashNotLoggedInException( __METHOD__ .
125 ' No user is logged in, files must belong to users' );
128 if ( !isset( $this->fileMetadata[$key] ) ) {
129 if ( !$this->fetchFileMetadata( $key ) ) {
130 // If nothing was received, it's likely due to replication lag.
131 // Check the master to see if the record is there.
132 $this->fetchFileMetadata( $key, DB_MASTER );
135 if ( !isset( $this->fileMetadata[$key] ) ) {
136 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
139 // create $this->files[$key]
140 $this->initFile( $key );
142 // fetch fileprops
143 if ( strlen( $this->fileMetadata[$key]['us_props'] ) ) {
144 $this->fileProps[$key] = unserialize( $this->fileMetadata[$key]['us_props'] );
145 } else { // b/c for rows with no us_props
146 wfDebug( __METHOD__ . " fetched props for $key from file\n" );
147 $path = $this->fileMetadata[$key]['us_path'];
148 $this->fileProps[$key] = $this->repo->getFileProps( $path );
152 if ( !$this->files[$key]->exists() ) {
153 wfDebug( __METHOD__ . " tried to get file at $key, but it doesn't exist\n" );
154 // @todo Is this not an UploadStashFileNotFoundException case?
155 throw new UploadStashBadPathException( "path doesn't exist" );
158 if ( !$noAuth ) {
159 if ( $this->fileMetadata[$key]['us_user'] != $this->userId ) {
160 throw new UploadStashWrongOwnerException( "This file ($key) doesn't "
161 . "belong to the current user." );
165 return $this->files[$key];
169 * Getter for file metadata.
171 * @param string $key Key under which file information is stored
172 * @return array
174 public function getMetadata( $key ) {
175 $this->getFile( $key );
177 return $this->fileMetadata[$key];
181 * Getter for fileProps
183 * @param string $key Key under which file information is stored
184 * @return array
186 public function getFileProps( $key ) {
187 $this->getFile( $key );
189 return $this->fileProps[$key];
193 * Stash a file in a temp directory and record that we did this in the
194 * database, along with other metadata.
196 * @param string $path Path to file you want stashed
197 * @param string $sourceType The type of upload that generated this file
198 * (currently, I believe, 'file' or null)
199 * @throws UploadStashBadPathException
200 * @throws UploadStashFileException
201 * @throws UploadStashNotLoggedInException
202 * @return UploadStashFile|null File, or null on failure
204 public function stashFile( $path, $sourceType = null ) {
205 if ( !is_file( $path ) ) {
206 wfDebug( __METHOD__ . " tried to stash file at '$path', but it doesn't exist\n" );
207 throw new UploadStashBadPathException( "path doesn't exist" );
209 $fileProps = FSFile::getPropsFromPath( $path );
210 wfDebug( __METHOD__ . " stashing file at '$path'\n" );
212 // we will be initializing from some tmpnam files that don't have extensions.
213 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
214 $extension = self::getExtensionForPath( $path );
215 if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
216 $pathWithGoodExtension = "$path.$extension";
217 } else {
218 $pathWithGoodExtension = $path;
221 // If no key was supplied, make one. a mysql insertid would be totally
222 // reasonable here, except that for historical reasons, the key is this
223 // 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 = wfBaseConvert( $sec . $usec, 10, 36 ) . '.' .
230 wfBaseConvert( mt_rand(), 10, 36 ) . '.' .
231 $this->userId . '.' .
232 $extension;
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 = array( '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 $this->fileMetadata[$key] = array(
282 'us_id' => $dbw->nextSequenceValue( 'uploadstash_us_id_seq' ),
283 'us_user' => $this->userId,
284 'us_key' => $key,
285 'us_orig_path' => $path,
286 'us_path' => $stashPath, // virtual URL
287 'us_props' => $dbw->encodeBlob( serialize( $fileProps ) ),
288 'us_size' => $fileProps['size'],
289 'us_sha1' => $fileProps['sha1'],
290 'us_mime' => $fileProps['mime'],
291 'us_media_type' => $fileProps['media_type'],
292 'us_image_width' => $fileProps['width'],
293 'us_image_height' => $fileProps['height'],
294 'us_image_bits' => $fileProps['bits'],
295 'us_source_type' => $sourceType,
296 'us_timestamp' => $dbw->timestamp(),
297 'us_status' => 'finished'
300 $dbw->insert(
301 'uploadstash',
302 $this->fileMetadata[$key],
303 __METHOD__
306 // store the insertid in the class variable so immediate retrieval
307 // (possibly laggy) isn't necesary.
308 $this->fileMetadata[$key]['us_id'] = $dbw->insertId();
310 # create the UploadStashFile object for this file.
311 $this->initFile( $key );
313 return $this->getFile( $key );
317 * Remove all files from the stash.
318 * Does not clean up files in the repo, just the record of them.
320 * @throws UploadStashNotLoggedInException
321 * @return bool Success
323 public function clear() {
324 if ( !$this->isLoggedIn ) {
325 throw new UploadStashNotLoggedInException( __METHOD__
326 . ' No user is logged in, files must belong to users' );
329 wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->userId . "\n" );
330 $dbw = $this->repo->getMasterDb();
331 $dbw->delete(
332 'uploadstash',
333 array( 'us_user' => $this->userId ),
334 __METHOD__
337 # destroy objects.
338 $this->files = array();
339 $this->fileMetadata = array();
341 return true;
345 * Remove a particular file from the stash. Also removes it from the repo.
347 * @param string $key
348 * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException
349 * @throws UploadStashWrongOwnerException
350 * @return bool Success
352 public function removeFile( $key ) {
353 if ( !$this->isLoggedIn ) {
354 throw new UploadStashNotLoggedInException( __METHOD__
355 . ' No user is logged in, files must belong to users' );
358 $dbw = $this->repo->getMasterDb();
360 // this is a cheap query. it runs on the master so that this function
361 // still works when there's lag. It won't be called all that often.
362 $row = $dbw->selectRow(
363 'uploadstash',
364 'us_user',
365 array( 'us_key' => $key ),
366 __METHOD__
369 if ( !$row ) {
370 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
373 if ( $row->us_user != $this->userId ) {
374 throw new UploadStashWrongOwnerException( "Can't delete: "
375 . "the file ($key) doesn't belong to this user." );
378 return $this->removeFileNoAuth( $key );
382 * Remove a file (see removeFile), but doesn't check ownership first.
384 * @param string $key
385 * @return bool Success
387 public function removeFileNoAuth( $key ) {
388 wfDebug( __METHOD__ . " clearing row $key\n" );
390 // Ensure we have the UploadStashFile loaded for this key
391 $this->getFile( $key, true );
393 $dbw = $this->repo->getMasterDb();
395 $dbw->delete(
396 'uploadstash',
397 array( 'us_key' => $key ),
398 __METHOD__
401 /** @todo Look into UnregisteredLocalFile and find out why the rv here is
402 * sometimes wrong (false when file was removed). For now, ignore.
404 $this->files[$key]->remove();
406 unset( $this->files[$key] );
407 unset( $this->fileMetadata[$key] );
409 return true;
413 * List all files in the stash.
415 * @throws UploadStashNotLoggedInException
416 * @return array
418 public function listFiles() {
419 if ( !$this->isLoggedIn ) {
420 throw new UploadStashNotLoggedInException( __METHOD__
421 . ' No user is logged in, files must belong to users' );
424 $dbr = $this->repo->getSlaveDb();
425 $res = $dbr->select(
426 'uploadstash',
427 'us_key',
428 array( 'us_user' => $this->userId ),
429 __METHOD__
432 if ( !is_object( $res ) || $res->numRows() == 0 ) {
433 // nothing to do.
434 return false;
437 // finish the read before starting writes.
438 $keys = array();
439 foreach ( $res as $row ) {
440 array_push( $keys, $row->us_key );
443 return $keys;
447 * Find or guess extension -- ensuring that our extension matches our MIME type.
448 * Since these files are constructed from php tempnames they may not start off
449 * with an extension.
450 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
451 * uploads versus the desired filename. Maybe we can get that passed to us...
452 * @param string $path
453 * @throws UploadStashFileException
454 * @return string
456 public static function getExtensionForPath( $path ) {
457 global $wgFileBlacklist;
458 // Does this have an extension?
459 $n = strrpos( $path, '.' );
460 $extension = null;
461 if ( $n !== false ) {
462 $extension = $n ? substr( $path, $n + 1 ) : '';
463 } else {
464 // If not, assume that it should be related to the MIME type of the original file.
465 $magic = MimeMagic::singleton();
466 $mimeType = $magic->guessMimeType( $path );
467 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
468 if ( count( $extensions ) ) {
469 $extension = $extensions[0];
473 if ( is_null( $extension ) ) {
474 throw new UploadStashFileException( "extension is null" );
477 $extension = File::normalizeExtension( $extension );
478 if ( in_array( $extension, $wgFileBlacklist ) ) {
479 // The file should already be checked for being evil.
480 // However, if somehow we got here, we definitely
481 // don't want to give it an extension of .php and
482 // put it in a web accesible directory.
483 return '';
486 return $extension;
490 * Helper function: do the actual database query to fetch file metadata.
492 * @param string $key
493 * @param int $readFromDB Constant (default: DB_SLAVE)
494 * @return bool
496 protected function fetchFileMetadata( $key, $readFromDB = DB_SLAVE ) {
497 // populate $fileMetadata[$key]
498 $dbr = null;
499 if ( $readFromDB === DB_MASTER ) {
500 // sometimes reading from the master is necessary, if there's replication lag.
501 $dbr = $this->repo->getMasterDb();
502 } else {
503 $dbr = $this->repo->getSlaveDb();
506 $row = $dbr->selectRow(
507 'uploadstash',
508 '*',
509 array( 'us_key' => $key ),
510 __METHOD__
513 if ( !is_object( $row ) ) {
514 // key wasn't present in the database. this will happen sometimes.
515 return false;
518 $this->fileMetadata[$key] = (array)$row;
519 $this->fileMetadata[$key]['us_props'] = $dbr->decodeBlob( $row->us_props );
521 return true;
525 * Helper function: Initialize the UploadStashFile for a given file.
527 * @param string $key Key under which to store the object
528 * @throws UploadStashZeroLengthFileException
529 * @return bool
531 protected function initFile( $key ) {
532 $file = new UploadStashFile( $this->repo, $this->fileMetadata[$key]['us_path'], $key );
533 if ( $file->getSize() === 0 ) {
534 throw new UploadStashZeroLengthFileException( "File is zero length" );
536 $this->files[$key] = $file;
538 return true;
542 class UploadStashFile extends UnregisteredLocalFile {
543 private $fileKey;
544 private $urlName;
545 protected $url;
548 * A LocalFile wrapper around a file that has been temporarily stashed,
549 * so we can do things like create thumbnails for it. Arguably
550 * UnregisteredLocalFile should be handling its own file repo but that
551 * class is a bit retarded currently.
553 * @param FileRepo $repo Repository where we should find the path
554 * @param string $path Path to file
555 * @param string $key Key to store the path and any stashed data under
556 * @throws UploadStashBadPathException
557 * @throws UploadStashFileNotFoundException
559 public function __construct( $repo, $path, $key ) {
560 $this->fileKey = $key;
562 // resolve mwrepo:// urls
563 if ( $repo->isVirtualUrl( $path ) ) {
564 $path = $repo->resolveVirtualUrl( $path );
565 } else {
566 // check if path appears to be sane, no parent traversals,
567 // and is in this repo's temp zone.
568 $repoTempPath = $repo->getZonePath( 'temp' );
569 if ( ( !$repo->validateFilename( $path ) ) ||
570 ( strpos( $path, $repoTempPath ) !== 0 )
572 wfDebug( "UploadStash: tried to construct an UploadStashFile "
573 . "from a file that should already exist at '$path', but path is not valid\n" );
574 throw new UploadStashBadPathException( 'path is not valid' );
577 // check if path exists! and is a plain file.
578 if ( !$repo->fileExists( $path ) ) {
579 wfDebug( "UploadStash: tried to construct an UploadStashFile from "
580 . "a file that should already exist at '$path', but path is not found\n" );
581 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
585 parent::__construct( false, $repo, $path, false );
587 $this->name = basename( $this->path );
591 * A method needed by the file transforming and scaling routines in File.php
592 * We do not necessarily care about doing the description at this point
593 * However, we also can't return the empty string, as the rest of MediaWiki
594 * demands this (and calls to imagemagick convert require it to be there)
596 * @return string Dummy value
598 public function getDescriptionUrl() {
599 return $this->getUrl();
603 * Get the path for the thumbnail (actually any transformation of this file)
604 * The actual argument is the result of thumbName although we seem to have
605 * buggy code elsewhere that expects a boolean 'suffix'
607 * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ),
608 * or false to just get the path
609 * @return string Path thumbnail should take on filesystem, or containing
610 * directory if thumbname is false
612 public function getThumbPath( $thumbName = false ) {
613 $path = dirname( $this->path );
614 if ( $thumbName !== false ) {
615 $path .= "/$thumbName";
618 return $path;
622 * Return the file/url base name of a thumbnail with the specified parameters.
623 * We override this because we want to use the pretty url name instead of the
624 * ugly file name.
626 * @param array $params Handler-specific parameters
627 * @param int $flags Bitfield that supports THUMB_* constants
628 * @return string Base name for URL, like '120px-12345.jpg', or null if there is no handler
630 function thumbName( $params, $flags = 0 ) {
631 return $this->generateThumbName( $this->getUrlName(), $params );
635 * Helper function -- given a 'subpage', return the local URL,
636 * e.g. /wiki/Special:UploadStash/subpage
637 * @param string $subPage
638 * @return string Local URL for this subpage in the Special:UploadStash space.
640 private function getSpecialUrl( $subPage ) {
641 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
645 * Get a URL to access the thumbnail
646 * This is required because the model of how files work requires that
647 * the thumbnail urls be predictable. However, in our model the URL is
648 * not based on the filename (that's hidden in the db)
650 * @param string $thumbName Basename of thumbnail file -- however, we don't
651 * want to use the file exactly
652 * @return string URL to access thumbnail, or URL with partial path
654 public function getThumbUrl( $thumbName = false ) {
655 wfDebug( __METHOD__ . " getting for $thumbName \n" );
657 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
661 * The basename for the URL, which we want to not be related to the filename.
662 * Will also be used as the lookup key for a thumbnail file.
664 * @return string Base url name, like '120px-123456.jpg'
666 public function getUrlName() {
667 if ( !$this->urlName ) {
668 $this->urlName = $this->fileKey;
671 return $this->urlName;
675 * Return the URL of the file, if for some reason we wanted to download it
676 * We tend not to do this for the original file, but we do want thumb icons
678 * @return string Url
680 public function getUrl() {
681 if ( !isset( $this->url ) ) {
682 $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
685 return $this->url;
689 * Parent classes use this method, for no obvious reason, to return the path
690 * (relative to wiki root, I assume). But with this class, the URL is
691 * unrelated to the path.
693 * @return string Url
695 public function getFullUrl() {
696 return $this->getUrl();
700 * Getter for file key (the unique id by which this file's location &
701 * metadata is stored in the db)
703 * @return string File key
705 public function getFileKey() {
706 return $this->fileKey;
710 * Remove the associated temporary file
711 * @return status Success
713 public function remove() {
714 if ( !$this->repo->fileExists( $this->path ) ) {
715 // Maybe the file's already been removed? This could totally happen in UploadBase.
716 return true;
719 return $this->repo->freeTemp( $this->path );
722 public function exists() {
723 return $this->repo->fileExists( $this->path );
727 class UploadStashException extends MWException {
730 class UploadStashFileNotFoundException extends UploadStashException {
733 class UploadStashBadPathException extends UploadStashException {
736 class UploadStashFileException extends UploadStashException {
739 class UploadStashZeroLengthFileException extends UploadStashException {
742 class UploadStashNotLoggedInException extends UploadStashException {
745 class UploadStashWrongOwnerException extends UploadStashException {
748 class UploadStashNoSuchKeyException extends UploadStashException {