MediaWiki REL1_30
UploadFromChunks.php
Go to the documentation of this file.
1<?php
31 protected $mOffset;
32 protected $mChunkIndex;
33 protected $mFileKey;
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
419
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}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTempDir()
Tries to get the system directory for temporary files.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
const DELETE_SOURCE
Definition FileRepo.php:38
A repository that stores files in the local filesystem and registers them in the wiki's own database.
Definition LocalRepo.php:35
MediaWiki exception.
msg( $key, $fallback)
Get a message from i18n.
static singleton()
Get a RepoGroup instance.
Definition RepoGroup.php:59
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
string $mTempPath
Local file system path to the file to upload (or a local copy)
getRealPath( $srcPath)
runUploadStashFileHook(User $user)
verifyPartialFile()
A verification routine suitable for partial files.
getVerificationErrorCode( $error)
setTempFile( $tempPath, $fileSize=null)
initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile=false)
Initialize the path information.
static getMaxUploadSize( $forType=null)
Get the MediaWiki maximum uploaded file size for given type of upload, based on $wgMaxUploadSize.
Implements uploading from chunks.
addChunk( $chunkPath, $chunkSize, $offset)
Add a chunk to the temporary directory.
outputChunk( $chunkPath)
Output the chunk to disk.
doStashFile(User $user=null)
Calls the parent doStashFile and updates the uploadsession table to handle "chunks".
getChunkFileKey( $index=null)
stashSession()
@inheritDoc
stashFile(User $user=null)
@inheritDoc
continueChunks( $name, $key, $webRequestUpload)
Continue chunk uploading.
tryStashFile(User $user, $isPartial=false)
@inheritDoc
getVirtualChunkLocation( $index)
Returns the virtual chunk location:
__construct(User $user, $stash=false, $repo=false)
Setup local pointers to stash, repo and user (similar to UploadFromStash)
getOffset()
Get the offset at which the next uploaded chunk will be appended to.
updateChunkStatus()
Update the chunk db table with the current status:
getChunkStatus()
Get the chunk db state and populate update relevant local values.
concatenateChunks()
Append the final chunk and ready file for parent::performUpload()
stashFileGetKey()
@inheritDoc
verifyChunk()
Verify that the chunk isn't really an evil html file.
getChunkIndex()
Get the current Chunk index.
Implements regular file uploads.
UploadStash is intended to accomplish a few things:
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:51
$res
Definition database.txt:21
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:18
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:1975
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. '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). '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:1049
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 local account $user
Definition hooks.txt:247
returning false will NOT prevent logging $e
Definition hooks.txt:2146