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