Rework Upload*Exception classes to implement ILocalizedException
[lhc/web/wiklou.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( wfMessage( $errorMsg, $error ) );
269 }
270 $stashPath = $storeStatus->value;
271
272 // fetch the current user ID
273 if ( !$this->isLoggedIn ) {
274 throw new UploadStashNotLoggedInException( __METHOD__
275 . ' No user is logged in, files must belong to users' );
276 }
277
278 // insert the file metadata into the db.
279 wfDebug( __METHOD__ . " inserting $stashPath under $key\n" );
280 $dbw = $this->repo->getMasterDB();
281
282 $serializedFileProps = serialize( $fileProps );
283 if ( strlen( $serializedFileProps ) > self::MAX_US_PROPS_SIZE ) {
284 // Database is going to truncate this and make the field invalid.
285 // Prioritize important metadata over file handler metadata.
286 // File handler should be prepared to regenerate invalid metadata if needed.
287 $fileProps['metadata'] = false;
288 $serializedFileProps = serialize( $fileProps );
289 }
290
291 $this->fileMetadata[$key] = [
292 'us_user' => $this->userId,
293 'us_key' => $key,
294 'us_orig_path' => $path,
295 'us_path' => $stashPath, // virtual URL
296 'us_props' => $dbw->encodeBlob( $serializedFileProps ),
297 'us_size' => $fileProps['size'],
298 'us_sha1' => $fileProps['sha1'],
299 'us_mime' => $fileProps['mime'],
300 'us_media_type' => $fileProps['media_type'],
301 'us_image_width' => $fileProps['width'],
302 'us_image_height' => $fileProps['height'],
303 'us_image_bits' => $fileProps['bits'],
304 'us_source_type' => $sourceType,
305 'us_timestamp' => $dbw->timestamp(),
306 'us_status' => 'finished'
307 ];
308
309 $dbw->insert(
310 'uploadstash',
311 $this->fileMetadata[$key],
312 __METHOD__
313 );
314
315 // store the insertid in the class variable so immediate retrieval
316 // (possibly laggy) isn't necesary.
317 $this->fileMetadata[$key]['us_id'] = $dbw->insertId();
318
319 # create the UploadStashFile object for this file.
320 $this->initFile( $key );
321
322 return $this->getFile( $key );
323 }
324
325 /**
326 * Remove all files from the stash.
327 * Does not clean up files in the repo, just the record of them.
328 *
329 * @throws UploadStashNotLoggedInException
330 * @return bool Success
331 */
332 public function clear() {
333 if ( !$this->isLoggedIn ) {
334 throw new UploadStashNotLoggedInException( __METHOD__
335 . ' No user is logged in, files must belong to users' );
336 }
337
338 wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->userId . "\n" );
339 $dbw = $this->repo->getMasterDB();
340 $dbw->delete(
341 'uploadstash',
342 [ 'us_user' => $this->userId ],
343 __METHOD__
344 );
345
346 # destroy objects.
347 $this->files = [];
348 $this->fileMetadata = [];
349
350 return true;
351 }
352
353 /**
354 * Remove a particular file from the stash. Also removes it from the repo.
355 *
356 * @param string $key
357 * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException
358 * @throws UploadStashWrongOwnerException
359 * @return bool Success
360 */
361 public function removeFile( $key ) {
362 if ( !$this->isLoggedIn ) {
363 throw new UploadStashNotLoggedInException( __METHOD__
364 . ' No user is logged in, files must belong to users' );
365 }
366
367 $dbw = $this->repo->getMasterDB();
368
369 // this is a cheap query. it runs on the master so that this function
370 // still works when there's lag. It won't be called all that often.
371 $row = $dbw->selectRow(
372 'uploadstash',
373 'us_user',
374 [ 'us_key' => $key ],
375 __METHOD__
376 );
377
378 if ( !$row ) {
379 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
380 }
381
382 if ( $row->us_user != $this->userId ) {
383 throw new UploadStashWrongOwnerException( "Can't delete: "
384 . "the file ($key) doesn't belong to this user." );
385 }
386
387 return $this->removeFileNoAuth( $key );
388 }
389
390 /**
391 * Remove a file (see removeFile), but doesn't check ownership first.
392 *
393 * @param string $key
394 * @return bool Success
395 */
396 public function removeFileNoAuth( $key ) {
397 wfDebug( __METHOD__ . " clearing row $key\n" );
398
399 // Ensure we have the UploadStashFile loaded for this key
400 $this->getFile( $key, true );
401
402 $dbw = $this->repo->getMasterDB();
403
404 $dbw->delete(
405 'uploadstash',
406 [ 'us_key' => $key ],
407 __METHOD__
408 );
409
410 /** @todo Look into UnregisteredLocalFile and find out why the rv here is
411 * sometimes wrong (false when file was removed). For now, ignore.
412 */
413 $this->files[$key]->remove();
414
415 unset( $this->files[$key] );
416 unset( $this->fileMetadata[$key] );
417
418 return true;
419 }
420
421 /**
422 * List all files in the stash.
423 *
424 * @throws UploadStashNotLoggedInException
425 * @return array
426 */
427 public function listFiles() {
428 if ( !$this->isLoggedIn ) {
429 throw new UploadStashNotLoggedInException( __METHOD__
430 . ' No user is logged in, files must belong to users' );
431 }
432
433 $dbr = $this->repo->getReplicaDB();
434 $res = $dbr->select(
435 'uploadstash',
436 'us_key',
437 [ 'us_user' => $this->userId ],
438 __METHOD__
439 );
440
441 if ( !is_object( $res ) || $res->numRows() == 0 ) {
442 // nothing to do.
443 return false;
444 }
445
446 // finish the read before starting writes.
447 $keys = [];
448 foreach ( $res as $row ) {
449 array_push( $keys, $row->us_key );
450 }
451
452 return $keys;
453 }
454
455 /**
456 * Find or guess extension -- ensuring that our extension matches our MIME type.
457 * Since these files are constructed from php tempnames they may not start off
458 * with an extension.
459 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
460 * uploads versus the desired filename. Maybe we can get that passed to us...
461 * @param string $path
462 * @throws UploadStashFileException
463 * @return string
464 */
465 public static function getExtensionForPath( $path ) {
466 global $wgFileBlacklist;
467 // Does this have an extension?
468 $n = strrpos( $path, '.' );
469 $extension = null;
470 if ( $n !== false ) {
471 $extension = $n ? substr( $path, $n + 1 ) : '';
472 } else {
473 // If not, assume that it should be related to the MIME type of the original file.
474 $magic = MimeMagic::singleton();
475 $mimeType = $magic->guessMimeType( $path );
476 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
477 if ( count( $extensions ) ) {
478 $extension = $extensions[0];
479 }
480 }
481
482 if ( is_null( $extension ) ) {
483 throw new UploadStashFileException( "extension is null" );
484 }
485
486 $extension = File::normalizeExtension( $extension );
487 if ( in_array( $extension, $wgFileBlacklist ) ) {
488 // The file should already be checked for being evil.
489 // However, if somehow we got here, we definitely
490 // don't want to give it an extension of .php and
491 // put it in a web accesible directory.
492 return '';
493 }
494
495 return $extension;
496 }
497
498 /**
499 * Helper function: do the actual database query to fetch file metadata.
500 *
501 * @param string $key
502 * @param int $readFromDB Constant (default: DB_REPLICA)
503 * @return bool
504 */
505 protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA ) {
506 // populate $fileMetadata[$key]
507 $dbr = null;
508 if ( $readFromDB === DB_MASTER ) {
509 // sometimes reading from the master is necessary, if there's replication lag.
510 $dbr = $this->repo->getMasterDB();
511 } else {
512 $dbr = $this->repo->getReplicaDB();
513 }
514
515 $row = $dbr->selectRow(
516 'uploadstash',
517 [
518 'us_user', 'us_key', 'us_orig_path', 'us_path', 'us_props',
519 'us_size', 'us_sha1', 'us_mime', 'us_media_type',
520 'us_image_width', 'us_image_height', 'us_image_bits',
521 'us_source_type', 'us_timestamp', 'us_status',
522 ],
523 [ 'us_key' => $key ],
524 __METHOD__
525 );
526
527 if ( !is_object( $row ) ) {
528 // key wasn't present in the database. this will happen sometimes.
529 return false;
530 }
531
532 $this->fileMetadata[$key] = (array)$row;
533 $this->fileMetadata[$key]['us_props'] = $dbr->decodeBlob( $row->us_props );
534
535 return true;
536 }
537
538 /**
539 * Helper function: Initialize the UploadStashFile for a given file.
540 *
541 * @param string $key Key under which to store the object
542 * @throws UploadStashZeroLengthFileException
543 * @return bool
544 */
545 protected function initFile( $key ) {
546 $file = new UploadStashFile( $this->repo, $this->fileMetadata[$key]['us_path'], $key );
547 if ( $file->getSize() === 0 ) {
548 throw new UploadStashZeroLengthFileException( "File is zero length" );
549 }
550 $this->files[$key] = $file;
551
552 return true;
553 }
554 }
555
556 class UploadStashFile extends UnregisteredLocalFile {
557 private $fileKey;
558 private $urlName;
559 protected $url;
560
561 /**
562 * A LocalFile wrapper around a file that has been temporarily stashed,
563 * so we can do things like create thumbnails for it. Arguably
564 * UnregisteredLocalFile should be handling its own file repo but that
565 * class is a bit retarded currently.
566 *
567 * @param FileRepo $repo Repository where we should find the path
568 * @param string $path Path to file
569 * @param string $key Key to store the path and any stashed data under
570 * @throws UploadStashBadPathException
571 * @throws UploadStashFileNotFoundException
572 */
573 public function __construct( $repo, $path, $key ) {
574 $this->fileKey = $key;
575
576 // resolve mwrepo:// urls
577 if ( $repo->isVirtualUrl( $path ) ) {
578 $path = $repo->resolveVirtualUrl( $path );
579 } else {
580 // check if path appears to be sane, no parent traversals,
581 // and is in this repo's temp zone.
582 $repoTempPath = $repo->getZonePath( 'temp' );
583 if ( ( !$repo->validateFilename( $path ) ) ||
584 ( strpos( $path, $repoTempPath ) !== 0 )
585 ) {
586 wfDebug( "UploadStash: tried to construct an UploadStashFile "
587 . "from a file that should already exist at '$path', but path is not valid\n" );
588 throw new UploadStashBadPathException( 'path is not valid' );
589 }
590
591 // check if path exists! and is a plain file.
592 if ( !$repo->fileExists( $path ) ) {
593 wfDebug( "UploadStash: tried to construct an UploadStashFile from "
594 . "a file that should already exist at '$path', but path is not found\n" );
595 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
596 }
597 }
598
599 parent::__construct( false, $repo, $path, false );
600
601 $this->name = basename( $this->path );
602 }
603
604 /**
605 * A method needed by the file transforming and scaling routines in File.php
606 * We do not necessarily care about doing the description at this point
607 * However, we also can't return the empty string, as the rest of MediaWiki
608 * demands this (and calls to imagemagick convert require it to be there)
609 *
610 * @return string Dummy value
611 */
612 public function getDescriptionUrl() {
613 return $this->getUrl();
614 }
615
616 /**
617 * Get the path for the thumbnail (actually any transformation of this file)
618 * The actual argument is the result of thumbName although we seem to have
619 * buggy code elsewhere that expects a boolean 'suffix'
620 *
621 * @param string $thumbName Name of thumbnail (e.g. "120px-123456.jpg" ),
622 * or false to just get the path
623 * @return string Path thumbnail should take on filesystem, or containing
624 * directory if thumbname is false
625 */
626 public function getThumbPath( $thumbName = false ) {
627 $path = dirname( $this->path );
628 if ( $thumbName !== false ) {
629 $path .= "/$thumbName";
630 }
631
632 return $path;
633 }
634
635 /**
636 * Return the file/url base name of a thumbnail with the specified parameters.
637 * We override this because we want to use the pretty url name instead of the
638 * ugly file name.
639 *
640 * @param array $params Handler-specific parameters
641 * @param int $flags Bitfield that supports THUMB_* constants
642 * @return string|null Base name for URL, like '120px-12345.jpg', or null if there is no handler
643 */
644 function thumbName( $params, $flags = 0 ) {
645 return $this->generateThumbName( $this->getUrlName(), $params );
646 }
647
648 /**
649 * Helper function -- given a 'subpage', return the local URL,
650 * e.g. /wiki/Special:UploadStash/subpage
651 * @param string $subPage
652 * @return string Local URL for this subpage in the Special:UploadStash space.
653 */
654 private function getSpecialUrl( $subPage ) {
655 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
656 }
657
658 /**
659 * Get a URL to access the thumbnail
660 * This is required because the model of how files work requires that
661 * the thumbnail urls be predictable. However, in our model the URL is
662 * not based on the filename (that's hidden in the db)
663 *
664 * @param string $thumbName Basename of thumbnail file -- however, we don't
665 * want to use the file exactly
666 * @return string URL to access thumbnail, or URL with partial path
667 */
668 public function getThumbUrl( $thumbName = false ) {
669 wfDebug( __METHOD__ . " getting for $thumbName \n" );
670
671 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
672 }
673
674 /**
675 * The basename for the URL, which we want to not be related to the filename.
676 * Will also be used as the lookup key for a thumbnail file.
677 *
678 * @return string Base url name, like '120px-123456.jpg'
679 */
680 public function getUrlName() {
681 if ( !$this->urlName ) {
682 $this->urlName = $this->fileKey;
683 }
684
685 return $this->urlName;
686 }
687
688 /**
689 * Return the URL of the file, if for some reason we wanted to download it
690 * We tend not to do this for the original file, but we do want thumb icons
691 *
692 * @return string Url
693 */
694 public function getUrl() {
695 if ( !isset( $this->url ) ) {
696 $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
697 }
698
699 return $this->url;
700 }
701
702 /**
703 * Parent classes use this method, for no obvious reason, to return the path
704 * (relative to wiki root, I assume). But with this class, the URL is
705 * unrelated to the path.
706 *
707 * @return string Url
708 */
709 public function getFullUrl() {
710 return $this->getUrl();
711 }
712
713 /**
714 * Getter for file key (the unique id by which this file's location &
715 * metadata is stored in the db)
716 *
717 * @return string File key
718 */
719 public function getFileKey() {
720 return $this->fileKey;
721 }
722
723 /**
724 * Remove the associated temporary file
725 * @return status Success
726 */
727 public function remove() {
728 if ( !$this->repo->fileExists( $this->path ) ) {
729 // Maybe the file's already been removed? This could totally happen in UploadBase.
730 return true;
731 }
732
733 return $this->repo->freeTemp( $this->path );
734 }
735
736 public function exists() {
737 return $this->repo->fileExists( $this->path );
738 }
739 }
740
741 class UploadStashException extends MWException implements ILocalizedException {
742 /** @var string|array|MessageSpecifier */
743 protected $messageSpec;
744
745 /**
746 * @param string|array|MessageSpecifier $messageSpec See Message::newFromSpecifier
747 * @param int $code Exception code
748 * @param Exception|Throwable $previous The previous exception used for the exception chaining.
749 */
750 public function __construct( $messageSpec, $code = 0, $previous = null ) {
751 $this->messageSpec = $messageSpec;
752
753 $msg = $this->getMessageObject()->text();
754 $msg = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $msg );
755 $msg = Sanitizer::stripAllTags( $msg );
756 parent::__construct( $msg, $code, $previous );
757 }
758
759 public function getMessageObject() {
760 return Message::newFromSpecifier( $this->messageSpec );
761 }
762 }
763
764 class UploadStashFileNotFoundException extends UploadStashException {
765 }
766
767 class UploadStashBadPathException extends UploadStashException {
768 }
769
770 class UploadStashFileException extends UploadStashException {
771 }
772
773 class UploadStashZeroLengthFileException extends UploadStashException {
774 }
775
776 class UploadStashNotLoggedInException extends UploadStashException {
777 }
778
779 class UploadStashWrongOwnerException extends UploadStashException {
780 }
781
782 class UploadStashNoSuchKeyException extends UploadStashException {
783 }