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