MediaWiki master
UploadStash.php
Go to the documentation of this file.
1<?php
27
59 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
60 public const KEY_FORMAT_REGEX = '/^[\w\-\.]+\.\w*$/';
61 private const MAX_US_PROPS_SIZE = 65535;
62
69 public $repo;
70
72 protected $files = [];
73
75 protected $fileMetadata = [];
76
78 protected $fileProps = [];
79
81 private $user;
82
91 public function __construct( FileRepo $repo, UserIdentity $user = null ) {
92 // this might change based on wiki's configuration.
93 $this->repo = $repo;
94
95 // if a user was passed, use it. otherwise, attempt to use the global request context.
96 // this keeps FileRepo from breaking when it creates an UploadStash object
97 $this->user = $user ?? RequestContext::getMain()->getUser();
98 }
99
113 public function getFile( $key, $noAuth = false ) {
114 if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
116 wfMessage( 'uploadstash-bad-path-bad-format', $key )
117 );
118 }
119
120 if ( !$noAuth && !$this->user->isRegistered() ) {
122 wfMessage( 'uploadstash-not-logged-in' )
123 );
124 }
125
126 if ( !isset( $this->fileMetadata[$key] ) ) {
127 if ( !$this->fetchFileMetadata( $key ) ) {
128 // If nothing was received, it's likely due to replication lag.
129 // Check the primary DB to see if the record is there.
130 $this->fetchFileMetadata( $key, DB_PRIMARY );
131 }
132
133 if ( !isset( $this->fileMetadata[$key] ) ) {
135 wfMessage( 'uploadstash-file-not-found', $key )
136 );
137 }
138
139 // create $this->files[$key]
140 $this->initFile( $key );
141
142 // fetch fileprops
143 if (
144 isset( $this->fileMetadata[$key]['us_props'] ) && strlen( $this->fileMetadata[$key]['us_props'] )
145 ) {
146 $this->fileProps[$key] = unserialize( $this->fileMetadata[$key]['us_props'] );
147 } else { // b/c for rows with no us_props
148 wfDebug( __METHOD__ . " fetched props for $key from file" );
149 $path = $this->fileMetadata[$key]['us_path'];
150 $this->fileProps[$key] = $this->repo->getFileProps( $path );
151 }
152 }
153
154 if ( !$this->files[$key]->exists() ) {
155 wfDebug( __METHOD__ . " tried to get file at $key, but it doesn't exist" );
156 // @todo Is this not an UploadStashFileNotFoundException case?
158 wfMessage( 'uploadstash-bad-path' )
159 );
160 }
161
162 if ( !$noAuth && $this->fileMetadata[$key]['us_user'] != $this->user->getId() ) {
164 wfMessage( 'uploadstash-wrong-owner', $key )
165 );
166 }
167
168 return $this->files[$key];
169 }
170
177 public function getMetadata( $key ) {
178 $this->getFile( $key );
179
180 return $this->fileMetadata[$key];
181 }
182
189 public function getFileProps( $key ) {
190 $this->getFile( $key );
191
192 return $this->fileProps[$key];
193 }
194
208 public function stashFile( $path, $sourceType = null, $fileProps = null ) {
209 if ( !is_file( $path ) ) {
210 wfDebug( __METHOD__ . " tried to stash file at '$path', but it doesn't exist" );
212 wfMessage( 'uploadstash-bad-path' )
213 );
214 }
215
216 // File props is expensive to generate for large files, so reuse if possible.
217 if ( !$fileProps ) {
218 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
219 $fileProps = $mwProps->getPropsFromPath( $path, true );
220 }
221 wfDebug( __METHOD__ . " stashing file at '$path'" );
222
223 // we will be initializing from some tmpnam files that don't have extensions.
224 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
225 $extension = self::getExtensionForPath( $path );
226 if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
227 $pathWithGoodExtension = "$path.$extension";
228 } else {
229 $pathWithGoodExtension = $path;
230 }
231
232 // If no key was supplied, make one. a mysql insertid would be totally
233 // reasonable here, except that for historical reasons, the key is this
234 // random thing instead. At least it's not guessable.
235 // Some things that when combined will make a suitably unique key.
236 // see: http://www.jwz.org/doc/mid.html
237 [ $usec, $sec ] = explode( ' ', microtime() );
238 $usec = substr( $usec, 2 );
239 $key = Wikimedia\base_convert( $sec . $usec, 10, 36 ) . '.' .
240 Wikimedia\base_convert( (string)mt_rand(), 10, 36 ) . '.' .
241 $this->user->getId() . '.' .
242 $extension;
243
244 $this->fileProps[$key] = $fileProps;
245
246 if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
248 wfMessage( 'uploadstash-bad-path-bad-format', $key )
249 );
250 }
251
252 wfDebug( __METHOD__ . " key for '$path': $key" );
253
254 // if not already in a temporary area, put it there
255 $storeStatus = $this->repo->storeTemp( basename( $pathWithGoodExtension ), $path );
256
257 if ( !$storeStatus->isOK() ) {
258 // It is a convention in MediaWiki to only return one error per API
259 // exception, even if multiple errors are available. We use reset()
260 // to pick the "first" thing that was wrong, preferring errors to
261 // warnings. This is a bit lame, as we may have more info in the
262 // $storeStatus and we're throwing it away, but to fix it means
263 // redesigning API errors significantly.
264 // $storeStatus->value just contains the virtual URL (if anything)
265 // which is probably useless to the caller.
266 $error = $storeStatus->getErrorsArray();
267 $error = reset( $error );
268 if ( !count( $error ) ) {
269 $error = $storeStatus->getWarningsArray();
270 $error = reset( $error );
271 if ( !count( $error ) ) {
272 $error = [ 'unknown', 'no error recorded' ];
273 }
274 }
275 // At this point, $error should contain the single "most important"
276 // error, plus any parameters.
277 $errorMsg = array_shift( $error );
278 throw new UploadStashFileException( wfMessage( $errorMsg, $error ) );
279 }
280 $stashPath = $storeStatus->value;
281
282 // fetch the current user ID
283 if ( !$this->user->isRegistered() ) {
285 wfMessage( 'uploadstash-not-logged-in' )
286 );
287 }
288
289 // insert the file metadata into the db.
290 wfDebug( __METHOD__ . " inserting $stashPath under $key" );
291 $dbw = $this->repo->getPrimaryDB();
292
293 $serializedFileProps = serialize( $fileProps );
294 if ( strlen( $serializedFileProps ) > self::MAX_US_PROPS_SIZE ) {
295 // Database is going to truncate this and make the field invalid.
296 // Prioritize important metadata over file handler metadata.
297 // File handler should be prepared to regenerate invalid metadata if needed.
298 $fileProps['metadata'] = [];
299 $serializedFileProps = serialize( $fileProps );
300 }
301
302 $insertRow = [
303 'us_user' => $this->user->getId(),
304 'us_key' => $key,
305 'us_orig_path' => $path,
306 'us_path' => $stashPath, // virtual URL
307 'us_props' => $dbw->encodeBlob( $serializedFileProps ),
308 'us_size' => $fileProps['size'],
309 'us_sha1' => $fileProps['sha1'],
310 'us_mime' => $fileProps['mime'],
311 'us_media_type' => $fileProps['media_type'],
312 'us_image_width' => $fileProps['width'],
313 'us_image_height' => $fileProps['height'],
314 'us_image_bits' => $fileProps['bits'],
315 'us_source_type' => $sourceType,
316 'us_timestamp' => $dbw->timestamp(),
317 'us_status' => 'finished'
318 ];
319
320 $dbw->newInsertQueryBuilder()
321 ->insertInto( 'uploadstash' )
322 ->row( $insertRow )
323 ->caller( __METHOD__ )->execute();
324
325 // store the insertid in the class variable so immediate retrieval
326 // (possibly laggy) isn't necessary.
327 $insertRow['us_id'] = $dbw->insertId();
328
329 $this->fileMetadata[$key] = $insertRow;
330
331 # create the UploadStashFile object for this file.
332 $this->initFile( $key );
333
334 return $this->getFile( $key );
335 }
336
344 public function clear() {
345 if ( !$this->user->isRegistered() ) {
347 wfMessage( 'uploadstash-not-logged-in' )
348 );
349 }
350
351 wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->user->getId() );
352 $dbw = $this->repo->getPrimaryDB();
353 $dbw->newDeleteQueryBuilder()
354 ->deleteFrom( 'uploadstash' )
355 ->where( [ 'us_user' => $this->user->getId() ] )
356 ->caller( __METHOD__ )->execute();
357
358 # destroy objects.
359 $this->files = [];
360 $this->fileMetadata = [];
361
362 return true;
363 }
364
373 public function removeFile( $key ) {
374 if ( !$this->user->isRegistered() ) {
376 wfMessage( 'uploadstash-not-logged-in' )
377 );
378 }
379
380 $dbw = $this->repo->getPrimaryDB();
381
382 // this is a cheap query. it runs on the primary DB so that this function
383 // still works when there's lag. It won't be called all that often.
384 $row = $dbw->newSelectQueryBuilder()
385 ->select( 'us_user' )
386 ->from( 'uploadstash' )
387 ->where( [ 'us_key' => $key ] )
388 ->caller( __METHOD__ )->fetchRow();
389
390 if ( !$row ) {
392 wfMessage( 'uploadstash-no-such-key', $key )
393 );
394 }
395
396 if ( $row->us_user != $this->user->getId() ) {
398 wfMessage( 'uploadstash-wrong-owner', $key )
399 );
400 }
401
402 return $this->removeFileNoAuth( $key );
403 }
404
411 public function removeFileNoAuth( $key ) {
412 wfDebug( __METHOD__ . " clearing row $key" );
413
414 // Ensure we have the UploadStashFile loaded for this key
415 $this->getFile( $key, true );
416
417 $dbw = $this->repo->getPrimaryDB();
418
419 $dbw->newDeleteQueryBuilder()
420 ->deleteFrom( 'uploadstash' )
421 ->where( [ 'us_key' => $key ] )
422 ->caller( __METHOD__ )->execute();
423
427 $this->files[$key]->remove();
428
429 unset( $this->files[$key] );
430 unset( $this->fileMetadata[$key] );
431
432 return true;
433 }
434
441 public function listFiles() {
442 if ( !$this->user->isRegistered() ) {
444 wfMessage( 'uploadstash-not-logged-in' )
445 );
446 }
447
448 $res = $this->repo->getReplicaDB()->newSelectQueryBuilder()
449 ->select( 'us_key' )
450 ->from( 'uploadstash' )
451 ->where( [ 'us_user' => $this->user->getId() ] )
452 ->caller( __METHOD__ )->fetchResultSet();
453
454 if ( $res->numRows() == 0 ) {
455 // nothing to do.
456 return false;
457 }
458
459 // finish the read before starting writes.
460 $keys = [];
461 foreach ( $res as $row ) {
462 $keys[] = $row->us_key;
463 }
464
465 return $keys;
466 }
467
477 public static function getExtensionForPath( $path ) {
478 $prohibitedFileExtensions = MediaWikiServices::getInstance()
479 ->getMainConfig()->get( MainConfigNames::ProhibitedFileExtensions );
480 // Does this have an extension?
481 $n = strrpos( $path, '.' );
482
483 if ( $n !== false ) {
484 $extension = $n ? substr( $path, $n + 1 ) : '';
485 } else {
486 // If not, assume that it should be related to the MIME type of the original file.
487 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
488 $mimeType = $magic->guessMimeType( $path );
489 $extension = $magic->getExtensionFromMimeTypeOrNull( $mimeType ) ?? '';
490 }
491
492 $extension = File::normalizeExtension( $extension );
493 if ( in_array( $extension, $prohibitedFileExtensions ) ) {
494 // The file should already be checked for being evil.
495 // However, if somehow we got here, we definitely
496 // don't want to give it an extension of .php and
497 // put it in a web accessible directory.
498 return '';
499 }
500
501 return $extension;
502 }
503
511 protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA ) {
512 // populate $fileMetadata[$key]
513 if ( $readFromDB === DB_PRIMARY ) {
514 // sometimes reading from the primary DB is necessary, if there's replication lag.
515 $dbr = $this->repo->getPrimaryDB();
516 } else {
517 $dbr = $this->repo->getReplicaDB();
518 }
519
520 $row = $dbr->newSelectQueryBuilder()
521 ->select( [
522 'us_user', 'us_key', 'us_orig_path', 'us_path', 'us_props',
523 'us_size', 'us_sha1', 'us_mime', 'us_media_type',
524 'us_image_width', 'us_image_height', 'us_image_bits',
525 'us_source_type', 'us_timestamp', 'us_status',
526 ] )
527 ->from( 'uploadstash' )
528 ->where( [ 'us_key' => $key ] )
529 ->caller( __METHOD__ )->fetchRow();
530
531 if ( !is_object( $row ) ) {
532 // key wasn't present in the database. this will happen sometimes.
533 return false;
534 }
535
536 $this->fileMetadata[$key] = (array)$row;
537 $this->fileMetadata[$key]['us_props'] = $dbr->decodeBlob( $row->us_props );
538
539 return true;
540 }
541
549 protected function initFile( $key ) {
550 $file = new UploadStashFile(
551 $this->repo,
552 $this->fileMetadata[$key]['us_path'],
553 $key,
554 $this->fileMetadata[$key]['us_sha1']
555 );
556 if ( $file->getSize() === 0 ) {
558 wfMessage( 'uploadstash-zero-length' )
559 );
560 }
561 $this->files[$key] = $file;
562
563 return true;
564 }
565}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
getFile()
Get the file for this page, if one exists.
Base class for file repositories.
Definition FileRepo.php:51
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:49
MimeMagic helper wrapper.
Group all the pieces relevant to the context of a request into one instance.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
UploadStash is intended to accomplish a few things:
static getExtensionForPath( $path)
Find or guess extension – ensuring that our extension matches our MIME type.
removeFile( $key)
Remove a particular file from the stash.
const KEY_FORMAT_REGEX
fetchFileMetadata( $key, $readFromDB=DB_REPLICA)
Helper function: do the actual database query to fetch file metadata.
getFileProps( $key)
Getter for fileProps.
clear()
Remove all files from the stash.
array $fileMetadata
cache of the file metadata that's stored in the database
array $fileProps
fileprops cache
listFiles()
List all files in the stash.
__construct(FileRepo $repo, UserIdentity $user=null)
Represents a temporary filestore, with metadata in the database.
getMetadata( $key)
Getter for file metadata.
removeFileNoAuth( $key)
Remove a file (see removeFile), but doesn't check ownership first.
initFile( $key)
Helper function: Initialize the UploadStashFile for a given file.
stashFile( $path, $sourceType=null, $fileProps=null)
Stash a file in a temp directory and record that we did this in the database, along with other metada...
getFile( $key, $noAuth=false)
Get a file and its metadata from the stash.
LocalRepo $repo
repository that this uses to store temp files public because we sometimes need to get a LocalFile wit...
array $files
array of initialized repo objects
Interface for objects representing user identity.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28