MediaWiki  1.29.1
UploadFromChunks.php
Go to the documentation of this file.
1 <?php
31  protected $mOffset;
32  protected $mChunkIndex;
33  protected $mFileKey;
34  protected $mVirtualTempPath;
36  private $repo;
37 
45  public function __construct( User $user, $stash = false, $repo = false ) {
46  $this->user = $user;
47 
48  if ( $repo ) {
49  $this->repo = $repo;
50  } else {
51  $this->repo = RepoGroup::singleton()->getLocalRepo();
52  }
53 
54  if ( $stash ) {
55  $this->stash = $stash;
56  } else {
57  if ( $user ) {
58  wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
59  } else {
60  wfDebug( __METHOD__ . " creating new UploadFromChunks instance with no user\n" );
61  }
62  $this->stash = new UploadStash( $this->repo, $this->user );
63  }
64  }
65 
69  public function tryStashFile( User $user, $isPartial = false ) {
70  try {
71  $this->verifyChunk();
73  return Status::newFatal( $e->msg );
74  }
75 
76  return parent::tryStashFile( $user, $isPartial );
77  }
78 
84  public function stashFile( User $user = null ) {
85  wfDeprecated( __METHOD__, '1.28' );
86  $this->verifyChunk();
87  return parent::stashFile( $user );
88  }
89 
95  public function stashFileGetKey() {
96  wfDeprecated( __METHOD__, '1.28' );
97  $this->verifyChunk();
98  return parent::stashFileGetKey();
99  }
100 
106  public function stashSession() {
107  wfDeprecated( __METHOD__, '1.28' );
108  $this->verifyChunk();
109  return parent::stashSession();
110  }
111 
118  protected function doStashFile( User $user = null ) {
119  // Stash file is the called on creating a new chunk session:
120  $this->mChunkIndex = 0;
121  $this->mOffset = 0;
122 
123  // Create a local stash target
124  $this->mStashFile = parent::doStashFile( $user );
125  // Update the initial file offset (based on file size)
126  $this->mOffset = $this->mStashFile->getSize();
127  $this->mFileKey = $this->mStashFile->getFileKey();
128 
129  // Output a copy of this first to chunk 0 location:
130  $this->outputChunk( $this->mStashFile->getPath() );
131 
132  // Update db table to reflect initial "chunk" state
133  $this->updateChunkStatus();
134 
135  return $this->mStashFile;
136  }
137 
145  public function continueChunks( $name, $key, $webRequestUpload ) {
146  $this->mFileKey = $key;
147  $this->mUpload = $webRequestUpload;
148  // Get the chunk status form the db:
149  $this->getChunkStatus();
150 
151  $metadata = $this->stash->getMetadata( $key );
152  $this->initializePathInfo( $name,
153  $this->getRealPath( $metadata['us_path'] ),
154  $metadata['us_size'],
155  false
156  );
157  }
158 
163  public function concatenateChunks() {
164  $chunkIndex = $this->getChunkIndex();
165  wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
166  $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
167 
168  // Concatenate all the chunks to mVirtualTempPath
169  $fileList = [];
170  // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
171  for ( $i = 0; $i <= $chunkIndex; $i++ ) {
172  $fileList[] = $this->getVirtualChunkLocation( $i );
173  }
174 
175  // Get the file extension from the last chunk
176  $ext = FileBackend::extensionFromPath( $this->mVirtualTempPath );
177  // Get a 0-byte temp file to perform the concatenation at
178  $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext, wfTempDir() );
179  $tmpPath = false; // fail in concatenate()
180  if ( $tmpFile ) {
181  // keep alive with $this
182  $tmpPath = $tmpFile->bind( $this )->getPath();
183  }
184 
185  // Concatenate the chunks at the temp file
186  $tStart = microtime( true );
187  $status = $this->repo->concatenate( $fileList, $tmpPath, FileRepo::DELETE_SOURCE );
188  $tAmount = microtime( true ) - $tStart;
189  if ( !$status->isOK() ) {
190  return $status;
191  }
192 
193  wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
194 
195  // File system path of the actual full temp file
196  $this->setTempFile( $tmpPath );
197 
198  $ret = $this->verifyUpload();
199  if ( $ret['status'] !== UploadBase::OK ) {
200  wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
201  $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
202 
203  return $status;
204  }
205 
206  // Update the mTempPath and mStashFile
207  // (for FileUpload or normal Stash to take over)
208  $tStart = microtime( true );
209  // This is a re-implementation of UploadBase::tryStashFile(), we can't call it because we
210  // override doStashFile() with completely different functionality in this class...
211  $error = $this->runUploadStashFileHook( $this->user );
212  if ( $error ) {
213  call_user_func_array( [ $status, 'fatal' ], $error );
214  return $status;
215  }
216  try {
217  $this->mStashFile = parent::doStashFile( $this->user );
218  } catch ( UploadStashException $e ) {
219  $status->fatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
220  return $status;
221  }
222 
223  $tAmount = microtime( true ) - $tStart;
224  $this->mStashFile->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
225  wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
226 
227  return $status;
228  }
229 
235  function getVirtualChunkLocation( $index ) {
236  return $this->repo->getVirtualUrl( 'temp' ) .
237  '/' .
238  $this->repo->getHashPath(
239  $this->getChunkFileKey( $index )
240  ) .
241  $this->getChunkFileKey( $index );
242  }
243 
252  public function addChunk( $chunkPath, $chunkSize, $offset ) {
253  // Get the offset before we add the chunk to the file system
254  $preAppendOffset = $this->getOffset();
255 
256  if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize() ) {
257  $status = Status::newFatal( 'file-too-large' );
258  } else {
259  // Make sure the client is uploading the correct chunk with a matching offset.
260  if ( $preAppendOffset == $offset ) {
261  // Update local chunk index for the current chunk
262  $this->mChunkIndex++;
263  try {
264  # For some reason mTempPath is set to first part
265  $oldTemp = $this->mTempPath;
266  $this->mTempPath = $chunkPath;
267  $this->verifyChunk();
268  $this->mTempPath = $oldTemp;
270  return Status::newFatal( $e->msg );
271  }
272  $status = $this->outputChunk( $chunkPath );
273  if ( $status->isGood() ) {
274  // Update local offset:
275  $this->mOffset = $preAppendOffset + $chunkSize;
276  // Update chunk table status db
277  $this->updateChunkStatus();
278  }
279  } else {
280  $status = Status::newFatal( 'invalid-chunk-offset' );
281  }
282  }
283 
284  return $status;
285  }
286 
290  private function updateChunkStatus() {
291  wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
292  $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
293 
294  $dbw = $this->repo->getMasterDB();
295  $dbw->update(
296  'uploadstash',
297  [
298  'us_status' => 'chunks',
299  'us_chunk_inx' => $this->getChunkIndex(),
300  'us_size' => $this->getOffset()
301  ],
302  [ 'us_key' => $this->mFileKey ],
303  __METHOD__
304  );
305  }
306 
310  private function getChunkStatus() {
311  // get Master db to avoid race conditions.
312  // Otherwise, if chunk upload time < replag there will be spurious errors
313  $dbw = $this->repo->getMasterDB();
314  $row = $dbw->selectRow(
315  'uploadstash',
316  [
317  'us_chunk_inx',
318  'us_size',
319  'us_path',
320  ],
321  [ 'us_key' => $this->mFileKey ],
322  __METHOD__
323  );
324  // Handle result:
325  if ( $row ) {
326  $this->mChunkIndex = $row->us_chunk_inx;
327  $this->mOffset = $row->us_size;
328  $this->mVirtualTempPath = $row->us_path;
329  }
330  }
331 
336  private function getChunkIndex() {
337  if ( $this->mChunkIndex !== null ) {
338  return $this->mChunkIndex;
339  }
340 
341  return 0;
342  }
343 
348  public function getOffset() {
349  if ( $this->mOffset !== null ) {
350  return $this->mOffset;
351  }
352 
353  return 0;
354  }
355 
363  private function outputChunk( $chunkPath ) {
364  // Key is fileKey + chunk index
365  $fileKey = $this->getChunkFileKey();
366 
367  // Store the chunk per its indexed fileKey:
368  $hashPath = $this->repo->getHashPath( $fileKey );
369  $storeStatus = $this->repo->quickImport( $chunkPath,
370  $this->repo->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
371 
372  // Check for error in stashing the chunk:
373  if ( !$storeStatus->isOK() ) {
374  $error = $storeStatus->getErrorsArray();
375  $error = reset( $error );
376  if ( !count( $error ) ) {
377  $error = $storeStatus->getWarningsArray();
378  $error = reset( $error );
379  if ( !count( $error ) ) {
380  $error = [ 'unknown', 'no error recorded' ];
381  }
382  }
383  throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
384  implode( '; ', $error ) );
385  }
386 
387  return $storeStatus;
388  }
389 
390  private function getChunkFileKey( $index = null ) {
391  if ( $index === null ) {
392  $index = $this->getChunkIndex();
393  }
394 
395  return $this->mFileKey . '.' . $index;
396  }
397 
403  private function verifyChunk() {
404  // Rest mDesiredDestName here so we verify the name as if it were mFileKey
405  $oldDesiredDestName = $this->mDesiredDestName;
406  $this->mDesiredDestName = $this->mFileKey;
407  $this->mTitle = false;
408  $res = $this->verifyPartialFile();
409  $this->mDesiredDestName = $oldDesiredDestName;
410  $this->mTitle = false;
411  if ( is_array( $res ) ) {
413  }
414  }
415 }
416 
418 }
419 
421 }
422 
424  public $msg;
425  public function __construct( $res ) {
426  $this->msg = call_user_func_array( 'wfMessage', $res );
427  parent::__construct( call_user_func_array( 'wfMessage', $res )
428  ->inLanguage( 'en' )->useDatabase( false )->text() );
429  }
430 }
UploadFromChunks\updateChunkStatus
updateChunkStatus()
Update the chunk db table with the current status:
Definition: UploadFromChunks.php:290
UploadFromChunks\stashFileGetKey
stashFileGetKey()
{}
Definition: UploadFromChunks.php:95
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
UploadFromChunks\getOffset
getOffset()
Get the offset at which the next uploaded chunk will be appended to.
Definition: UploadFromChunks.php:348
UploadFromChunks\getChunkIndex
getChunkIndex()
Get the current Chunk index.
Definition: UploadFromChunks.php:336
UploadFromChunks\outputChunk
outputChunk( $chunkPath)
Output the chunk to disk.
Definition: UploadFromChunks.php:363
captcha-old.count
count
Definition: captcha-old.py:225
text
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
UploadFromChunks\$mVirtualTempPath
$mVirtualTempPath
Definition: UploadFromChunks.php:34
UploadChunkZeroLengthFileException
Definition: UploadFromChunks.php:417
UploadStash
UploadStash is intended to accomplish a few things:
Definition: UploadStash.php:54
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
FileBackend\extensionFromPath
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1507
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:63
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
UploadFromChunks\stashSession
stashSession()
{}
Definition: UploadFromChunks.php:106
UploadFromChunks\__construct
__construct(User $user, $stash=false, $repo=false)
Setup local pointers to stash, repo and user (similar to UploadFromStash)
Definition: UploadFromChunks.php:45
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1092
php
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
MWException
MediaWiki exception.
Definition: MWException.php:26
user
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
Definition: distributors.txt:9
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1128
UploadChunkFileException
Definition: UploadFromChunks.php:420
UploadFromChunks\addChunk
addChunk( $chunkPath, $chunkSize, $offset)
Add a chunk to the temporary directory.
Definition: UploadFromChunks.php:252
UploadFromChunks\$mChunkIndex
$mChunkIndex
Definition: UploadFromChunks.php:32
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:999
UploadFromChunks\$mOffset
$mOffset
Definition: UploadFromChunks.php:31
TempFSFile\factory
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
Definition: TempFSFile.php:55
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
UploadFromChunks\concatenateChunks
concatenateChunks()
Append the final chunk and ready file for parent::performUpload()
Definition: UploadFromChunks.php:163
UploadFromChunks\stashFile
stashFile(User $user=null)
{}
Definition: UploadFromChunks.php:84
UploadFromChunks\getChunkStatus
getChunkStatus()
Get the chunk db state and populate update relevant local values.
Definition: UploadFromChunks.php:310
MWException\msg
msg( $key, $fallback)
Get a message from i18n.
Definition: MWException.php:86
UploadFromChunks\tryStashFile
tryStashFile(User $user, $isPartial=false)
{}
Definition: UploadFromChunks.php:69
UploadFromChunks\$repo
LocalRepo $repo
Definition: UploadFromChunks.php:36
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1956
UploadFromChunks\getChunkFileKey
getChunkFileKey( $index=null)
Definition: UploadFromChunks.php:390
UploadFromChunks\$mFileKey
$mFileKey
Definition: UploadFromChunks.php:33
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2061
UploadFromChunks\getVirtualChunkLocation
getVirtualChunkLocation( $index)
Returns the virtual chunk location:
Definition: UploadFromChunks.php:235
$ext
$ext
Definition: NoLocalSettings.php:25
UploadFromFile\verifyUpload
verifyUpload()
Definition: UploadFromFile.php:80
UploadFromChunks\doStashFile
doStashFile(User $user=null)
Calls the parent doStashFile and updates the uploadsession table to handle "chunks".
Definition: UploadFromChunks.php:118
UploadFromChunks\continueChunks
continueChunks( $name, $key, $webRequestUpload)
Continue chunk uploading.
Definition: UploadFromChunks.php:145
FileRepo\DELETE_SOURCE
const DELETE_SOURCE
Definition: FileRepo.php:38
UploadChunkVerificationException\__construct
__construct( $res)
Definition: UploadFromChunks.php:425
UploadFromChunks
Implements uploading from chunks.
Definition: UploadFromChunks.php:30
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
UploadFromFile
Implements regular file uploads.
Definition: UploadFromFile.php:30
UploadChunkVerificationException\$msg
$msg
Definition: UploadFromChunks.php:424
LocalRepo
A repository that stores files in the local filesystem and registers them in the wiki's own database.
Definition: LocalRepo.php:35
UploadStashException
Definition: UploadStash.php:738
UploadChunkVerificationException
Definition: UploadFromChunks.php:423
UploadFromChunks\verifyChunk
verifyChunk()
Verify that the chunk isn't really an evil html file.
Definition: UploadFromChunks.php:403