wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / upload / UploadFromChunks.php
blobfe8b949235eba1d40ba5471cfad81069cca3abc6
1 <?php
2 /**
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
20 * @file
21 * @ingroup Upload
24 /**
25 * Implements uploading from chunks
27 * @ingroup Upload
28 * @author Michael Dale
30 class UploadFromChunks extends UploadFromFile {
31 protected $mOffset;
32 protected $mChunkIndex;
33 protected $mFileKey;
34 protected $mVirtualTempPath;
35 /** @var LocalRepo */
36 private $repo;
38 /**
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.
47 $this->user = $user;
49 if ( $repo ) {
50 $this->repo = $repo;
51 } else {
52 $this->repo = RepoGroup::singleton()->getLocalRepo();
55 if ( $stash ) {
56 $this->stash = $stash;
57 } else {
58 if ( $user ) {
59 wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
60 } else {
61 wfDebug( __METHOD__ . " creating new UploadFromChunks instance with no user\n" );
63 $this->stash = new UploadStash( $this->repo, $this->user );
67 /**
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;
76 $this->mOffset = 0;
78 $this->verifyChunk();
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;
94 /**
95 * Continue chunk uploading
97 * @param string $name
98 * @param string $key
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'],
111 false
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
125 $fileList = array();
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()
136 if ( $tmpFile ) {
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() ) {
146 return $status;
148 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
150 // File system path
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'] ) );
159 return $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." );
170 return $status;
174 * Returns the virtual chunk location:
175 * @param int $index
176 * @return string
178 function getVirtualChunkLocation( $index ) {
179 return $this->repo->getVirtualUrl( 'temp' ) .
180 '/' .
181 $this->repo->getHashPath(
182 $this->getChunkFileKey( $index )
184 $this->getChunkFileKey( $index );
188 * Add a chunk to the temporary directory
190 * @param string $chunkPath Path to temporary chunk file
191 * @param int $chunkSize Size of the current chunk
192 * @param int $offset Offset of current chunk ( mutch match database chunk offset )
193 * @return Status
195 public function addChunk( $chunkPath, $chunkSize, $offset ) {
196 // Get the offset before we add the chunk to the file system
197 $preAppendOffset = $this->getOffset();
199 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize() ) {
200 $status = Status::newFatal( 'file-too-large' );
201 } else {
202 // Make sure the client is uploading the correct chunk with a matching offset.
203 if ( $preAppendOffset == $offset ) {
204 // Update local chunk index for the current chunk
205 $this->mChunkIndex++;
206 try {
207 # For some reason mTempPath is set to first part
208 $oldTemp = $this->mTempPath;
209 $this->mTempPath = $chunkPath;
210 $this->verifyChunk();
211 $this->mTempPath = $oldTemp;
212 } catch ( UploadChunkVerificationException $e ) {
213 return Status::newFatal( $e->getMessage() );
215 $status = $this->outputChunk( $chunkPath );
216 if ( $status->isGood() ) {
217 // Update local offset:
218 $this->mOffset = $preAppendOffset + $chunkSize;
219 // Update chunk table status db
220 $this->updateChunkStatus();
222 } else {
223 $status = Status::newFatal( 'invalid-chunk-offset' );
227 return $status;
231 * Update the chunk db table with the current status:
233 private function updateChunkStatus() {
234 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
235 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
237 $dbw = $this->repo->getMasterDb();
238 // Use a quick transaction since we will upload the full temp file into shared
239 // storage, which takes time for large files. We don't want to hold locks then.
240 $dbw->update(
241 'uploadstash',
242 array(
243 'us_status' => 'chunks',
244 'us_chunk_inx' => $this->getChunkIndex(),
245 'us_size' => $this->getOffset()
247 array( 'us_key' => $this->mFileKey ),
248 __METHOD__
250 $dbw->commit( __METHOD__, 'flush' );
254 * Get the chunk db state and populate update relevant local values
256 private function getChunkStatus() {
257 // get Master db to avoid race conditions.
258 // Otherwise, if chunk upload time < replag there will be spurious errors
259 $dbw = $this->repo->getMasterDb();
260 $row = $dbw->selectRow(
261 'uploadstash',
262 array(
263 'us_chunk_inx',
264 'us_size',
265 'us_path',
267 array( 'us_key' => $this->mFileKey ),
268 __METHOD__
270 // Handle result:
271 if ( $row ) {
272 $this->mChunkIndex = $row->us_chunk_inx;
273 $this->mOffset = $row->us_size;
274 $this->mVirtualTempPath = $row->us_path;
279 * Get the current Chunk index
280 * @return int Index of the current chunk
282 private function getChunkIndex() {
283 if ( $this->mChunkIndex !== null ) {
284 return $this->mChunkIndex;
287 return 0;
291 * Get the offset at which the next uploaded chunk will be appended to
292 * @return int Current byte offset of the chunk file set
294 public function getOffset() {
295 if ( $this->mOffset !== null ) {
296 return $this->mOffset;
299 return 0;
303 * Output the chunk to disk
305 * @param string $chunkPath
306 * @throws UploadChunkFileException
307 * @return FileRepoStatus
309 private function outputChunk( $chunkPath ) {
310 // Key is fileKey + chunk index
311 $fileKey = $this->getChunkFileKey();
313 // Store the chunk per its indexed fileKey:
314 $hashPath = $this->repo->getHashPath( $fileKey );
315 $storeStatus = $this->repo->quickImport( $chunkPath,
316 $this->repo->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
318 // Check for error in stashing the chunk:
319 if ( !$storeStatus->isOK() ) {
320 $error = $storeStatus->getErrorsArray();
321 $error = reset( $error );
322 if ( !count( $error ) ) {
323 $error = $storeStatus->getWarningsArray();
324 $error = reset( $error );
325 if ( !count( $error ) ) {
326 $error = array( 'unknown', 'no error recorded' );
329 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
330 implode( '; ', $error ) );
333 return $storeStatus;
336 private function getChunkFileKey( $index = null ) {
337 if ( $index === null ) {
338 $index = $this->getChunkIndex();
341 return $this->mFileKey . '.' . $index;
345 * Verify that the chunk isn't really an evil html file
347 * @throws UploadChunkVerificationException
349 private function verifyChunk() {
350 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
351 $oldDesiredDestName = $this->mDesiredDestName;
352 $this->mDesiredDestName = $this->mFileKey;
353 $this->mTitle = false;
354 $res = $this->verifyPartialFile();
355 $this->mDesiredDestName = $oldDesiredDestName;
356 $this->mTitle = false;
357 if ( is_array( $res ) ) {
358 throw new UploadChunkVerificationException( $res[0] );
363 class UploadChunkZeroLengthFileException extends MWException {
366 class UploadChunkFileException extends MWException {
369 class UploadChunkVerificationException extends MWException {