]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/upload/UploadStash.php
MediaWiki 1.30.2-scripts2
[autoinstalls/mediawiki.git] / includes / upload / UploadStash.php
1 <?php
2 /**
3  * Temporary storage for uploaded files.
4  *
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.
9  *
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.
14  *
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
19  *
20  * @file
21  * @ingroup Upload
22  */
23
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.
41  *
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.
46  *
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
51  *
52  * @ingroup Upload
53  */
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*$/';
57         const MAX_US_PROPS_SIZE = 65535;
58
59         /**
60          * repository that this uses to store temp files
61          * public because we sometimes need to get a LocalFile within the same repo.
62          *
63          * @var LocalRepo
64          */
65         public $repo;
66
67         // array of initialized repo objects
68         protected $files = [];
69
70         // cache of the file metadata that's stored in the database
71         protected $fileMetadata = [];
72
73         // fileprops cache
74         protected $fileProps = [];
75
76         // current user
77         protected $user, $userId, $isLoggedIn;
78
79         /**
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).
83          *
84          * @param FileRepo $repo
85          * @param User $user (default null)
86          */
87         public function __construct( FileRepo $repo, $user = null ) {
88                 // this might change based on wiki's configuration.
89                 $this->repo = $repo;
90
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
93                 if ( $user ) {
94                         $this->user = $user;
95                 } else {
96                         global $wgUser;
97                         $this->user = $wgUser;
98                 }
99
100                 if ( is_object( $this->user ) ) {
101                         $this->userId = $this->user->getId();
102                         $this->isLoggedIn = $this->user->isLoggedIn();
103                 }
104         }
105
106         /**
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.
110          *
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
118          */
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" );
122                 }
123
124                 if ( !$noAuth && !$this->isLoggedIn ) {
125                         throw new UploadStashNotLoggedInException( __METHOD__ .
126                                 ' No user is logged in, files must belong to users' );
127                 }
128
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 );
134                         }
135
136                         if ( !isset( $this->fileMetadata[$key] ) ) {
137                                 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
138                         }
139
140                         // create $this->files[$key]
141                         $this->initFile( $key );
142
143                         // fetch fileprops
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 );
150                         }
151                 }
152
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" );
157                 }
158
159                 if ( !$noAuth ) {
160                         if ( $this->fileMetadata[$key]['us_user'] != $this->userId ) {
161                                 throw new UploadStashWrongOwnerException( "This file ($key) doesn't "
162                                         . "belong to the current user." );
163                         }
164                 }
165
166                 return $this->files[$key];
167         }
168
169         /**
170          * Getter for file metadata.
171          *
172          * @param string $key Key under which file information is stored
173          * @return array
174          */
175         public function getMetadata( $key ) {
176                 $this->getFile( $key );
177
178                 return $this->fileMetadata[$key];
179         }
180
181         /**
182          * Getter for fileProps
183          *
184          * @param string $key Key under which file information is stored
185          * @return array
186          */
187         public function getFileProps( $key ) {
188                 $this->getFile( $key );
189
190                 return $this->fileProps[$key];
191         }
192
193         /**
194          * Stash a file in a temp directory and record that we did this in the
195          * database, along with other metadata.
196          *
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
204          */
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" );
209                 }
210
211                 $mwProps = new MWFileProps( MimeMagic::singleton() );
212                 $fileProps = $mwProps->getPropsFromPath( $path, true );
213                 wfDebug( __METHOD__ . " stashing file at '$path'\n" );
214
215                 // we will be initializing from some tmpnam files that don't have extensions.
216                 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
217                 $extension = self::getExtensionForPath( $path );
218                 if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
219                         $pathWithGoodExtension = "$path.$extension";
220                 } else {
221                         $pathWithGoodExtension = $path;
222                 }
223
224                 // If no key was supplied, make one.  a mysql insertid would be totally
225                 // reasonable here, except that for historical reasons, the key is this
226                 // random thing instead.  At least it's not guessable.
227                 // Some things that when combined will make a suitably unique key.
228                 // see: http://www.jwz.org/doc/mid.html
229                 list( $usec, $sec ) = explode( ' ', microtime() );
230                 $usec = substr( $usec, 2 );
231                 $key = Wikimedia\base_convert( $sec . $usec, 10, 36 ) . '.' .
232                         Wikimedia\base_convert( mt_rand(), 10, 36 ) . '.' .
233                         $this->userId . '.' .
234                         $extension;
235
236                 $this->fileProps[$key] = $fileProps;
237
238                 if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
239                         throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
240                 }
241
242                 wfDebug( __METHOD__ . " key for '$path': $key\n" );
243
244                 // if not already in a temporary area, put it there
245                 $storeStatus = $this->repo->storeTemp( basename( $pathWithGoodExtension ), $path );
246
247                 if ( !$storeStatus->isOK() ) {
248                         // It is a convention in MediaWiki to only return one error per API
249                         // exception, even if multiple errors are available. We use reset()
250                         // to pick the "first" thing that was wrong, preferring errors to
251                         // warnings. This is a bit lame, as we may have more info in the
252                         // $storeStatus and we're throwing it away, but to fix it means
253                         // redesigning API errors significantly.
254                         // $storeStatus->value just contains the virtual URL (if anything)
255                         // which is probably useless to the caller.
256                         $error = $storeStatus->getErrorsArray();
257                         $error = reset( $error );
258                         if ( !count( $error ) ) {
259                                 $error = $storeStatus->getWarningsArray();
260                                 $error = reset( $error );
261                                 if ( !count( $error ) ) {
262                                         $error = [ 'unknown', 'no error recorded' ];
263                                 }
264                         }
265                         // At this point, $error should contain the single "most important"
266                         // error, plus any parameters.
267                         $errorMsg = array_shift( $error );
268                         throw new UploadStashFileException( "Error storing file in '$path': "
269                                 . wfMessage( $errorMsg, $error )->text() );
270                 }
271                 $stashPath = $storeStatus->value;
272
273                 // fetch the current user ID
274                 if ( !$this->isLoggedIn ) {
275                         throw new UploadStashNotLoggedInException( __METHOD__
276                                 . ' No user is logged in, files must belong to users' );
277                 }
278
279                 // insert the file metadata into the db.
280                 wfDebug( __METHOD__ . " inserting $stashPath under $key\n" );
281                 $dbw = $this->repo->getMasterDB();
282
283                 $serializedFileProps = serialize( $fileProps );
284                 if ( strlen( $serializedFileProps ) > self::MAX_US_PROPS_SIZE ) {
285                         // Database is going to truncate this and make the field invalid.
286                         // Prioritize important metadata over file handler metadata.
287                         // File handler should be prepared to regenerate invalid metadata if needed.
288                         $fileProps['metadata'] = false;
289                         $serializedFileProps = serialize( $fileProps );
290                 }
291
292                 $this->fileMetadata[$key] = [
293                         'us_user' => $this->userId,
294                         'us_key' => $key,
295                         'us_orig_path' => $path,
296                         'us_path' => $stashPath, // virtual URL
297                         'us_props' => $dbw->encodeBlob( $serializedFileProps ),
298                         'us_size' => $fileProps['size'],
299                         'us_sha1' => $fileProps['sha1'],
300                         'us_mime' => $fileProps['mime'],
301                         'us_media_type' => $fileProps['media_type'],
302                         'us_image_width' => $fileProps['width'],
303                         'us_image_height' => $fileProps['height'],
304                         'us_image_bits' => $fileProps['bits'],
305                         'us_source_type' => $sourceType,
306                         'us_timestamp' => $dbw->timestamp(),
307                         'us_status' => 'finished'
308                 ];
309
310                 $dbw->insert(
311                         'uploadstash',
312                         $this->fileMetadata[$key],
313                         __METHOD__
314                 );
315
316                 // store the insertid in the class variable so immediate retrieval
317                 // (possibly laggy) isn't necesary.
318                 $this->fileMetadata[$key]['us_id'] = $dbw->insertId();
319
320                 # create the UploadStashFile object for this file.
321                 $this->initFile( $key );
322
323                 return $this->getFile( $key );
324         }
325
326         /**
327          * Remove all files from the stash.
328          * Does not clean up files in the repo, just the record of them.
329          *
330          * @throws UploadStashNotLoggedInException
331          * @return bool Success
332          */
333         public function clear() {
334                 if ( !$this->isLoggedIn ) {
335                         throw new UploadStashNotLoggedInException( __METHOD__
336                                 . ' No user is logged in, files must belong to users' );
337                 }
338
339                 wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->userId . "\n" );
340                 $dbw = $this->repo->getMasterDB();
341                 $dbw->delete(
342                         'uploadstash',
343                         [ 'us_user' => $this->userId ],
344                         __METHOD__
345                 );
346
347                 # destroy objects.
348                 $this->files = [];
349                 $this->fileMetadata = [];
350
351                 return true;
352         }
353
354         /**
355          * Remove a particular file from the stash.  Also removes it from the repo.
356          *
357          * @param string $key
358          * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException
359          * @throws UploadStashWrongOwnerException
360          * @return bool Success
361          */
362         public function removeFile( $key ) {
363                 if ( !$this->isLoggedIn ) {
364                         throw new UploadStashNotLoggedInException( __METHOD__
365                                 . ' No user is logged in, files must belong to users' );
366                 }
367
368                 $dbw = $this->repo->getMasterDB();
369
370                 // this is a cheap query. it runs on the master so that this function
371                 // still works when there's lag. It won't be called all that often.
372                 $row = $dbw->selectRow(
373                         'uploadstash',
374                         'us_user',
375                         [ 'us_key' => $key ],
376                         __METHOD__
377                 );
378
379                 if ( !$row ) {
380                         throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
381                 }
382
383                 if ( $row->us_user != $this->userId ) {
384                         throw new UploadStashWrongOwnerException( "Can't delete: "
385                                 . "the file ($key) doesn't belong to this user." );
386                 }
387
388                 return $this->removeFileNoAuth( $key );
389         }
390
391         /**
392          * Remove a file (see removeFile), but doesn't check ownership first.
393          *
394          * @param string $key
395          * @return bool Success
396          */
397         public function removeFileNoAuth( $key ) {
398                 wfDebug( __METHOD__ . " clearing row $key\n" );
399
400                 // Ensure we have the UploadStashFile loaded for this key
401                 $this->getFile( $key, true );
402
403                 $dbw = $this->repo->getMasterDB();
404
405                 $dbw->delete(
406                         'uploadstash',
407                         [ 'us_key' => $key ],
408                         __METHOD__
409                 );
410
411                 /** @todo Look into UnregisteredLocalFile and find out why the rv here is
412                  *  sometimes wrong (false when file was removed). For now, ignore.
413                  */
414                 $this->files[$key]->remove();
415
416                 unset( $this->files[$key] );
417                 unset( $this->fileMetadata[$key] );
418
419                 return true;
420         }
421
422         /**
423          * List all files in the stash.
424          *
425          * @throws UploadStashNotLoggedInException
426          * @return array
427          */
428         public function listFiles() {
429                 if ( !$this->isLoggedIn ) {
430                         throw new UploadStashNotLoggedInException( __METHOD__
431                                 . ' No user is logged in, files must belong to users' );
432                 }
433
434                 $dbr = $this->repo->getReplicaDB();
435                 $res = $dbr->select(
436                         'uploadstash',
437                         'us_key',
438                         [ 'us_user' => $this->userId ],
439                         __METHOD__
440                 );
441
442                 if ( !is_object( $res ) || $res->numRows() == 0 ) {
443                         // nothing to do.
444                         return false;
445                 }
446
447                 // finish the read before starting writes.
448                 $keys = [];
449                 foreach ( $res as $row ) {
450                         array_push( $keys, $row->us_key );
451                 }
452
453                 return $keys;
454         }
455
456         /**
457          * Find or guess extension -- ensuring that our extension matches our MIME type.
458          * Since these files are constructed from php tempnames they may not start off
459          * with an extension.
460          * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
461          * uploads versus the desired filename. Maybe we can get that passed to us...
462          * @param string $path
463          * @throws UploadStashFileException
464          * @return string
465          */
466         public static function getExtensionForPath( $path ) {
467                 global $wgFileBlacklist;
468                 // Does this have an extension?
469                 $n = strrpos( $path, '.' );
470                 $extension = null;
471                 if ( $n !== false ) {
472                         $extension = $n ? substr( $path, $n + 1 ) : '';
473                 } else {
474                         // If not, assume that it should be related to the MIME type of the original file.
475                         $magic = MimeMagic::singleton();
476                         $mimeType = $magic->guessMimeType( $path );
477                         $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
478                         if ( count( $extensions ) ) {
479                                 $extension = $extensions[0];
480                         }
481                 }
482
483                 if ( is_null( $extension ) ) {
484                         throw new UploadStashFileException( "extension is null" );
485                 }
486
487                 $extension = File::normalizeExtension( $extension );
488                 if ( in_array( $extension, $wgFileBlacklist ) ) {
489                         // The file should already be checked for being evil.
490                         // However, if somehow we got here, we definitely
491                         // don't want to give it an extension of .php and
492                         // put it in a web accesible directory.
493                         return '';
494                 }
495
496                 return $extension;
497         }
498
499         /**
500          * Helper function: do the actual database query to fetch file metadata.
501          *
502          * @param string $key
503          * @param int $readFromDB Constant (default: DB_REPLICA)
504          * @return bool
505          */
506         protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA ) {
507                 // populate $fileMetadata[$key]
508                 $dbr = null;
509                 if ( $readFromDB === DB_MASTER ) {
510                         // sometimes reading from the master is necessary, if there's replication lag.
511                         $dbr = $this->repo->getMasterDB();
512                 } else {
513                         $dbr = $this->repo->getReplicaDB();
514                 }
515
516                 $row = $dbr->selectRow(
517                         'uploadstash',
518                         '*',
519                         [ 'us_key' => $key ],
520                         __METHOD__
521                 );
522
523                 if ( !is_object( $row ) ) {
524                         // key wasn't present in the database. this will happen sometimes.
525                         return false;
526                 }
527
528                 $this->fileMetadata[$key] = (array)$row;
529                 $this->fileMetadata[$key]['us_props'] = $dbr->decodeBlob( $row->us_props );
530
531                 return true;
532         }
533
534         /**
535          * Helper function: Initialize the UploadStashFile for a given file.
536          *
537          * @param string $key Key under which to store the object
538          * @throws UploadStashZeroLengthFileException
539          * @return bool
540          */
541         protected function initFile( $key ) {
542                 $file = new UploadStashFile( $this->repo, $this->fileMetadata[$key]['us_path'], $key );
543                 if ( $file->getSize() === 0 ) {
544                         throw new UploadStashZeroLengthFileException( "File is zero length" );
545                 }
546                 $this->files[$key] = $file;
547
548                 return true;
549         }
550 }
551
552 class UploadStashFile extends UnregisteredLocalFile {
553         private $fileKey;
554         private $urlName;
555         protected $url;
556
557         /**
558          * A LocalFile wrapper around a file that has been temporarily stashed,
559          * so we can do things like create thumbnails for it. Arguably
560          * UnregisteredLocalFile should be handling its own file repo but that
561          * class is a bit retarded currently.
562          *
563          * @param FileRepo $repo Repository where we should find the path
564          * @param string $path Path to file
565          * @param string $key Key to store the path and any stashed data under
566          * @throws UploadStashBadPathException
567          * @throws UploadStashFileNotFoundException
568          */
569         public function __construct( $repo, $path, $key ) {
570                 $this->fileKey = $key;
571
572                 // resolve mwrepo:// urls
573                 if ( $repo->isVirtualUrl( $path ) ) {
574                         $path = $repo->resolveVirtualUrl( $path );
575                 } else {
576                         // check if path appears to be sane, no parent traversals,
577                         // and is in this repo's temp zone.
578                         $repoTempPath = $repo->getZonePath( 'temp' );
579                         if ( ( !$repo->validateFilename( $path ) ) ||
580                                 ( strpos( $path, $repoTempPath ) !== 0 )
581                         ) {
582                                 wfDebug( "UploadStash: tried to construct an UploadStashFile "
583                                         . "from a file that should already exist at '$path', but path is not valid\n" );
584                                 throw new UploadStashBadPathException( 'path is not valid' );
585                         }
586
587                         // check if path exists! and is a plain file.
588                         if ( !$repo->fileExists( $path ) ) {
589                                 wfDebug( "UploadStash: tried to construct an UploadStashFile from "
590                                         . "a file that should already exist at '$path', but path is not found\n" );
591                                 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
592                         }
593                 }
594
595                 parent::__construct( false, $repo, $path, false );
596
597                 $this->name = basename( $this->path );
598         }
599
600         /**
601          * A method needed by the file transforming and scaling routines in File.php
602          * We do not necessarily care about doing the description at this point
603          * However, we also can't return the empty string, as the rest of MediaWiki
604          * demands this (and calls to imagemagick convert require it to be there)
605          *
606          * @return string Dummy value
607          */
608         public function getDescriptionUrl() {
609                 return $this->getUrl();
610         }
611
612         /**
613          * Get the path for the thumbnail (actually any transformation of this file)
614          * The actual argument is the result of thumbName although we seem to have
615          * buggy code elsewhere that expects a boolean 'suffix'
616          *
617          * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ),
618          *   or false to just get the path
619          * @return string Path thumbnail should take on filesystem, or containing
620          *   directory if thumbname is false
621          */
622         public function getThumbPath( $thumbName = false ) {
623                 $path = dirname( $this->path );
624                 if ( $thumbName !== false ) {
625                         $path .= "/$thumbName";
626                 }
627
628                 return $path;
629         }
630
631         /**
632          * Return the file/url base name of a thumbnail with the specified parameters.
633          * We override this because we want to use the pretty url name instead of the
634          * ugly file name.
635          *
636          * @param array $params Handler-specific parameters
637          * @param int $flags Bitfield that supports THUMB_* constants
638          * @return string|null Base name for URL, like '120px-12345.jpg', or null if there is no handler
639          */
640         function thumbName( $params, $flags = 0 ) {
641                 return $this->generateThumbName( $this->getUrlName(), $params );
642         }
643
644         /**
645          * Helper function -- given a 'subpage', return the local URL,
646          * e.g. /wiki/Special:UploadStash/subpage
647          * @param string $subPage
648          * @return string Local URL for this subpage in the Special:UploadStash space.
649          */
650         private function getSpecialUrl( $subPage ) {
651                 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
652         }
653
654         /**
655          * Get a URL to access the thumbnail
656          * This is required because the model of how files work requires that
657          * the thumbnail urls be predictable. However, in our model the URL is
658          * not based on the filename (that's hidden in the db)
659          *
660          * @param string $thumbName Basename of thumbnail file -- however, we don't
661          *   want to use the file exactly
662          * @return string URL to access thumbnail, or URL with partial path
663          */
664         public function getThumbUrl( $thumbName = false ) {
665                 wfDebug( __METHOD__ . " getting for $thumbName \n" );
666
667                 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
668         }
669
670         /**
671          * The basename for the URL, which we want to not be related to the filename.
672          * Will also be used as the lookup key for a thumbnail file.
673          *
674          * @return string Base url name, like '120px-123456.jpg'
675          */
676         public function getUrlName() {
677                 if ( !$this->urlName ) {
678                         $this->urlName = $this->fileKey;
679                 }
680
681                 return $this->urlName;
682         }
683
684         /**
685          * Return the URL of the file, if for some reason we wanted to download it
686          * We tend not to do this for the original file, but we do want thumb icons
687          *
688          * @return string Url
689          */
690         public function getUrl() {
691                 if ( !isset( $this->url ) ) {
692                         $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
693                 }
694
695                 return $this->url;
696         }
697
698         /**
699          * Parent classes use this method, for no obvious reason, to return the path
700          * (relative to wiki root, I assume). But with this class, the URL is
701          * unrelated to the path.
702          *
703          * @return string Url
704          */
705         public function getFullUrl() {
706                 return $this->getUrl();
707         }
708
709         /**
710          * Getter for file key (the unique id by which this file's location &
711          * metadata is stored in the db)
712          *
713          * @return string File key
714          */
715         public function getFileKey() {
716                 return $this->fileKey;
717         }
718
719         /**
720          * Remove the associated temporary file
721          * @return status Success
722          */
723         public function remove() {
724                 if ( !$this->repo->fileExists( $this->path ) ) {
725                         // Maybe the file's already been removed? This could totally happen in UploadBase.
726                         return true;
727                 }
728
729                 return $this->repo->freeTemp( $this->path );
730         }
731
732         public function exists() {
733                 return $this->repo->fileExists( $this->path );
734         }
735 }
736
737 class UploadStashException extends MWException {
738 }
739
740 class UploadStashFileNotFoundException extends UploadStashException {
741 }
742
743 class UploadStashBadPathException extends UploadStashException {
744 }
745
746 class UploadStashFileException extends UploadStashException {
747 }
748
749 class UploadStashZeroLengthFileException extends UploadStashException {
750 }
751
752 class UploadStashNotLoggedInException extends UploadStashException {
753 }
754
755 class UploadStashWrongOwnerException extends UploadStashException {
756 }
757
758 class UploadStashNoSuchKeyException extends UploadStashException {
759 }