r110979: removed implode() call and format the message as plaintext, as any HTML...
[lhc/web/wiklou.git] / includes / upload / UploadStash.php
1 <?php
2 /**
3 * UploadStash is intended to accomplish a few things:
4 * - enable applications to temporarily stash files without publishing them to the wiki.
5 * - Several parts of MediaWiki do this in similar ways: UploadBase, UploadWizard, and FirefoggChunkedExtension
6 * And there are several that reimplement stashing from scratch, in idiosyncratic ways. The idea is to unify them all here.
7 * Mostly all of them are the same except for storing some custom fields, which we subsume into the data array.
8 * - enable applications to find said files later, as long as the db table or temp files haven't been purged.
9 * - enable the uploading user (and *ONLY* the uploading user) to access said files, and thumbnails of said files, via a URL.
10 * We accomplish this using a database table, with ownership checking as you might expect. See SpecialUploadStash, which
11 * implements a web interface to some files stored this way.
12 *
13 * UploadStash right now is *mostly* intended to show you one user's slice of the entire stash. The user parameter is only optional
14 * because there are few cases where we clean out the stash from an automated script. In the future we might refactor this.
15 *
16 * UploadStash represents the entire stash of temporary files.
17 * UploadStashFile is a filestore for the actual physical disk files.
18 * UploadFromStash extends UploadBase, and represents a single stashed file as it is moved from the stash to the regular file repository
19 *
20 * @ingroup Upload
21 */
22 class UploadStash {
23
24 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
25 const KEY_FORMAT_REGEX = '/^[\w-\.]+\.\w*$/';
26
27 /**
28 * repository that this uses to store temp files
29 * public because we sometimes need to get a LocalFile within the same repo.
30 *
31 * @var LocalRepo
32 */
33 public $repo;
34
35 // array of initialized repo objects
36 protected $files = array();
37
38 // cache of the file metadata that's stored in the database
39 protected $fileMetadata = array();
40
41 // fileprops cache
42 protected $fileProps = array();
43
44 // current user
45 protected $user, $userId, $isLoggedIn;
46
47 /**
48 * Represents a temporary filestore, with metadata in the database.
49 * Designed to be compatible with the session stashing code in UploadBase (should replace it eventually)
50 *
51 * @param $repo FileRepo
52 */
53 public function __construct( FileRepo $repo, $user = null ) {
54 // this might change based on wiki's configuration.
55 $this->repo = $repo;
56
57 // if a user was passed, use it. otherwise, attempt to use the global.
58 // this keeps FileRepo from breaking when it creates an UploadStash object
59 if ( $user ) {
60 $this->user = $user;
61 } else {
62 global $wgUser;
63 $this->user = $wgUser;
64 }
65
66 if ( is_object( $this->user ) ) {
67 $this->userId = $this->user->getId();
68 $this->isLoggedIn = $this->user->isLoggedIn();
69 }
70 }
71
72 /**
73 * Get a file and its metadata from the stash.
74 * The noAuth param is a bit janky but is required for automated scripts which clean out the stash.
75 *
76 * @param $key String: key under which file information is stored
77 * @param $noAuth Boolean (optional) Don't check authentication. Used by maintenance scripts.
78 * @throws UploadStashFileNotFoundException
79 * @throws UploadStashNotLoggedInException
80 * @throws UploadStashWrongOwnerException
81 * @throws UploadStashBadPathException
82 * @return UploadStashFile
83 */
84 public function getFile( $key, $noAuth = false ) {
85
86 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
87 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
88 }
89
90 if ( !$noAuth ) {
91 if ( !$this->isLoggedIn ) {
92 throw new UploadStashNotLoggedInException( __METHOD__ . ' No user is logged in, files must belong to users' );
93 }
94 }
95
96 if ( !isset( $this->fileMetadata[$key] ) ) {
97 if ( !$this->fetchFileMetadata( $key ) ) {
98 // If nothing was received, it's likely due to replication lag. Check the master to see if the record is there.
99 $this->fetchFileMetadata( $key, DB_MASTER );
100 }
101
102 if ( !isset( $this->fileMetadata[$key] ) ) {
103 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
104 }
105
106 // create $this->files[$key]
107 $this->initFile( $key );
108
109 // fetch fileprops
110 $path = $this->fileMetadata[$key]['us_path'];
111 $this->fileProps[$key] = $this->repo->getFileProps( $path );
112 }
113
114 if ( ! $this->files[$key]->exists() ) {
115 wfDebug( __METHOD__ . " tried to get file at $key, but it doesn't exist\n" );
116 throw new UploadStashBadPathException( "path doesn't exist" );
117 }
118
119 if ( !$noAuth ) {
120 if ( $this->fileMetadata[$key]['us_user'] != $this->userId ) {
121 throw new UploadStashWrongOwnerException( "This file ($key) doesn't belong to the current user." );
122 }
123 }
124
125 return $this->files[$key];
126 }
127
128 /**
129 * Getter for file metadata.
130 *
131 * @param key String: key under which file information is stored
132 * @return Array
133 */
134 public function getMetadata ( $key ) {
135 $this->getFile( $key );
136 return $this->fileMetadata[$key];
137 }
138
139 /**
140 * Getter for fileProps
141 *
142 * @param key String: key under which file information is stored
143 * @return Array
144 */
145 public function getFileProps ( $key ) {
146 $this->getFile( $key );
147 return $this->fileProps[$key];
148 }
149
150 /**
151 * Stash a file in a temp directory and record that we did this in the database, along with other metadata.
152 *
153 * @param $path String: path to file you want stashed
154 * @param $sourceType String: the type of upload that generated this file (currently, I believe, 'file' or null)
155 * @throws UploadStashBadPathException
156 * @throws UploadStashFileException
157 * @throws UploadStashNotLoggedInException
158 * @return UploadStashFile: file, or null on failure
159 */
160 public function stashFile( $path, $sourceType = null ) {
161 if ( ! file_exists( $path ) ) {
162 wfDebug( __METHOD__ . " tried to stash file at '$path', but it doesn't exist\n" );
163 throw new UploadStashBadPathException( "path doesn't exist" );
164 }
165 $fileProps = FSFile::getPropsFromPath( $path );
166 wfDebug( __METHOD__ . " stashing file at '$path'\n" );
167
168 // we will be initializing from some tmpnam files that don't have extensions.
169 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
170 $extension = self::getExtensionForPath( $path );
171 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
172 $pathWithGoodExtension = "$path.$extension";
173 if ( ! rename( $path, $pathWithGoodExtension ) ) {
174 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
175 }
176 $path = $pathWithGoodExtension;
177 }
178
179 // If no key was supplied, make one. a mysql insertid would be totally reasonable here, except
180 // that for historical reasons, the key is this random thing instead. At least it's not guessable.
181 //
182 // some things that when combined will make a suitably unique key.
183 // see: http://www.jwz.org/doc/mid.html
184 list ($usec, $sec) = explode( ' ', microtime() );
185 $usec = substr($usec, 2);
186 $key = wfBaseConvert( $sec . $usec, 10, 36 ) . '.' .
187 wfBaseConvert( mt_rand(), 10, 36 ) . '.'.
188 $this->userId . '.' .
189 $extension;
190
191 $this->fileProps[$key] = $fileProps;
192
193 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
194 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
195 }
196
197 wfDebug( __METHOD__ . " key for '$path': $key\n" );
198
199 // if not already in a temporary area, put it there
200 $storeStatus = $this->repo->storeTemp( basename( $path ), $path );
201
202 if ( ! $storeStatus->isOK() ) {
203 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
204 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
205 // This is a bit lame, as we may have more info in the $storeStatus and we're throwing it away, but to fix it means
206 // redesigning API errors significantly.
207 // $storeStatus->value just contains the virtual URL (if anything) which is probably useless to the caller
208 $error = $storeStatus->getErrorsArray();
209 $error = reset( $error );
210 if ( ! count( $error ) ) {
211 $error = $storeStatus->getWarningsArray();
212 $error = reset( $error );
213 if ( ! count( $error ) ) {
214 $error = array( 'unknown', 'no error recorded' );
215 }
216 }
217 // at this point, $error should contain the single "most important" error, plus any parameters.
218 throw new UploadStashFileException( "Error storing file in '$path': " . wfMessage( $error )->text() );
219 }
220 $stashPath = $storeStatus->value;
221
222 // fetch the current user ID
223 if ( !$this->isLoggedIn ) {
224 throw new UploadStashNotLoggedInException( __METHOD__ . ' No user is logged in, files must belong to users' );
225 }
226
227 // insert the file metadata into the db.
228 wfDebug( __METHOD__ . " inserting $stashPath under $key\n" );
229 $dbw = $this->repo->getMasterDb();
230
231 $this->fileMetadata[$key] = array(
232 'us_id' => $dbw->nextSequenceValue( 'uploadstash_us_id_seq' ),
233 'us_user' => $this->userId,
234 'us_key' => $key,
235 'us_orig_path' => $path,
236 'us_path' => $stashPath, // virtual URL
237 'us_size' => $fileProps['size'],
238 'us_sha1' => $fileProps['sha1'],
239 'us_mime' => $fileProps['mime'],
240 'us_media_type' => $fileProps['media_type'],
241 'us_image_width' => $fileProps['width'],
242 'us_image_height' => $fileProps['height'],
243 'us_image_bits' => $fileProps['bits'],
244 'us_source_type' => $sourceType,
245 'us_timestamp' => $dbw->timestamp(),
246 'us_status' => 'finished'
247 );
248
249 $dbw->insert(
250 'uploadstash',
251 $this->fileMetadata[$key],
252 __METHOD__
253 );
254
255 // store the insertid in the class variable so immediate retrieval (possibly laggy) isn't necesary.
256 $this->fileMetadata[$key]['us_id'] = $dbw->insertId();
257
258 # create the UploadStashFile object for this file.
259 $this->initFile( $key );
260
261 return $this->getFile( $key );
262 }
263
264 /**
265 * Remove all files from the stash.
266 * Does not clean up files in the repo, just the record of them.
267 *
268 * @throws UploadStashNotLoggedInException
269 * @return boolean: success
270 */
271 public function clear() {
272 if ( !$this->isLoggedIn ) {
273 throw new UploadStashNotLoggedInException( __METHOD__ . ' No user is logged in, files must belong to users' );
274 }
275
276 wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->userId . "\n" );
277 $dbw = $this->repo->getMasterDb();
278 $dbw->delete(
279 'uploadstash',
280 array( 'us_user' => $this->userId ),
281 __METHOD__
282 );
283
284 # destroy objects.
285 $this->files = array();
286 $this->fileMetadata = array();
287
288 return true;
289 }
290
291 /**
292 * Remove a particular file from the stash. Also removes it from the repo.
293 *
294 * @throws UploadStashNotLoggedInException
295 * @throws UploadStashWrongOwnerException
296 * @return boolean: success
297 */
298 public function removeFile( $key ) {
299 if ( !$this->isLoggedIn ) {
300 throw new UploadStashNotLoggedInException( __METHOD__ . ' No user is logged in, files must belong to users' );
301 }
302
303 $dbw = $this->repo->getMasterDb();
304
305 // this is a cheap query. it runs on the master so that this function still works when there's lag.
306 // it won't be called all that often.
307 $row = $dbw->selectRow(
308 'uploadstash',
309 'us_user',
310 array( 'us_key' => $key ),
311 __METHOD__
312 );
313
314 if( !$row ) {
315 throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
316 }
317
318 if ( $row->us_user != $this->userId ) {
319 throw new UploadStashWrongOwnerException( "Can't delete: the file ($key) doesn't belong to this user." );
320 }
321
322 return $this->removeFileNoAuth( $key );
323 }
324
325
326 /**
327 * Remove a file (see removeFile), but doesn't check ownership first.
328 *
329 * @return boolean: success
330 */
331 public function removeFileNoAuth( $key ) {
332 wfDebug( __METHOD__ . " clearing row $key\n" );
333
334 $dbw = $this->repo->getMasterDb();
335
336 // this gets its own transaction since it's called serially by the cleanupUploadStash maintenance script
337 $dbw->begin( __METHOD__ );
338 $dbw->delete(
339 'uploadstash',
340 array( 'us_key' => $key ),
341 __METHOD__
342 );
343 $dbw->commit( __METHOD__ );
344
345 // TODO: look into UnregisteredLocalFile and find out why the rv here is sometimes wrong (false when file was removed)
346 // for now, ignore.
347 $this->files[$key]->remove();
348
349 unset( $this->files[$key] );
350 unset( $this->fileMetadata[$key] );
351
352 return true;
353 }
354
355 /**
356 * List all files in the stash.
357 *
358 * @throws UploadStashNotLoggedInException
359 * @return Array
360 */
361 public function listFiles() {
362 if ( !$this->isLoggedIn ) {
363 throw new UploadStashNotLoggedInException( __METHOD__ . ' No user is logged in, files must belong to users' );
364 }
365
366 $dbr = $this->repo->getSlaveDb();
367 $res = $dbr->select(
368 'uploadstash',
369 'us_key',
370 array( 'us_user' => $this->userId ),
371 __METHOD__
372 );
373
374 if ( !is_object( $res ) || $res->numRows() == 0 ) {
375 // nothing to do.
376 return false;
377 }
378
379 // finish the read before starting writes.
380 $keys = array();
381 foreach ( $res as $row ) {
382 array_push( $keys, $row->us_key );
383 }
384
385 return $keys;
386 }
387
388 /**
389 * Find or guess extension -- ensuring that our extension matches our mime type.
390 * Since these files are constructed from php tempnames they may not start off
391 * with an extension.
392 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
393 * uploads versus the desired filename. Maybe we can get that passed to us...
394 */
395 public static function getExtensionForPath( $path ) {
396 // Does this have an extension?
397 $n = strrpos( $path, '.' );
398 $extension = null;
399 if ( $n !== false ) {
400 $extension = $n ? substr( $path, $n + 1 ) : '';
401 } else {
402 // If not, assume that it should be related to the mime type of the original file.
403 $magic = MimeMagic::singleton();
404 $mimeType = $magic->guessMimeType( $path );
405 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
406 if ( count( $extensions ) ) {
407 $extension = $extensions[0];
408 }
409 }
410
411 if ( is_null( $extension ) ) {
412 throw new UploadStashFileException( "extension is null" );
413 }
414
415 return File::normalizeExtension( $extension );
416 }
417
418 /**
419 * Helper function: do the actual database query to fetch file metadata.
420 *
421 * @param $key String: key
422 * @return boolean
423 */
424 protected function fetchFileMetadata( $key, $readFromDB = DB_SLAVE ) {
425 // populate $fileMetadata[$key]
426 $dbr = null;
427 if( $readFromDB === DB_MASTER ) {
428 // sometimes reading from the master is necessary, if there's replication lag.
429 $dbr = $this->repo->getMasterDb();
430 } else {
431 $dbr = $this->repo->getSlaveDb();
432 }
433
434 $row = $dbr->selectRow(
435 'uploadstash',
436 '*',
437 array( 'us_key' => $key ),
438 __METHOD__
439 );
440
441 if ( !is_object( $row ) ) {
442 // key wasn't present in the database. this will happen sometimes.
443 return false;
444 }
445
446 $this->fileMetadata[$key] = (array)$row;
447
448 return true;
449 }
450
451 /**
452 * Helper function: Initialize the UploadStashFile for a given file.
453 *
454 * @param $path String: path to file
455 * @param $key String: key under which to store the object
456 * @throws UploadStashZeroLengthFileException
457 * @return bool
458 */
459 protected function initFile( $key ) {
460 $file = new UploadStashFile( $this->repo, $this->fileMetadata[$key]['us_path'], $key );
461 if ( $file->getSize() === 0 ) {
462 throw new UploadStashZeroLengthFileException( "File is zero length" );
463 }
464 $this->files[$key] = $file;
465 return true;
466 }
467 }
468
469 class UploadStashFile extends UnregisteredLocalFile {
470 private $fileKey;
471 private $urlName;
472 protected $url;
473
474 /**
475 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
476 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
477 *
478 * @param $repo FileRepo: repository where we should find the path
479 * @param $path String: path to file
480 * @param $key String: key to store the path and any stashed data under
481 * @throws UploadStashBadPathException
482 * @throws UploadStashFileNotFoundException
483 */
484 public function __construct( $repo, $path, $key ) {
485 $this->fileKey = $key;
486
487 // resolve mwrepo:// urls
488 if ( $repo->isVirtualUrl( $path ) ) {
489 $path = $repo->resolveVirtualUrl( $path );
490 } else {
491
492 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
493 $repoTempPath = $repo->getZonePath( 'temp' );
494 if ( ( ! $repo->validateFilename( $path ) ) ||
495 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
496 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
497 throw new UploadStashBadPathException( 'path is not valid' );
498 }
499
500 // check if path exists! and is a plain file.
501 if ( ! $repo->fileExists( $path, FileRepo::FILES_ONLY ) ) {
502 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
503 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
504 }
505 }
506
507 parent::__construct( false, $repo, $path, false );
508
509 $this->name = basename( $this->path );
510 }
511
512 /**
513 * A method needed by the file transforming and scaling routines in File.php
514 * We do not necessarily care about doing the description at this point
515 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
516 * convert require it to be there)
517 *
518 * @return String: dummy value
519 */
520 public function getDescriptionUrl() {
521 return $this->getUrl();
522 }
523
524 /**
525 * Get the path for the thumbnail (actually any transformation of this file)
526 * The actual argument is the result of thumbName although we seem to have
527 * buggy code elsewhere that expects a boolean 'suffix'
528 *
529 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
530 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
531 */
532 public function getThumbPath( $thumbName = false ) {
533 $path = dirname( $this->path );
534 if ( $thumbName !== false ) {
535 $path .= "/$thumbName";
536 }
537 return $path;
538 }
539
540 /**
541 * Return the file/url base name of a thumbnail with the specified parameters.
542 * We override this because we want to use the pretty url name instead of the
543 * ugly file name.
544 *
545 * @param $params Array: handler-specific parameters
546 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
547 */
548 function thumbName( $params ) {
549 return $this->generateThumbName( $this->getUrlName(), $params );
550 }
551
552 /**
553 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
554 * @param {String} $subPage
555 * @return {String} local URL for this subpage in the Special:UploadStash space.
556 */
557 private function getSpecialUrl( $subPage ) {
558 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
559 }
560
561 /**
562 * Get a URL to access the thumbnail
563 * This is required because the model of how files work requires that
564 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
565 * (that's hidden in the db)
566 *
567 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
568 * @return String: URL to access thumbnail, or URL with partial path
569 */
570 public function getThumbUrl( $thumbName = false ) {
571 wfDebug( __METHOD__ . " getting for $thumbName \n" );
572 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
573 }
574
575 /**
576 * The basename for the URL, which we want to not be related to the filename.
577 * Will also be used as the lookup key for a thumbnail file.
578 *
579 * @return String: base url name, like '120px-123456.jpg'
580 */
581 public function getUrlName() {
582 if ( ! $this->urlName ) {
583 $this->urlName = $this->fileKey;
584 }
585 return $this->urlName;
586 }
587
588 /**
589 * Return the URL of the file, if for some reason we wanted to download it
590 * We tend not to do this for the original file, but we do want thumb icons
591 *
592 * @return String: url
593 */
594 public function getUrl() {
595 if ( !isset( $this->url ) ) {
596 $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
597 }
598 return $this->url;
599 }
600
601 /**
602 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
603 * But with this class, the URL is unrelated to the path.
604 *
605 * @return String: url
606 */
607 public function getFullUrl() {
608 return $this->getUrl();
609 }
610
611 /**
612 * Getter for file key (the unique id by which this file's location & metadata is stored in the db)
613 *
614 * @return String: file key
615 */
616 public function getFileKey() {
617 return $this->fileKey;
618 }
619
620 /**
621 * Remove the associated temporary file
622 * @return Status: success
623 */
624 public function remove() {
625 if ( !$this->repo->fileExists( $this->path, FileRepo::FILES_ONLY ) ) {
626 // Maybe the file's already been removed? This could totally happen in UploadBase.
627 return true;
628 }
629
630 return $this->repo->freeTemp( $this->path );
631 }
632
633 public function exists() {
634 return $this->repo->fileExists( $this->path, FileRepo::FILES_ONLY );
635 }
636
637 }
638
639 class UploadStashNotAvailableException extends MWException {};
640 class UploadStashFileNotFoundException extends MWException {};
641 class UploadStashBadPathException extends MWException {};
642 class UploadStashFileException extends MWException {};
643 class UploadStashZeroLengthFileException extends MWException {};
644 class UploadStashNotLoggedInException extends MWException {};
645 class UploadStashWrongOwnerException extends MWException {};
646 class UploadStashNoSuchKeyException extends MWException {};