MediaWiki  1.28.1
UploadStash.php
Go to the documentation of this file.
1 <?php
54 class UploadStash {
55  // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
56  const KEY_FORMAT_REGEX = '/^[\w-\.]+\.\w*$/';
57  const MAX_US_PROPS_SIZE = 65535;
58 
65  public $repo;
66 
67  // array of initialized repo objects
68  protected $files = [];
69 
70  // cache of the file metadata that's stored in the database
71  protected $fileMetadata = [];
72 
73  // fileprops cache
74  protected $fileProps = [];
75 
76  // current user
77  protected $user, $userId, $isLoggedIn;
78 
87  public function __construct( FileRepo $repo, $user = null ) {
88  // this might change based on wiki's configuration.
89  $this->repo = $repo;
90 
91  // if a user was passed, use it. otherwise, attempt to use the global.
92  // this keeps FileRepo from breaking when it creates an UploadStash object
93  if ( $user ) {
94  $this->user = $user;
95  } else {
97  $this->user = $wgUser;
98  }
99 
100  if ( is_object( $this->user ) ) {
101  $this->userId = $this->user->getId();
102  $this->isLoggedIn = $this->user->isLoggedIn();
103  }
104  }
105 
119  public function getFile( $key, $noAuth = false ) {
120  if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
121  throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
122  }
123 
124  if ( !$noAuth && !$this->isLoggedIn ) {
125  throw new UploadStashNotLoggedInException( __METHOD__ .
126  ' No user is logged in, files must belong to users' );
127  }
128 
129  if ( !isset( $this->fileMetadata[$key] ) ) {
130  if ( !$this->fetchFileMetadata( $key ) ) {
131  // If nothing was received, it's likely due to replication lag.
132  // Check the master to see if the record is there.
133  $this->fetchFileMetadata( $key, DB_MASTER );
134  }
135 
136  if ( !isset( $this->fileMetadata[$key] ) ) {
137  throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
138  }
139 
140  // create $this->files[$key]
141  $this->initFile( $key );
142 
143  // fetch fileprops
144  if ( strlen( $this->fileMetadata[$key]['us_props'] ) ) {
145  $this->fileProps[$key] = unserialize( $this->fileMetadata[$key]['us_props'] );
146  } else { // b/c for rows with no us_props
147  wfDebug( __METHOD__ . " fetched props for $key from file\n" );
148  $path = $this->fileMetadata[$key]['us_path'];
149  $this->fileProps[$key] = $this->repo->getFileProps( $path );
150  }
151  }
152 
153  if ( !$this->files[$key]->exists() ) {
154  wfDebug( __METHOD__ . " tried to get file at $key, but it doesn't exist\n" );
155  // @todo Is this not an UploadStashFileNotFoundException case?
156  throw new UploadStashBadPathException( "path doesn't exist" );
157  }
158 
159  if ( !$noAuth ) {
160  if ( $this->fileMetadata[$key]['us_user'] != $this->userId ) {
161  throw new UploadStashWrongOwnerException( "This file ($key) doesn't "
162  . "belong to the current user." );
163  }
164  }
165 
166  return $this->files[$key];
167  }
168 
175  public function getMetadata( $key ) {
176  $this->getFile( $key );
177 
178  return $this->fileMetadata[$key];
179  }
180 
187  public function getFileProps( $key ) {
188  $this->getFile( $key );
189 
190  return $this->fileProps[$key];
191  }
192 
205  public function stashFile( $path, $sourceType = null ) {
206  if ( !is_file( $path ) ) {
207  wfDebug( __METHOD__ . " tried to stash file at '$path', but it doesn't exist\n" );
208  throw new UploadStashBadPathException( "path doesn't exist" );
209  }
210 
211  $mwProps = new MWFileProps( MimeMagic::singleton() );
212  $fileProps = $mwProps->getPropsFromPath( $path, true );
213  wfDebug( __METHOD__ . " stashing file at '$path'\n" );
214 
215  // we will be initializing from some tmpnam files that don't have extensions.
216  // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
217  $extension = self::getExtensionForPath( $path );
218  if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
219  $pathWithGoodExtension = "$path.$extension";
220  } else {
221  $pathWithGoodExtension = $path;
222  }
223 
224  // If no key was supplied, make one. a mysql insertid would be totally
225  // reasonable here, except that for historical reasons, the key is this
226  // random thing instead. At least it's not guessable.
227  // Some things that when combined will make a suitably unique key.
228  // see: http://www.jwz.org/doc/mid.html
229  list( $usec, $sec ) = explode( ' ', microtime() );
230  $usec = substr( $usec, 2 );
231  $key = Wikimedia\base_convert( $sec . $usec, 10, 36 ) . '.' .
232  Wikimedia\base_convert( mt_rand(), 10, 36 ) . '.' .
233  $this->userId . '.' .
234  $extension;
235 
236  $this->fileProps[$key] = $fileProps;
237 
238  if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
239  throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
240  }
241 
242  wfDebug( __METHOD__ . " key for '$path': $key\n" );
243 
244  // if not already in a temporary area, put it there
245  $storeStatus = $this->repo->storeTemp( basename( $pathWithGoodExtension ), $path );
246 
247  if ( !$storeStatus->isOK() ) {
248  // It is a convention in MediaWiki to only return one error per API
249  // exception, even if multiple errors are available. We use reset()
250  // to pick the "first" thing that was wrong, preferring errors to
251  // warnings. This is a bit lame, as we may have more info in the
252  // $storeStatus and we're throwing it away, but to fix it means
253  // redesigning API errors significantly.
254  // $storeStatus->value just contains the virtual URL (if anything)
255  // which is probably useless to the caller.
256  $error = $storeStatus->getErrorsArray();
257  $error = reset( $error );
258  if ( !count( $error ) ) {
259  $error = $storeStatus->getWarningsArray();
260  $error = reset( $error );
261  if ( !count( $error ) ) {
262  $error = [ 'unknown', 'no error recorded' ];
263  }
264  }
265  // At this point, $error should contain the single "most important"
266  // error, plus any parameters.
267  $errorMsg = array_shift( $error );
268  throw new UploadStashFileException( "Error storing file in '$path': "
269  . wfMessage( $errorMsg, $error )->text() );
270  }
271  $stashPath = $storeStatus->value;
272 
273  // fetch the current user ID
274  if ( !$this->isLoggedIn ) {
275  throw new UploadStashNotLoggedInException( __METHOD__
276  . ' No user is logged in, files must belong to users' );
277  }
278 
279  // insert the file metadata into the db.
280  wfDebug( __METHOD__ . " inserting $stashPath under $key\n" );
281  $dbw = $this->repo->getMasterDB();
282 
283  $serializedFileProps = serialize( $fileProps );
284  if ( strlen( $serializedFileProps ) > self::MAX_US_PROPS_SIZE ) {
285  // Database is going to truncate this and make the field invalid.
286  // Prioritize important metadata over file handler metadata.
287  // File handler should be prepared to regenerate invalid metadata if needed.
288  $fileProps['metadata'] = false;
289  $serializedFileProps = serialize( $fileProps );
290  }
291 
292  $this->fileMetadata[$key] = [
293  'us_id' => $dbw->nextSequenceValue( 'uploadstash_us_id_seq' ),
294  'us_user' => $this->userId,
295  'us_key' => $key,
296  'us_orig_path' => $path,
297  'us_path' => $stashPath, // virtual URL
298  'us_props' => $dbw->encodeBlob( $serializedFileProps ),
299  'us_size' => $fileProps['size'],
300  'us_sha1' => $fileProps['sha1'],
301  'us_mime' => $fileProps['mime'],
302  'us_media_type' => $fileProps['media_type'],
303  'us_image_width' => $fileProps['width'],
304  'us_image_height' => $fileProps['height'],
305  'us_image_bits' => $fileProps['bits'],
306  'us_source_type' => $sourceType,
307  'us_timestamp' => $dbw->timestamp(),
308  'us_status' => 'finished'
309  ];
310 
311  $dbw->insert(
312  'uploadstash',
313  $this->fileMetadata[$key],
314  __METHOD__
315  );
316 
317  // store the insertid in the class variable so immediate retrieval
318  // (possibly laggy) isn't necesary.
319  $this->fileMetadata[$key]['us_id'] = $dbw->insertId();
320 
321  # create the UploadStashFile object for this file.
322  $this->initFile( $key );
323 
324  return $this->getFile( $key );
325  }
326 
334  public function clear() {
335  if ( !$this->isLoggedIn ) {
336  throw new UploadStashNotLoggedInException( __METHOD__
337  . ' No user is logged in, files must belong to users' );
338  }
339 
340  wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->userId . "\n" );
341  $dbw = $this->repo->getMasterDB();
342  $dbw->delete(
343  'uploadstash',
344  [ 'us_user' => $this->userId ],
345  __METHOD__
346  );
347 
348  # destroy objects.
349  $this->files = [];
350  $this->fileMetadata = [];
351 
352  return true;
353  }
354 
363  public function removeFile( $key ) {
364  if ( !$this->isLoggedIn ) {
365  throw new UploadStashNotLoggedInException( __METHOD__
366  . ' No user is logged in, files must belong to users' );
367  }
368 
369  $dbw = $this->repo->getMasterDB();
370 
371  // this is a cheap query. it runs on the master so that this function
372  // still works when there's lag. It won't be called all that often.
373  $row = $dbw->selectRow(
374  'uploadstash',
375  'us_user',
376  [ 'us_key' => $key ],
377  __METHOD__
378  );
379 
380  if ( !$row ) {
381  throw new UploadStashNoSuchKeyException( "No such key ($key), cannot remove" );
382  }
383 
384  if ( $row->us_user != $this->userId ) {
385  throw new UploadStashWrongOwnerException( "Can't delete: "
386  . "the file ($key) doesn't belong to this user." );
387  }
388 
389  return $this->removeFileNoAuth( $key );
390  }
391 
398  public function removeFileNoAuth( $key ) {
399  wfDebug( __METHOD__ . " clearing row $key\n" );
400 
401  // Ensure we have the UploadStashFile loaded for this key
402  $this->getFile( $key, true );
403 
404  $dbw = $this->repo->getMasterDB();
405 
406  $dbw->delete(
407  'uploadstash',
408  [ 'us_key' => $key ],
409  __METHOD__
410  );
411 
415  $this->files[$key]->remove();
416 
417  unset( $this->files[$key] );
418  unset( $this->fileMetadata[$key] );
419 
420  return true;
421  }
422 
429  public function listFiles() {
430  if ( !$this->isLoggedIn ) {
431  throw new UploadStashNotLoggedInException( __METHOD__
432  . ' No user is logged in, files must belong to users' );
433  }
434 
435  $dbr = $this->repo->getSlaveDB();
436  $res = $dbr->select(
437  'uploadstash',
438  'us_key',
439  [ 'us_user' => $this->userId ],
440  __METHOD__
441  );
442 
443  if ( !is_object( $res ) || $res->numRows() == 0 ) {
444  // nothing to do.
445  return false;
446  }
447 
448  // finish the read before starting writes.
449  $keys = [];
450  foreach ( $res as $row ) {
451  array_push( $keys, $row->us_key );
452  }
453 
454  return $keys;
455  }
456 
467  public static function getExtensionForPath( $path ) {
469  // Does this have an extension?
470  $n = strrpos( $path, '.' );
471  $extension = null;
472  if ( $n !== false ) {
473  $extension = $n ? substr( $path, $n + 1 ) : '';
474  } else {
475  // If not, assume that it should be related to the MIME type of the original file.
476  $magic = MimeMagic::singleton();
477  $mimeType = $magic->guessMimeType( $path );
478  $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
479  if ( count( $extensions ) ) {
480  $extension = $extensions[0];
481  }
482  }
483 
484  if ( is_null( $extension ) ) {
485  throw new UploadStashFileException( "extension is null" );
486  }
487 
488  $extension = File::normalizeExtension( $extension );
489  if ( in_array( $extension, $wgFileBlacklist ) ) {
490  // The file should already be checked for being evil.
491  // However, if somehow we got here, we definitely
492  // don't want to give it an extension of .php and
493  // put it in a web accesible directory.
494  return '';
495  }
496 
497  return $extension;
498  }
499 
507  protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA ) {
508  // populate $fileMetadata[$key]
509  $dbr = null;
510  if ( $readFromDB === DB_MASTER ) {
511  // sometimes reading from the master is necessary, if there's replication lag.
512  $dbr = $this->repo->getMasterDB();
513  } else {
514  $dbr = $this->repo->getSlaveDB();
515  }
516 
517  $row = $dbr->selectRow(
518  'uploadstash',
519  '*',
520  [ 'us_key' => $key ],
521  __METHOD__
522  );
523 
524  if ( !is_object( $row ) ) {
525  // key wasn't present in the database. this will happen sometimes.
526  return false;
527  }
528 
529  $this->fileMetadata[$key] = (array)$row;
530  $this->fileMetadata[$key]['us_props'] = $dbr->decodeBlob( $row->us_props );
531 
532  return true;
533  }
534 
542  protected function initFile( $key ) {
543  $file = new UploadStashFile( $this->repo, $this->fileMetadata[$key]['us_path'], $key );
544  if ( $file->getSize() === 0 ) {
545  throw new UploadStashZeroLengthFileException( "File is zero length" );
546  }
547  $this->files[$key] = $file;
548 
549  return true;
550  }
551 }
552 
554  private $fileKey;
555  private $urlName;
556  protected $url;
557 
570  public function __construct( $repo, $path, $key ) {
571  $this->fileKey = $key;
572 
573  // resolve mwrepo:// urls
574  if ( $repo->isVirtualUrl( $path ) ) {
576  } else {
577  // check if path appears to be sane, no parent traversals,
578  // and is in this repo's temp zone.
579  $repoTempPath = $repo->getZonePath( 'temp' );
580  if ( ( !$repo->validateFilename( $path ) ) ||
581  ( strpos( $path, $repoTempPath ) !== 0 )
582  ) {
583  wfDebug( "UploadStash: tried to construct an UploadStashFile "
584  . "from a file that should already exist at '$path', but path is not valid\n" );
585  throw new UploadStashBadPathException( 'path is not valid' );
586  }
587 
588  // check if path exists! and is a plain file.
589  if ( !$repo->fileExists( $path ) ) {
590  wfDebug( "UploadStash: tried to construct an UploadStashFile from "
591  . "a file that should already exist at '$path', but path is not found\n" );
592  throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
593  }
594  }
595 
596  parent::__construct( false, $repo, $path, false );
597 
598  $this->name = basename( $this->path );
599  }
600 
609  public function getDescriptionUrl() {
610  return $this->getUrl();
611  }
612 
623  public function getThumbPath( $thumbName = false ) {
624  $path = dirname( $this->path );
625  if ( $thumbName !== false ) {
626  $path .= "/$thumbName";
627  }
628 
629  return $path;
630  }
631 
641  function thumbName( $params, $flags = 0 ) {
642  return $this->generateThumbName( $this->getUrlName(), $params );
643  }
644 
651  private function getSpecialUrl( $subPage ) {
652  return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
653  }
654 
665  public function getThumbUrl( $thumbName = false ) {
666  wfDebug( __METHOD__ . " getting for $thumbName \n" );
667 
668  return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
669  }
670 
677  public function getUrlName() {
678  if ( !$this->urlName ) {
679  $this->urlName = $this->fileKey;
680  }
681 
682  return $this->urlName;
683  }
684 
691  public function getUrl() {
692  if ( !isset( $this->url ) ) {
693  $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
694  }
695 
696  return $this->url;
697  }
698 
706  public function getFullUrl() {
707  return $this->getUrl();
708  }
709 
716  public function getFileKey() {
717  return $this->fileKey;
718  }
719 
724  public function remove() {
725  if ( !$this->repo->fileExists( $this->path ) ) {
726  // Maybe the file's already been removed? This could totally happen in UploadBase.
727  return true;
728  }
729 
730  return $this->repo->freeTemp( $this->path );
731  }
732 
733  public function exists() {
734  return $this->repo->fileExists( $this->path );
735  }
736 }
737 
739 }
740 
742 }
743 
745 }
746 
748 }
749 
751 }
752 
754 }
755 
757 }
758 
760 }
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
the array() calling protocol came about after MediaWiki 1.4rc1.
const KEY_FORMAT_REGEX
Definition: UploadStash.php:56
clear()
Remove all files from the stash.
getSpecialUrl($subPage)
Helper function – given a 'subpage', return the local URL, e.g.
static getTitleFor($name, $subpage=false, $fragment= '')
Get a localised Title object for a specified special page name If you don't need a full Title object...
Definition: SpecialPage.php:82
static singleton()
Get an instance of this class.
Definition: MimeMagic.php:29
listFiles()
List all files in the stash.
static isVirtualUrl($url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:254
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
resolveVirtualUrl($url)
Get the backend storage path corresponding to a virtual URL.
Definition: FileRepo.php:323
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
const DB_MASTER
Definition: defines.php:23
static normalizeExtension($extension)
Normalize a file extension to the common form, making it lowercase and checking some synonyms...
Definition: File.php:223
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
A file object referring to either a standalone local file, or a file in a local repository with no da...
getFileKey()
Getter for file key (the unique id by which this file's location & metadata is stored in the db) ...
fetchFileMetadata($key, $readFromDB=DB_REPLICA)
Helper function: do the actual database query to fetch file metadata.
initFile($key)
Helper function: Initialize the UploadStashFile for a given file.
getUrlName()
The basename for the URL, which we want to not be related to the filename.
__construct(FileRepo $repo, $user=null)
Represents a temporary filestore, with metadata in the database.
Definition: UploadStash.php:87
unserialize($serialized)
Definition: ApiMessage.php:102
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
$res
Definition: database.txt:21
const MAX_US_PROPS_SIZE
Definition: UploadStash.php:57
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
Definition: distributors.txt:9
getUrl()
Return the URL of the file, if for some reason we wanted to download it We tend not to do this for th...
$params
getMetadata($key)
Getter for file metadata.
validateFilename($filename)
Determine if a relative path is valid, i.e.
Definition: FileRepo.php:1667
getThumbUrl($thumbName=false)
Get a URL to access the thumbnail This is required because the model of how files work requires that ...
fileExists($file)
Checks existence of a a file.
Definition: FileRepo.php:1353
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
getFileProps($key)
Getter for fileProps.
generateThumbName($name, $params)
Generate a thumbnail file name from a name and specified parameters.
Definition: File.php:952
getThumbPath($thumbName=false)
Get the path for the thumbnail (actually any transformation of this file) The actual argument is the ...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
UploadStash is intended to accomplish a few things:
Definition: UploadStash.php:54
__construct($repo, $path, $key)
A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create ...
thumbName($params, $flags=0)
Return the file/url base name of a thumbnail with the specified parameters.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation files(the"Software")
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
Definition: design.txt:12
Base class for file repositories.
Definition: FileRepo.php:37
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
getFullUrl()
Parent classes use this method, for no obvious reason, to return the path (relative to wiki root...
const DB_REPLICA
Definition: defines.php:22
static getExtensionForPath($path)
Find or guess extension – ensuring that our extension matches our MIME type.
serialize()
Definition: ApiMessage.php:94
removeFileNoAuth($key)
Remove a file (see removeFile), but doesn't check ownership first.
$extensions
removeFile($key)
Remove a particular file from the stash.
getDescriptionUrl()
A method needed by the file transforming and scaling routines in File.php We do not necessarily care ...
$wgFileBlacklist
Files with these extensions will never be allowed as uploads.
LocalRepo $repo
repository that this uses to store temp files public because we sometimes need to get a LocalFile wit...
Definition: UploadStash.php:65
getFile($key, $noAuth=false)
Get a file and its metadata from the stash.
getZonePath($zone)
Get the storage path corresponding to one of the zones.
Definition: FileRepo.php:363
stashFile($path, $sourceType=null)
Stash a file in a temp directory and record that we did this in the database, along with other metada...
$wgUser
Definition: Setup.php:806