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)
41 * @param User|null $user Default: null
42 * @param UploadStash|bool $stash Default: false
43 * @param FileRepo|bool $repo Default: false
45 public function __construct( $user = null, $stash = false, $repo = false ) {
46 // user object. sometimes this won't exist, as when running from cron.
52 $this->repo
= RepoGroup
::singleton()->getLocalRepo();
56 $this->stash
= $stash;
59 wfDebug( __METHOD__
. " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
61 wfDebug( __METHOD__
. " creating new UploadFromChunks instance with no user\n" );
63 $this->stash
= new UploadStash( $this->repo
, $this->user
);
68 * Calls the parent stashFile and updates the uploadsession table to handle "chunks"
70 * @param User|null $user
71 * @return UploadStashFile Stashed file
73 public function stashFile( User
$user = null ) {
74 // Stash file is the called on creating a new chunk session:
75 $this->mChunkIndex
= 0;
79 // Create a local stash target
80 $this->mLocalFile
= parent
::stashFile( $user );
81 // Update the initial file offset (based on file size)
82 $this->mOffset
= $this->mLocalFile
->getSize();
83 $this->mFileKey
= $this->mLocalFile
->getFileKey();
85 // Output a copy of this first to chunk 0 location:
86 $this->outputChunk( $this->mLocalFile
->getPath() );
88 // Update db table to reflect initial "chunk" state
89 $this->updateChunkStatus();
91 return $this->mLocalFile
;
95 * Continue chunk uploading
99 * @param WebRequestUpload $webRequestUpload
101 public function continueChunks( $name, $key, $webRequestUpload ) {
102 $this->mFileKey
= $key;
103 $this->mUpload
= $webRequestUpload;
104 // Get the chunk status form the db:
105 $this->getChunkStatus();
107 $metadata = $this->stash
->getMetadata( $key );
108 $this->initializePathInfo( $name,
109 $this->getRealPath( $metadata['us_path'] ),
110 $metadata['us_size'],
116 * Append the final chunk and ready file for parent::performUpload()
117 * @return FileRepoStatus
119 public function concatenateChunks() {
120 $chunkIndex = $this->getChunkIndex();
121 wfDebug( __METHOD__
. " concatenate {$this->mChunkIndex} chunks:" .
122 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
124 // Concatenate all the chunks to mVirtualTempPath
126 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
127 for ( $i = 0; $i <= $chunkIndex; $i++
) {
128 $fileList[] = $this->getVirtualChunkLocation( $i );
131 // Get the file extension from the last chunk
132 $ext = FileBackend
::extensionFromPath( $this->mVirtualTempPath
);
133 // Get a 0-byte temp file to perform the concatenation at
134 $tmpFile = TempFSFile
::factory( 'chunkedupload_', $ext );
135 $tmpPath = false; // fail in concatenate()
137 // keep alive with $this
138 $tmpPath = $tmpFile->bind( $this )->getPath();
141 // Concatenate the chunks at the temp file
142 $tStart = microtime( true );
143 $status = $this->repo
->concatenate( $fileList, $tmpPath, FileRepo
::DELETE_SOURCE
);
144 $tAmount = microtime( true ) - $tStart;
145 if ( !$status->isOk() ) {
148 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
151 $this->mTempPath
= $tmpPath;
152 // Since this was set for the last chunk previously
153 $this->mFileSize
= filesize( $this->mTempPath
);
154 $ret = $this->verifyUpload();
155 if ( $ret['status'] !== UploadBase
::OK
) {
156 wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
157 $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
162 // Update the mTempPath and mLocalFile
163 // (for FileUpload or normal Stash to take over)
164 $tStart = microtime( true );
165 $this->mLocalFile
= parent
::stashFile( $this->user
);
166 $tAmount = microtime( true ) - $tStart;
167 $this->mLocalFile
->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
168 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
174 * Perform the upload, then remove the temp copy afterward
175 * @param string $comment
176 * @param string $pageText
181 public function performUpload( $comment, $pageText, $watch, $user ) {
182 $rv = parent
::performUpload( $comment, $pageText, $watch, $user );
188 * Returns the virtual chunk location:
192 function getVirtualChunkLocation( $index ) {
193 return $this->repo
->getVirtualUrl( 'temp' ) .
195 $this->repo
->getHashPath(
196 $this->getChunkFileKey( $index )
198 $this->getChunkFileKey( $index );
202 * Add a chunk to the temporary directory
204 * @param string $chunkPath Path to temporary chunk file
205 * @param int $chunkSize Size of the current chunk
206 * @param int $offset Offset of current chunk ( mutch match database chunk offset )
209 public function addChunk( $chunkPath, $chunkSize, $offset ) {
210 // Get the offset before we add the chunk to the file system
211 $preAppendOffset = $this->getOffset();
213 if ( $preAppendOffset +
$chunkSize > $this->getMaxUploadSize() ) {
214 $status = Status
::newFatal( 'file-too-large' );
216 // Make sure the client is uploading the correct chunk with a matching offset.
217 if ( $preAppendOffset == $offset ) {
218 // Update local chunk index for the current chunk
219 $this->mChunkIndex++
;
221 # For some reason mTempPath is set to first part
222 $oldTemp = $this->mTempPath
;
223 $this->mTempPath
= $chunkPath;
224 $this->verifyChunk();
225 $this->mTempPath
= $oldTemp;
226 } catch ( UploadChunkVerificationException
$e ) {
227 return Status
::newFatal( $e->getMessage() );
229 $status = $this->outputChunk( $chunkPath );
230 if ( $status->isGood() ) {
231 // Update local offset:
232 $this->mOffset
= $preAppendOffset +
$chunkSize;
233 // Update chunk table status db
234 $this->updateChunkStatus();
237 $status = Status
::newFatal( 'invalid-chunk-offset' );
245 * Update the chunk db table with the current status:
247 private function updateChunkStatus() {
248 wfDebug( __METHOD__
. " update chunk status for {$this->mFileKey} offset:" .
249 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
251 $dbw = $this->repo
->getMasterDb();
252 // Use a quick transaction since we will upload the full temp file into shared
253 // storage, which takes time for large files. We don't want to hold locks then.
254 $dbw->begin( __METHOD__
);
258 'us_status' => 'chunks',
259 'us_chunk_inx' => $this->getChunkIndex(),
260 'us_size' => $this->getOffset()
262 array( 'us_key' => $this->mFileKey
),
265 $dbw->commit( __METHOD__
);
269 * Get the chunk db state and populate update relevant local values
271 private function getChunkStatus() {
272 // get Master db to avoid race conditions.
273 // Otherwise, if chunk upload time < replag there will be spurious errors
274 $dbw = $this->repo
->getMasterDb();
275 $row = $dbw->selectRow(
282 array( 'us_key' => $this->mFileKey
),
287 $this->mChunkIndex
= $row->us_chunk_inx
;
288 $this->mOffset
= $row->us_size
;
289 $this->mVirtualTempPath
= $row->us_path
;
294 * Get the current Chunk index
295 * @return int Index of the current chunk
297 private function getChunkIndex() {
298 if ( $this->mChunkIndex
!== null ) {
299 return $this->mChunkIndex
;
306 * Get the offset at which the next uploaded chunk will be appended to
307 * @return int Current byte offset of the chunk file set
309 public function getOffset() {
310 if ( $this->mOffset
!== null ) {
311 return $this->mOffset
;
318 * Output the chunk to disk
320 * @param string $chunkPath
321 * @throws UploadChunkFileException
322 * @return FileRepoStatus
324 private function outputChunk( $chunkPath ) {
325 // Key is fileKey + chunk index
326 $fileKey = $this->getChunkFileKey();
328 // Store the chunk per its indexed fileKey:
329 $hashPath = $this->repo
->getHashPath( $fileKey );
330 $storeStatus = $this->repo
->quickImport( $chunkPath,
331 $this->repo
->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
333 // Check for error in stashing the chunk:
334 if ( !$storeStatus->isOK() ) {
335 $error = $storeStatus->getErrorsArray();
336 $error = reset( $error );
337 if ( !count( $error ) ) {
338 $error = $storeStatus->getWarningsArray();
339 $error = reset( $error );
340 if ( !count( $error ) ) {
341 $error = array( 'unknown', 'no error recorded' );
344 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
345 implode( '; ', $error ) );
351 private function getChunkFileKey( $index = null ) {
352 if ( $index === null ) {
353 $index = $this->getChunkIndex();
356 return $this->mFileKey
. '.' . $index;
360 * Verify that the chunk isn't really an evil html file
362 * @throws UploadChunkVerificationException
364 private function verifyChunk() {
365 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
366 $oldDesiredDestName = $this->mDesiredDestName
;
367 $this->mDesiredDestName
= $this->mFileKey
;
368 $this->mTitle
= false;
369 $res = $this->verifyPartialFile();
370 $this->mDesiredDestName
= $oldDesiredDestName;
371 $this->mTitle
= false;
372 if ( is_array( $res ) ) {
373 throw new UploadChunkVerificationException( $res[0] );
378 class UploadChunkZeroLengthFileException
extends MWException
{
381 class UploadChunkFileException
extends MWException
{
384 class UploadChunkVerificationException
extends MWException
{