3 * Backend for uploading files from chunks.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Implements uploading from chunks
28 * @author Michael Dale
30 class UploadFromChunks
extends UploadFromFile
{
32 protected $mChunkIndex;
34 protected $mVirtualTempPath;
39 * Setup local pointers to stash, repo and user (similar to UploadFromStash)
42 * @param UploadStash|bool $stash Default: false
43 * @param FileRepo|bool $repo Default: false
45 public function __construct( User
$user, $stash = false, $repo = false ) {
51 $this->repo
= RepoGroup
::singleton()->getLocalRepo();
55 $this->stash
= $stash;
58 wfDebug( __METHOD__
. " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
60 wfDebug( __METHOD__
. " creating new UploadFromChunks instance with no user\n" );
62 $this->stash
= new UploadStash( $this->repo
, $this->user
);
67 * Calls the parent doStashFile and updates the uploadsession table to handle "chunks"
69 * @param User|null $user
70 * @return UploadStashFile Stashed file
72 protected function doStashFile( User
$user = null ) {
73 // Stash file is the called on creating a new chunk session:
74 $this->mChunkIndex
= 0;
78 // Create a local stash target
79 $this->mStashFile
= parent
::doStashFile( $user );
80 // Update the initial file offset (based on file size)
81 $this->mOffset
= $this->mStashFile
->getSize();
82 $this->mFileKey
= $this->mStashFile
->getFileKey();
84 // Output a copy of this first to chunk 0 location:
85 $this->outputChunk( $this->mStashFile
->getPath() );
87 // Update db table to reflect initial "chunk" state
88 $this->updateChunkStatus();
90 return $this->mStashFile
;
94 * Continue chunk uploading
98 * @param WebRequestUpload $webRequestUpload
100 public function continueChunks( $name, $key, $webRequestUpload ) {
101 $this->mFileKey
= $key;
102 $this->mUpload
= $webRequestUpload;
103 // Get the chunk status form the db:
104 $this->getChunkStatus();
106 $metadata = $this->stash
->getMetadata( $key );
107 $this->initializePathInfo( $name,
108 $this->getRealPath( $metadata['us_path'] ),
109 $metadata['us_size'],
115 * Append the final chunk and ready file for parent::performUpload()
116 * @return FileRepoStatus
118 public function concatenateChunks() {
119 $chunkIndex = $this->getChunkIndex();
120 wfDebug( __METHOD__
. " concatenate {$this->mChunkIndex} chunks:" .
121 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
123 // Concatenate all the chunks to mVirtualTempPath
125 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
126 for ( $i = 0; $i <= $chunkIndex; $i++
) {
127 $fileList[] = $this->getVirtualChunkLocation( $i );
130 // Get the file extension from the last chunk
131 $ext = FileBackend
::extensionFromPath( $this->mVirtualTempPath
);
132 // Get a 0-byte temp file to perform the concatenation at
133 $tmpFile = TempFSFile
::factory( 'chunkedupload_', $ext, wfTempDir() );
134 $tmpPath = false; // fail in concatenate()
136 // keep alive with $this
137 $tmpPath = $tmpFile->bind( $this )->getPath();
140 // Concatenate the chunks at the temp file
141 $tStart = microtime( true );
142 $status = $this->repo
->concatenate( $fileList, $tmpPath, FileRepo
::DELETE_SOURCE
);
143 $tAmount = microtime( true ) - $tStart;
144 if ( !$status->isOK() ) {
148 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
150 // File system path of the actual full temp file
151 $this->setTempFile( $tmpPath );
153 $ret = $this->verifyUpload();
154 if ( $ret['status'] !== UploadBase
::OK
) {
155 wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
156 $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
161 // Update the mTempPath and mStashFile
162 // (for FileUpload or normal Stash to take over)
163 $tStart = microtime( true );
164 // This is a re-implementation of UploadBase::tryStashFile(), we can't call it because we
165 // override doStashFile() with completely different functionality in this class...
166 $error = $this->runUploadStashFileHook( $this->user
);
168 call_user_func_array( [ $status, 'fatal' ], $error );
172 $this->mStashFile
= parent
::doStashFile( $this->user
);
173 } catch ( UploadStashException
$e ) {
174 $status->fatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
178 $tAmount = microtime( true ) - $tStart;
179 $this->mStashFile
->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
180 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
186 * Returns the virtual chunk location:
190 function getVirtualChunkLocation( $index ) {
191 return $this->repo
->getVirtualUrl( 'temp' ) .
193 $this->repo
->getHashPath(
194 $this->getChunkFileKey( $index )
196 $this->getChunkFileKey( $index );
200 * Add a chunk to the temporary directory
202 * @param string $chunkPath Path to temporary chunk file
203 * @param int $chunkSize Size of the current chunk
204 * @param int $offset Offset of current chunk ( mutch match database chunk offset )
207 public function addChunk( $chunkPath, $chunkSize, $offset ) {
208 // Get the offset before we add the chunk to the file system
209 $preAppendOffset = $this->getOffset();
211 if ( $preAppendOffset +
$chunkSize > $this->getMaxUploadSize() ) {
212 $status = Status
::newFatal( 'file-too-large' );
214 // Make sure the client is uploading the correct chunk with a matching offset.
215 if ( $preAppendOffset == $offset ) {
216 // Update local chunk index for the current chunk
217 $this->mChunkIndex++
;
219 # For some reason mTempPath is set to first part
220 $oldTemp = $this->mTempPath
;
221 $this->mTempPath
= $chunkPath;
222 $this->verifyChunk();
223 $this->mTempPath
= $oldTemp;
224 } catch ( UploadChunkVerificationException
$e ) {
225 return Status
::newFatal( $e->getMessage() );
227 $status = $this->outputChunk( $chunkPath );
228 if ( $status->isGood() ) {
229 // Update local offset:
230 $this->mOffset
= $preAppendOffset +
$chunkSize;
231 // Update chunk table status db
232 $this->updateChunkStatus();
235 $status = Status
::newFatal( 'invalid-chunk-offset' );
243 * Update the chunk db table with the current status:
245 private function updateChunkStatus() {
246 wfDebug( __METHOD__
. " update chunk status for {$this->mFileKey} offset:" .
247 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
249 $dbw = $this->repo
->getMasterDB();
253 'us_status' => 'chunks',
254 'us_chunk_inx' => $this->getChunkIndex(),
255 'us_size' => $this->getOffset()
257 [ 'us_key' => $this->mFileKey
],
263 * Get the chunk db state and populate update relevant local values
265 private function getChunkStatus() {
266 // get Master db to avoid race conditions.
267 // Otherwise, if chunk upload time < replag there will be spurious errors
268 $dbw = $this->repo
->getMasterDB();
269 $row = $dbw->selectRow(
276 [ 'us_key' => $this->mFileKey
],
281 $this->mChunkIndex
= $row->us_chunk_inx
;
282 $this->mOffset
= $row->us_size
;
283 $this->mVirtualTempPath
= $row->us_path
;
288 * Get the current Chunk index
289 * @return int Index of the current chunk
291 private function getChunkIndex() {
292 if ( $this->mChunkIndex
!== null ) {
293 return $this->mChunkIndex
;
300 * Get the offset at which the next uploaded chunk will be appended to
301 * @return int Current byte offset of the chunk file set
303 public function getOffset() {
304 if ( $this->mOffset
!== null ) {
305 return $this->mOffset
;
312 * Output the chunk to disk
314 * @param string $chunkPath
315 * @throws UploadChunkFileException
316 * @return FileRepoStatus
318 private function outputChunk( $chunkPath ) {
319 // Key is fileKey + chunk index
320 $fileKey = $this->getChunkFileKey();
322 // Store the chunk per its indexed fileKey:
323 $hashPath = $this->repo
->getHashPath( $fileKey );
324 $storeStatus = $this->repo
->quickImport( $chunkPath,
325 $this->repo
->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
327 // Check for error in stashing the chunk:
328 if ( !$storeStatus->isOK() ) {
329 $error = $storeStatus->getErrorsArray();
330 $error = reset( $error );
331 if ( !count( $error ) ) {
332 $error = $storeStatus->getWarningsArray();
333 $error = reset( $error );
334 if ( !count( $error ) ) {
335 $error = [ 'unknown', 'no error recorded' ];
338 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
339 implode( '; ', $error ) );
345 private function getChunkFileKey( $index = null ) {
346 if ( $index === null ) {
347 $index = $this->getChunkIndex();
350 return $this->mFileKey
. '.' . $index;
354 * Verify that the chunk isn't really an evil html file
356 * @throws UploadChunkVerificationException
358 private function verifyChunk() {
359 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
360 $oldDesiredDestName = $this->mDesiredDestName
;
361 $this->mDesiredDestName
= $this->mFileKey
;
362 $this->mTitle
= false;
363 $res = $this->verifyPartialFile();
364 $this->mDesiredDestName
= $oldDesiredDestName;
365 $this->mTitle
= false;
366 if ( is_array( $res ) ) {
367 throw new UploadChunkVerificationException( $res[0] );
372 class UploadChunkZeroLengthFileException
extends MWException
{
375 class UploadChunkFileException
extends MWException
{
378 class UploadChunkVerificationException
extends MWException
{