MediaWiki master
UploadStash.php
Go to the documentation of this file.
1<?php
8
9namespace MediaWiki\Upload;
10
11use MediaWiki\Context\RequestContext;
12use MediaWiki\FileRepo\File\File;
13use MediaWiki\FileRepo\LocalRepo;
14use MediaWiki\MainConfigNames;
15use MediaWiki\MediaWikiServices;
16use MediaWiki\Upload\Exception\UploadStashBadPathException;
17use MediaWiki\Upload\Exception\UploadStashFileException;
18use MediaWiki\Upload\Exception\UploadStashFileNotFoundException;
19use MediaWiki\Upload\Exception\UploadStashNoSuchKeyException;
20use MediaWiki\Upload\Exception\UploadStashNotLoggedInException;
21use MediaWiki\Upload\Exception\UploadStashWrongOwnerException;
22use MediaWiki\Upload\Exception\UploadStashZeroLengthFileException;
23use MediaWiki\User\UserIdentity;
24use MediaWiki\Utils\MWFileProps;
25
37 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
38 public const KEY_FORMAT_REGEX = '/^[\w\-\.]+\.\w*$/';
39 private const MAX_US_PROPS_SIZE = 65535;
40
47 public $repo;
48
50 protected $files = [];
51
53 protected $fileMetadata = [];
54
56 protected $fileProps = [];
57
59 private $user;
60
66 public function __construct( LocalRepo $repo, ?UserIdentity $user = null ) {
67 $this->repo = $repo;
68 $this->user = $user ?? RequestContext::getMain()->getUser();
69 }
70
84 public function getFile( $key, $noAuth = false ) {
85 if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
87 wfMessage( 'uploadstash-bad-path-bad-format', $key )
88 );
89 }
90
91 if ( !$noAuth && !$this->user->isRegistered() ) {
93 wfMessage( 'uploadstash-not-logged-in' )
94 );
95 }
96
97 if ( !isset( $this->fileMetadata[$key] ) ) {
98 if ( !$this->fetchFileMetadata( $key ) ) {
99 // If nothing was received, it's likely due to replication lag.
100 // Check the primary DB to see if the record is there.
101 $this->fetchFileMetadata( $key, DB_PRIMARY );
102 }
103
104 if ( !isset( $this->fileMetadata[$key] ) ) {
106 wfMessage( 'uploadstash-file-not-found', $key )
107 );
108 }
109
110 // Create $this->files[$key]
111 $this->initFile( $key );
112
113 // Fetch file props
114 if (
115 isset( $this->fileMetadata[$key]['us_props'] )
116 && strlen( $this->fileMetadata[$key]['us_props'] )
117 ) {
118 $this->fileProps[$key] = unserialize( $this->fileMetadata[$key]['us_props'] );
119 } else {
120 // b/c for rows with no us_props
121 wfDebug( __METHOD__ . " fetched props for $key from file" );
122 $path = $this->fileMetadata[$key]['us_path'];
123 $this->fileProps[$key] = $this->repo->getFileProps( $path );
124 }
125 }
126
127 if ( !$noAuth && $this->fileMetadata[$key]['us_user'] != $this->user->getId() ) {
129 wfMessage( 'uploadstash-wrong-owner', $key )
130 );
131 }
132
133 return $this->files[$key];
134 }
135
142 public function getMetadata( $key ) {
143 $this->getFile( $key );
144
145 return $this->fileMetadata[$key];
146 }
147
154 public function getFileProps( $key ) {
155 $this->getFile( $key );
156
157 return $this->fileProps[$key];
158 }
159
173 public function stashFile( $path, $sourceType = null, $fileProps = null ) {
174 if ( !$this->user->isRegistered() ) {
176 wfMessage( 'uploadstash-not-logged-in' )
177 );
178 }
179
180 if ( !is_file( $path ) ) {
181 wfDebug( __METHOD__ . " tried to stash file at '$path', but it doesn't exist" );
183 wfMessage( 'uploadstash-bad-path' )
184 );
185 }
186
187 // File props is expensive to generate for large files, so reuse if possible.
188 if ( !$fileProps ) {
189 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
190 $fileProps = $mwProps->getPropsFromPath( $path, true );
191 }
192
193 if ( !$fileProps['size'] ) {
195 wfMessage( 'uploadstash-zero-length' )
196 );
197 }
198
199 wfDebug( __METHOD__ . " stashing file at '$path'" );
200
201 // We will be initializing from some tmpnam files that don't have extensions.
202 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
203 $extension = self::getExtensionForPath( $path );
204 if ( !str_ends_with( $path, ".$extension" ) ) {
205 $pathWithGoodExtension = "$path.$extension";
206 } else {
207 $pathWithGoodExtension = $path;
208 }
209
210 // If no key was supplied, make one.
211 [ $usec, $sec ] = explode( ' ', microtime() );
212 $usec = substr( $usec, 2 );
213 $key = \Wikimedia\base_convert( $sec . $usec, 10, 36 ) . '.' .
214 \Wikimedia\base_convert( (string)mt_rand(), 10, 36 ) . '.' .
215 $this->user->getId() . '.' .
216 $extension;
217
218 $this->fileProps[$key] = $fileProps;
219
220 if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
222 wfMessage( 'uploadstash-bad-path-bad-format', $key )
223 );
224 }
225
226 wfDebug( __METHOD__ . " key for '$path': $key" );
227
228 // If not already in a temporary area, put it there.
229 $storeStatus = $this->repo->storeTemp( basename( $pathWithGoodExtension ), $path );
230
231 if ( !$storeStatus->isOK() ) {
232 // Choose the best error message to throw so that ApiUpload can catch it and
233 // convert it to an error.
234 // TODO: return a StatusValue instead and use ApiBase::addMessagesFromStatus()
235 foreach ( $storeStatus->getMessages( 'error' ) as $msg ) {
236 throw new UploadStashFileException( $msg );
237 }
238 foreach ( $storeStatus->getMessages( 'warning' ) as $msg ) {
239 throw new UploadStashFileException( $msg );
240 }
241 // XXX: This isn't a real message, hopefully this case is unreachable
242 throw new UploadStashFileException( [ 'unknown', 'no error recorded' ] );
243 }
244 $stashPath = $storeStatus->value;
245
246 // Insert the file metadata into the DB.
247 wfDebug( __METHOD__ . " inserting $stashPath under $key" );
248 $dbw = $this->repo->getPrimaryDB();
249
250 $serializedFileProps = serialize( $fileProps );
251 if ( strlen( $serializedFileProps ) > self::MAX_US_PROPS_SIZE ) {
252 // The database is going to truncate this and make the field invalid.
253 // Prioritize important metadata over file handler metadata.
254 // File handler should be prepared to regenerate invalid metadata if needed.
255 // TODO: make us_props be a mediumblob like fr_metadata.
256 $fileProps['metadata'] = [];
257 $serializedFileProps = serialize( $fileProps );
258 }
259
260 $insertRow = [
261 'us_user' => $this->user->getId(),
262 'us_key' => $key,
263 'us_orig_path' => $path,
264 'us_path' => $stashPath, // virtual URL
265 'us_props' => $dbw->encodeBlob( $serializedFileProps ),
266 'us_size' => $fileProps['size'],
267 'us_sha1' => $fileProps['sha1'],
268 'us_mime' => $fileProps['mime'],
269 'us_media_type' => $fileProps['media_type'],
270 'us_image_width' => $fileProps['width'],
271 'us_image_height' => $fileProps['height'],
272 'us_image_bits' => $fileProps['bits'],
273 'us_source_type' => $sourceType,
274 'us_timestamp' => $dbw->timestamp(),
275 'us_status' => 'finished'
276 ];
277
278 $dbw->newInsertQueryBuilder()
279 ->insertInto( 'uploadstash' )
280 ->row( $insertRow )
281 ->caller( __METHOD__ )->execute();
282
283 $insertRow['us_id'] = $dbw->insertId();
284 $this->fileMetadata[$key] = $insertRow;
285
286 $this->initFile( $key );
287 return $this->getFile( $key );
288 }
289
297 public function clear() {
298 if ( !$this->user->isRegistered() ) {
300 wfMessage( 'uploadstash-not-logged-in' )
301 );
302 }
303
304 wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->user->getId() );
305 $dbw = $this->repo->getPrimaryDB();
306 $dbw->newDeleteQueryBuilder()
307 ->deleteFrom( 'uploadstash' )
308 ->where( [ 'us_user' => $this->user->getId() ] )
309 ->caller( __METHOD__ )->execute();
310
311 // Destroy objects.
312 $this->files = [];
313 $this->fileMetadata = [];
314
315 return true;
316 }
317
326 public function removeFile( $key ) {
327 if ( !$this->user->isRegistered() ) {
329 wfMessage( 'uploadstash-not-logged-in' )
330 );
331 }
332
333 $dbw = $this->repo->getPrimaryDB();
334
335 // Load from the primary since we are in an update path.
336 $row = $dbw->newSelectQueryBuilder()
337 ->select( 'us_user' )
338 ->from( 'uploadstash' )
339 ->where( [ 'us_key' => $key ] )
340 ->caller( __METHOD__ )->fetchRow();
341
342 if ( !$row ) {
344 wfMessage( 'uploadstash-no-such-key', $key )
345 );
346 }
347
348 if ( $row->us_user != $this->user->getId() ) {
350 wfMessage( 'uploadstash-wrong-owner', $key )
351 );
352 }
353
354 return $this->removeFileNoAuth( $key );
355 }
356
363 public function removeFileNoAuth( $key ) {
364 wfDebug( __METHOD__ . " clearing row $key" );
365
366 // Ensure we have the UploadStashFile loaded for this key
367 $this->getFile( $key, true );
368
369 $dbw = $this->repo->getPrimaryDB();
370
371 $dbw->newDeleteQueryBuilder()
372 ->deleteFrom( 'uploadstash' )
373 ->where( [ 'us_key' => $key ] )
374 ->caller( __METHOD__ )->execute();
375
376 $success = $this->files[$key]->remove();
377
378 unset( $this->files[$key] );
379 unset( $this->fileMetadata[$key] );
380
381 return $success;
382 }
383
390 public function listFiles(): array {
391 if ( !$this->user->isRegistered() ) {
393 wfMessage( 'uploadstash-not-logged-in' )
394 );
395 }
396
397 return $this->repo->getReplicaDB()->newSelectQueryBuilder()
398 ->select( 'us_key' )
399 ->from( 'uploadstash' )
400 ->where( [ 'us_user' => $this->user->getId() ] )
401 ->caller( __METHOD__ )
402 ->fetchFieldValues();
403 }
404
416 public static function getExtensionForPath( $path ) {
417 $prohibitedFileExtensions = MediaWikiServices::getInstance()
418 ->getMainConfig()->get( MainConfigNames::ProhibitedFileExtensions );
419 // Does this have an extension?
420 $n = strrpos( $path, '.' );
421
422 if ( $n !== false ) {
423 $extension = $n ? substr( $path, $n + 1 ) : '';
424 } else {
425 // If not, assume that it should be related to the MIME type of the original file.
426 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
427 $mimeType = $magic->guessMimeType( $path );
428 $extension = $magic->getExtensionFromMimeTypeOrNull( $mimeType ) ?? '';
429 }
430
431 $extension = File::normalizeExtension( $extension );
432 if ( in_array( $extension, $prohibitedFileExtensions ) ) {
433 // The file should already be checked for being evil. However, if
434 // somehow we got here, we definitely don't want to give it an
435 // extension of .php and put it in a web accessible directory.
436 return '';
437 }
438
439 return $extension;
440 }
441
449 protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA ) {
450 if ( $readFromDB === DB_PRIMARY ) {
451 $dbr = $this->repo->getPrimaryDB();
452 } else {
453 $dbr = $this->repo->getReplicaDB();
454 }
455
456 $row = $dbr->newSelectQueryBuilder()
457 ->select( [
458 'us_user', 'us_key', 'us_orig_path', 'us_path', 'us_props',
459 'us_size', 'us_sha1', 'us_mime', 'us_media_type',
460 'us_image_width', 'us_image_height', 'us_image_bits',
461 'us_source_type', 'us_timestamp', 'us_status',
462 ] )
463 ->from( 'uploadstash' )
464 ->where( [ 'us_key' => $key ] )
465 ->caller( __METHOD__ )->fetchRow();
466
467 if ( !is_object( $row ) ) {
468 // The key wasn't present in the database. This will happen sometimes.
469 return false;
470 }
471
472 $this->fileMetadata[$key] = (array)$row;
473 $this->fileMetadata[$key]['us_props'] = $dbr->decodeBlob( $row->us_props );
474
475 return true;
476 }
477
485 protected function initFile( $key ) {
486 $file = new UploadStashFile(
487 $this->repo,
488 $this->fileMetadata[$key]['us_path'],
489 $key,
490 $this->fileMetadata[$key]['us_sha1'],
491 $this->fileMetadata[$key]['us_mime'] ?? false
492 );
493 $this->files[$key] = $file;
494
495 return true;
496 }
497}
498
500class_alias( UploadStash::class, 'UploadStash' );
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.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:72
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:43
const ProhibitedFileExtensions
Name constant for the ProhibitedFileExtensions setting, for use with Config\get().
static getInstance()
Returns the global default instance of the top level service locator.
UploadStash provides temporary file storage for users, persisting across multiple requests.
UploadStashFile[] $files
Array of initialized file objects.
LocalRepo $repo
Repository that this uses to store temp files.
getFile( $key, $noAuth=false)
Get a file and its metadata from the stash.
listFiles()
List all files in the stash.
clear()
Remove all files from the stash.
getFileProps( $key)
Get file properties.
removeFile( $key)
Remove a particular file from the stash and the repo.
getMetadata( $key)
Get file metadata.
static getExtensionForPath( $path)
Find or guess extension, ensuring that our extension matches our MIME type.
fetchFileMetadata( $key, $readFromDB=DB_REPLICA)
Helper function: do the actual database query to fetch file metadata.
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...
__construct(LocalRepo $repo, ?UserIdentity $user=null)
initFile( $key)
Helper function: Initialize the UploadStashFile for a given file.
removeFileNoAuth( $key)
Remove a file, but doesn't check ownership first.
array $fileProps
Cache of unserialized file properties (us_props) indexed by stash key.
array $fileMetadata
Cache of uploadstash rows indexed by stash key.
MimeMagic helper wrapper.
Interface for objects representing user identity.