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