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