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;
37 * Setup local pointers to stash, repo and user (similar to UploadFromStash)
39 * @param $user User|null Default: null
40 * @param $stash UploadStash|bool Default: false
41 * @param $repo FileRepo|bool Default: false
43 public function __construct( $user = null, $stash = false, $repo = false ) {
44 // user object. sometimes this won't exist, as when running from cron.
50 $this->repo
= RepoGroup
::singleton()->getLocalRepo();
54 $this->stash
= $stash;
57 wfDebug( __METHOD__
. " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
59 wfDebug( __METHOD__
. " creating new UploadFromChunks instance with no user\n" );
61 $this->stash
= new UploadStash( $this->repo
, $this->user
);
68 * Calls the parent stashFile and updates the uploadsession table to handle "chunks"
70 * @return UploadStashFile stashed file
72 public function stashFile( 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->mLocalFile
= parent
::stashFile();
80 // Update the initial file offset (based on file size)
81 $this->mOffset
= $this->mLocalFile
->getSize();
82 $this->mFileKey
= $this->mLocalFile
->getFileKey();
84 // Output a copy of this first to chunk 0 location:
85 $this->outputChunk( $this->mLocalFile
->getPath() );
87 // Update db table to reflect initial "chunk" state
88 $this->updateChunkStatus();
89 return $this->mLocalFile
;
93 * Continue chunk uploading
95 public function continueChunks( $name, $key, $webRequestUpload ) {
96 $this->mFileKey
= $key;
97 $this->mUpload
= $webRequestUpload;
98 // Get the chunk status form the db:
99 $this->getChunkStatus();
101 $metadata = $this->stash
->getMetadata( $key );
102 $this->initializePathInfo( $name,
103 $this->getRealPath( $metadata['us_path'] ),
104 $metadata['us_size'],
110 * Append the final chunk and ready file for parent::performUpload()
111 * @return FileRepoStatus
113 public function concatenateChunks() {
114 $chunkIndex = $this->getChunkIndex();
115 wfDebug( __METHOD__
. " concatenate {$this->mChunkIndex} chunks:" .
116 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
118 // Concatenate all the chunks to mVirtualTempPath
120 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
121 for ( $i = 0; $i <= $chunkIndex; $i++
) {
122 $fileList[] = $this->getVirtualChunkLocation( $i );
125 // Get the file extension from the last chunk
126 $ext = FileBackend
::extensionFromPath( $this->mVirtualTempPath
);
127 // Get a 0-byte temp file to perform the concatenation at
128 $tmpFile = TempFSFile
::factory( 'chunkedupload_', $ext );
129 $tmpPath = false; // fail in concatenate()
131 // keep alive with $this
132 $tmpPath = $tmpFile->bind( $this )->getPath();
135 // Concatenate the chunks at the temp file
136 $tStart = microtime( true );
137 $status = $this->repo
->concatenate( $fileList, $tmpPath, FileRepo
::DELETE_SOURCE
);
138 $tAmount = microtime( true ) - $tStart;
139 if ( !$status->isOk() ) {
142 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds.\n" );
145 $this->mTempPath
= $tmpPath;
146 // Since this was set for the last chunk previously
147 $this->mFileSize
= filesize( $this->mTempPath
);
148 $ret = $this->verifyUpload();
149 if ( $ret['status'] !== UploadBase
::OK
) {
150 wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
151 $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
155 // Update the mTempPath and mLocalFile
156 // (for FileUpload or normal Stash to take over)
157 $tStart = microtime( true );
158 $this->mLocalFile
= parent
::stashFile( $this->user
);
159 $tAmount = microtime( true ) - $tStart;
160 $this->mLocalFile
->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
161 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds.\n" );
167 * Perform the upload, then remove the temp copy afterward
168 * @param $comment string
169 * @param $pageText string
174 public function performUpload( $comment, $pageText, $watch, $user ) {
175 $rv = parent
::performUpload( $comment, $pageText, $watch, $user );
180 * Returns the virtual chunk location:
184 function getVirtualChunkLocation( $index ) {
185 return $this->repo
->getVirtualUrl( 'temp' ) .
187 $this->repo
->getHashPath(
188 $this->getChunkFileKey( $index )
190 $this->getChunkFileKey( $index );
194 * Add a chunk to the temporary directory
196 * @param string $chunkPath path to temporary chunk file
197 * @param int $chunkSize size of the current chunk
198 * @param int $offset offset of current chunk ( mutch match database chunk offset )
201 public function addChunk( $chunkPath, $chunkSize, $offset ) {
202 // Get the offset before we add the chunk to the file system
203 $preAppendOffset = $this->getOffset();
205 if ( $preAppendOffset +
$chunkSize > $this->getMaxUploadSize() ) {
206 $status = Status
::newFatal( 'file-too-large' );
208 // Make sure the client is uploading the correct chunk with a matching offset.
209 if ( $preAppendOffset == $offset ) {
210 // Update local chunk index for the current chunk
211 $this->mChunkIndex++
;
213 # For some reason mTempPath is set to first part
214 $oldTemp = $this->mTempPath
;
215 $this->mTempPath
= $chunkPath;
216 $this->verifyChunk();
217 $this->mTempPath
= $oldTemp;
218 } catch ( UploadChunkVerificationException
$e ) {
219 return Status
::newFatal( $e->getMessage() );
221 $status = $this->outputChunk( $chunkPath );
222 if ( $status->isGood() ) {
223 // Update local offset:
224 $this->mOffset
= $preAppendOffset +
$chunkSize;
225 // Update chunk table status db
226 $this->updateChunkStatus();
229 $status = Status
::newFatal( 'invalid-chunk-offset' );
236 * Update the chunk db table with the current status:
238 private function updateChunkStatus() {
239 wfDebug( __METHOD__
. " update chunk status for {$this->mFileKey} offset:" .
240 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
242 $dbw = $this->repo
->getMasterDb();
243 // Use a quick transaction since we will upload the full temp file into shared
244 // storage, which takes time for large files. We don't want to hold locks then.
245 $dbw->begin( __METHOD__
);
249 'us_status' => 'chunks',
250 'us_chunk_inx' => $this->getChunkIndex(),
251 'us_size' => $this->getOffset()
253 array( 'us_key' => $this->mFileKey
),
256 $dbw->commit( __METHOD__
);
260 * Get the chunk db state and populate update relevant local values
262 private function getChunkStatus() {
263 // get Master db to avoid race conditions.
264 // Otherwise, if chunk upload time < replag there will be spurious errors
265 $dbw = $this->repo
->getMasterDb();
266 $row = $dbw->selectRow(
273 array( 'us_key' => $this->mFileKey
),
278 $this->mChunkIndex
= $row->us_chunk_inx
;
279 $this->mOffset
= $row->us_size
;
280 $this->mVirtualTempPath
= $row->us_path
;
285 * Get the current Chunk index
286 * @return Integer index of the current chunk
288 private function getChunkIndex() {
289 if ( $this->mChunkIndex
!== null ) {
290 return $this->mChunkIndex
;
296 * Gets the current offset in fromt the stashedupload table
297 * @return Integer current byte offset of the chunk file set
299 private function getOffset() {
300 if ( $this->mOffset
!== null ) {
301 return $this->mOffset
;
307 * Output the chunk to disk
309 * @param $chunkPath string
310 * @throws UploadChunkFileException
311 * @return FileRepoStatus
313 private function outputChunk( $chunkPath ) {
314 // Key is fileKey + chunk index
315 $fileKey = $this->getChunkFileKey();
317 // Store the chunk per its indexed fileKey:
318 $hashPath = $this->repo
->getHashPath( $fileKey );
319 $storeStatus = $this->repo
->quickImport( $chunkPath,
320 $this->repo
->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
322 // Check for error in stashing the chunk:
323 if ( ! $storeStatus->isOK() ) {
324 $error = $storeStatus->getErrorsArray();
325 $error = reset( $error );
326 if ( ! count( $error ) ) {
327 $error = $storeStatus->getWarningsArray();
328 $error = reset( $error );
329 if ( ! count( $error ) ) {
330 $error = array( 'unknown', 'no error recorded' );
333 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
334 implode( '; ', $error ) );
339 private function getChunkFileKey( $index = null ) {
340 if ( $index === null ) {
341 $index = $this->getChunkIndex();
343 return $this->mFileKey
. '.' . $index;
347 * Verify that the chunk isn't really an evil html file
349 * @throws UploadChunkVerificationException
351 private function verifyChunk() {
352 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
353 $oldDesiredDestName = $this->mDesiredDestName
;
354 $this->mDesiredDestName
= $this->mFileKey
;
355 $this->mTitle
= false;
356 $res = $this->verifyPartialFile();
357 $this->mDesiredDestName
= $oldDesiredDestName;
358 $this->mTitle
= false;
359 if ( is_array( $res ) ) {
360 throw new UploadChunkVerificationException( $res[0] );
365 class UploadChunkZeroLengthFileException
extends MWException
{
368 class UploadChunkFileException
extends MWException
{
371 class UploadChunkVerificationException
extends MWException
{