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