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