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