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