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