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