MediaWiki  1.33.0
Go to the documentation of this file.
1 <?php
31  protected $mOffset;
32  protected $mChunkIndex;
33  protected $mFileKey;
34  protected $mVirtualTempPath;
36  private $repo;
45  public function __construct( User $user, $stash = false, $repo = false ) {
46  $this->user = $user;
48  if ( $repo ) {
49  $this->repo = $repo;
50  } else {
51  $this->repo = RepoGroup::singleton()->getLocalRepo();
52  }
54  if ( $stash ) {
55  $this->stash = $stash;
56  } else {
57  wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
58  $this->stash = new UploadStash( $this->repo, $this->user );
59  }
60  }
65  public function tryStashFile( User $user, $isPartial = false ) {
66  try {
67  $this->verifyChunk();
69  return Status::newFatal( $e->msg );
70  }
72  return parent::tryStashFile( $user, $isPartial );
73  }
80  public function stashFile( User $user = null ) {
81  wfDeprecated( __METHOD__, '1.28' );
82  $this->verifyChunk();
83  return parent::stashFile( $user );
84  }
91  public function stashFileGetKey() {
92  wfDeprecated( __METHOD__, '1.28' );
93  $this->verifyChunk();
94  return parent::stashFileGetKey();
95  }
102  public function stashSession() {
103  wfDeprecated( __METHOD__, '1.28' );
104  $this->verifyChunk();
105  return parent::stashSession();
106  }
114  protected function doStashFile( User $user = null ) {
115  // Stash file is the called on creating a new chunk session:
116  $this->mChunkIndex = 0;
117  $this->mOffset = 0;
119  // Create a local stash target
120  $this->mStashFile = parent::doStashFile( $user );
121  // Update the initial file offset (based on file size)
122  $this->mOffset = $this->mStashFile->getSize();
123  $this->mFileKey = $this->mStashFile->getFileKey();
125  // Output a copy of this first to chunk 0 location:
126  $this->outputChunk( $this->mStashFile->getPath() );
128  // Update db table to reflect initial "chunk" state
129  $this->updateChunkStatus();
131  return $this->mStashFile;
132  }
141  public function continueChunks( $name, $key, $webRequestUpload ) {
142  $this->mFileKey = $key;
143  $this->mUpload = $webRequestUpload;
144  // Get the chunk status form the db:
145  $this->getChunkStatus();
147  $metadata = $this->stash->getMetadata( $key );
148  $this->initializePathInfo( $name,
149  $this->getRealPath( $metadata['us_path'] ),
150  $metadata['us_size'],
151  false
152  );
153  }
159  public function concatenateChunks() {
160  $chunkIndex = $this->getChunkIndex();
161  wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
162  $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
164  // Concatenate all the chunks to mVirtualTempPath
165  $fileList = [];
166  // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
167  for ( $i = 0; $i <= $chunkIndex; $i++ ) {
168  $fileList[] = $this->getVirtualChunkLocation( $i );
169  }
171  // Get the file extension from the last chunk
172  $ext = FileBackend::extensionFromPath( $this->mVirtualTempPath );
173  // Get a 0-byte temp file to perform the concatenation at
174  $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext, wfTempDir() );
175  $tmpPath = false; // fail in concatenate()
176  if ( $tmpFile ) {
177  // keep alive with $this
178  $tmpPath = $tmpFile->bind( $this )->getPath();
179  }
181  // Concatenate the chunks at the temp file
182  $tStart = microtime( true );
183  $status = $this->repo->concatenate( $fileList, $tmpPath, FileRepo::DELETE_SOURCE );
184  $tAmount = microtime( true ) - $tStart;
185  if ( !$status->isOK() ) {
186  return $status;
187  }
189  wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
191  // File system path of the actual full temp file
192  $this->setTempFile( $tmpPath );
194  $ret = $this->verifyUpload();
195  if ( $ret['status'] !== UploadBase::OK ) {
196  wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
197  $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
199  return $status;
200  }
202  // Update the mTempPath and mStashFile
203  // (for FileUpload or normal Stash to take over)
204  $tStart = microtime( true );
205  // This is a re-implementation of UploadBase::tryStashFile(), we can't call it because we
206  // override doStashFile() with completely different functionality in this class...
207  $error = $this->runUploadStashFileHook( $this->user );
208  if ( $error ) {
209  $status->fatal( ...$error );
210  return $status;
211  }
212  try {
213  $this->mStashFile = parent::doStashFile( $this->user );
214  } catch ( UploadStashException $e ) {
215  $status->fatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
216  return $status;
217  }
219  $tAmount = microtime( true ) - $tStart;
220  $this->mStashFile->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
221  wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
223  return $status;
224  }
231  function getVirtualChunkLocation( $index ) {
232  return $this->repo->getVirtualUrl( 'temp' ) .
233  '/' .
234  $this->repo->getHashPath(
235  $this->getChunkFileKey( $index )
236  ) .
237  $this->getChunkFileKey( $index );
238  }
248  public function addChunk( $chunkPath, $chunkSize, $offset ) {
249  // Get the offset before we add the chunk to the file system
250  $preAppendOffset = $this->getOffset();
252  if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize() ) {
253  $status = Status::newFatal( 'file-too-large' );
254  } else {
255  // Make sure the client is uploading the correct chunk with a matching offset.
256  if ( $preAppendOffset == $offset ) {
257  // Update local chunk index for the current chunk
258  $this->mChunkIndex++;
259  try {
260  # For some reason mTempPath is set to first part
261  $oldTemp = $this->mTempPath;
262  $this->mTempPath = $chunkPath;
263  $this->verifyChunk();
264  $this->mTempPath = $oldTemp;
266  return Status::newFatal( $e->msg );
267  }
268  $status = $this->outputChunk( $chunkPath );
269  if ( $status->isGood() ) {
270  // Update local offset:
271  $this->mOffset = $preAppendOffset + $chunkSize;
272  // Update chunk table status db
273  $this->updateChunkStatus();
274  }
275  } else {
276  $status = Status::newFatal( 'invalid-chunk-offset' );
277  }
278  }
280  return $status;
281  }
286  private function updateChunkStatus() {
287  wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
288  $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
290  $dbw = $this->repo->getMasterDB();
291  $dbw->update(
292  'uploadstash',
293  [
294  'us_status' => 'chunks',
295  'us_chunk_inx' => $this->getChunkIndex(),
296  'us_size' => $this->getOffset()
297  ],
298  [ 'us_key' => $this->mFileKey ],
299  __METHOD__
300  );
301  }
306  private function getChunkStatus() {
307  // get Master db to avoid race conditions.
308  // Otherwise, if chunk upload time < replag there will be spurious errors
309  $dbw = $this->repo->getMasterDB();
310  $row = $dbw->selectRow(
311  'uploadstash',
312  [
313  'us_chunk_inx',
314  'us_size',
315  'us_path',
316  ],
317  [ 'us_key' => $this->mFileKey ],
318  __METHOD__
319  );
320  // Handle result:
321  if ( $row ) {
322  $this->mChunkIndex = $row->us_chunk_inx;
323  $this->mOffset = $row->us_size;
324  $this->mVirtualTempPath = $row->us_path;
325  }
326  }
332  private function getChunkIndex() {
333  if ( $this->mChunkIndex !== null ) {
334  return $this->mChunkIndex;
335  }
337  return 0;
338  }
344  public function getOffset() {
345  if ( $this->mOffset !== null ) {
346  return $this->mOffset;
347  }
349  return 0;
350  }
359  private function outputChunk( $chunkPath ) {
360  // Key is fileKey + chunk index
361  $fileKey = $this->getChunkFileKey();
363  // Store the chunk per its indexed fileKey:
364  $hashPath = $this->repo->getHashPath( $fileKey );
365  $storeStatus = $this->repo->quickImport( $chunkPath,
366  $this->repo->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
368  // Check for error in stashing the chunk:
369  if ( !$storeStatus->isOK() ) {
370  $error = $storeStatus->getErrorsArray();
371  $error = reset( $error );
372  if ( !count( $error ) ) {
373  $error = $storeStatus->getWarningsArray();
374  $error = reset( $error );
375  if ( !count( $error ) ) {
376  $error = [ 'unknown', 'no error recorded' ];
377  }
378  }
379  throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
380  implode( '; ', $error ) );
381  }
383  return $storeStatus;
384  }
386  private function getChunkFileKey( $index = null ) {
387  if ( $index === null ) {
388  $index = $this->getChunkIndex();
389  }
391  return $this->mFileKey . '.' . $index;
392  }
399  private function verifyChunk() {
400  // Rest mDesiredDestName here so we verify the name as if it were mFileKey
401  $oldDesiredDestName = $this->mDesiredDestName;
402  $this->mDesiredDestName = $this->mFileKey;
403  $this->mTitle = false;
404  $res = $this->verifyPartialFile();
405  $this->mDesiredDestName = $oldDesiredDestName;
406  $this->mTitle = false;
407  if ( is_array( $res ) ) {
409  }
410  }
411 }
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1266
Update the chunk db table with the current status:
Definition: UploadFromChunks.php:286
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
Definition: UploadFromChunks.php:91
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:61
Get the offset at which the next uploaded chunk will be appended to.
Definition: UploadFromChunks.php:344
Get the current Chunk index.
Definition: UploadFromChunks.php:332
outputChunk( $chunkPath)
Output the chunk to disk.
Definition: UploadFromChunks.php:359
Definition: UploadFromChunks.php:34
UploadStash is intended to accomplish a few things:
Definition: UploadStash.php:53
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1490
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
Definition: database.txt:21
Definition: UploadFromChunks.php:102
__construct(User $user, $stash=false, $repo=false)
Setup local pointers to stash, repo and user (similar to UploadFromStash)
Definition: UploadFromChunks.php:45
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:1043
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
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( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1078
Definition: UploadChunkFileException.php:24
addChunk( $chunkPath, $chunkSize, $offset)
Add a chunk to the temporary directory.
Definition: UploadFromChunks.php:248
Definition: UploadFromChunks.php:32
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:949
Definition: UploadFromChunks.php:31
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
Definition: TempFSFile.php:55
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
Append the final chunk and ready file for parent::performUpload()
Definition: UploadFromChunks.php:159
stashFile(User $user=null)
Definition: UploadFromChunks.php:80
Get the chunk db state and populate update relevant local values.
Definition: UploadFromChunks.php:306
tryStashFile(User $user, $isPartial=false)
Definition: UploadFromChunks.php:65
LocalRepo $repo
Definition: UploadFromChunks.php:36
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:1985
getChunkFileKey( $index=null)
Definition: UploadFromChunks.php:386
Definition: UploadFromChunks.php:33
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1989
getVirtualChunkLocation( $index)
Returns the virtual chunk location:
Definition: UploadFromChunks.php:231
Definition: UploadFromFile.php:80
doStashFile(User $user=null)
Calls the parent doStashFile and updates the uploadsession table to handle "chunks".
Definition: UploadFromChunks.php:114
continueChunks( $name, $key, $webRequestUpload)
Continue chunk uploading.
Definition: UploadFromChunks.php:141
if(!is_readable( $file)) $ext
Definition: router.php:48
Definition: FileRepo.php:40
Implements uploading from chunks.
Definition: UploadFromChunks.php:30
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
Implements regular file uploads.
Definition: UploadFromFile.php:30
A repository that stores files in the local filesystem and registers them in the wiki's own database.
Definition: LocalRepo.php:36
Definition: UploadStashException.php:26
Definition: UploadChunkVerificationException.php:24
Verify that the chunk isn't really an evil html file.
Definition: UploadFromChunks.php:399