Set Redis::OPT_READ_TIMEOUT by default
[mediawiki.git] / includes / upload / UploadFromChunks.php
blobd15ae43b360b85851eaf5163fe7f645da5937376
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;
36 /**
37 * Setup local pointers to stash, repo and user (similar to UploadFromStash)
39 * @param User|null $user Default: null
40 * @param UploadStash|bool $stash Default: false
41 * @param FileRepo|bool $repo 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.
45 $this->user = $user;
47 if ( $repo ) {
48 $this->repo = $repo;
49 } else {
50 $this->repo = RepoGroup::singleton()->getLocalRepo();
53 if ( $stash ) {
54 $this->stash = $stash;
55 } else {
56 if ( $user ) {
57 wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
58 } else {
59 wfDebug( __METHOD__ . " creating new UploadFromChunks instance with no user\n" );
61 $this->stash = new UploadStash( $this->repo, $this->user );
64 return true;
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();
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();
90 return $this->mLocalFile;
93 /**
94 * Continue chunk uploading
96 * @param string $name
97 * @param string $key
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'],
110 false
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
124 $fileList = array();
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 );
134 $tmpPath = false; // fail in concatenate()
135 if ( $tmpFile ) {
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() ) {
145 return $status;
147 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
149 // File system path
150 $this->mTempPath = $tmpPath;
151 // Since this was set for the last chunk previously
152 $this->mFileSize = filesize( $this->mTempPath );
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'] ) );
157 return $status;
160 // Update the mTempPath and mLocalFile
161 // (for FileUpload or normal Stash to take over)
162 $tStart = microtime( true );
163 $this->mLocalFile = parent::stashFile( $this->user );
164 $tAmount = microtime( true ) - $tStart;
165 $this->mLocalFile->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
166 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
168 return $status;
172 * Perform the upload, then remove the temp copy afterward
173 * @param string $comment
174 * @param string $pageText
175 * @param bool $watch
176 * @param User $user
177 * @return Status
179 public function performUpload( $comment, $pageText, $watch, $user ) {
180 $rv = parent::performUpload( $comment, $pageText, $watch, $user );
181 return $rv;
185 * Returns the virtual chunk location:
186 * @param int $index
187 * @return string
189 function getVirtualChunkLocation( $index ) {
190 return $this->repo->getVirtualUrl( 'temp' ) .
191 '/' .
192 $this->repo->getHashPath(
193 $this->getChunkFileKey( $index )
195 $this->getChunkFileKey( $index );
199 * Add a chunk to the temporary directory
201 * @param string $chunkPath path to temporary chunk file
202 * @param int $chunkSize size of the current chunk
203 * @param int $offset offset of current chunk ( mutch match database chunk offset )
204 * @return Status
206 public function addChunk( $chunkPath, $chunkSize, $offset ) {
207 // Get the offset before we add the chunk to the file system
208 $preAppendOffset = $this->getOffset();
210 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize() ) {
211 $status = Status::newFatal( 'file-too-large' );
212 } else {
213 // Make sure the client is uploading the correct chunk with a matching offset.
214 if ( $preAppendOffset == $offset ) {
215 // Update local chunk index for the current chunk
216 $this->mChunkIndex++;
217 try {
218 # For some reason mTempPath is set to first part
219 $oldTemp = $this->mTempPath;
220 $this->mTempPath = $chunkPath;
221 $this->verifyChunk();
222 $this->mTempPath = $oldTemp;
223 } catch ( UploadChunkVerificationException $e ) {
224 return Status::newFatal( $e->getMessage() );
226 $status = $this->outputChunk( $chunkPath );
227 if ( $status->isGood() ) {
228 // Update local offset:
229 $this->mOffset = $preAppendOffset + $chunkSize;
230 // Update chunk table status db
231 $this->updateChunkStatus();
233 } else {
234 $status = Status::newFatal( 'invalid-chunk-offset' );
237 return $status;
241 * Update the chunk db table with the current status:
243 private function updateChunkStatus() {
244 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
245 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
247 $dbw = $this->repo->getMasterDb();
248 // Use a quick transaction since we will upload the full temp file into shared
249 // storage, which takes time for large files. We don't want to hold locks then.
250 $dbw->begin( __METHOD__ );
251 $dbw->update(
252 'uploadstash',
253 array(
254 'us_status' => 'chunks',
255 'us_chunk_inx' => $this->getChunkIndex(),
256 'us_size' => $this->getOffset()
258 array( 'us_key' => $this->mFileKey ),
259 __METHOD__
261 $dbw->commit( __METHOD__ );
265 * Get the chunk db state and populate update relevant local values
267 private function getChunkStatus() {
268 // get Master db to avoid race conditions.
269 // Otherwise, if chunk upload time < replag there will be spurious errors
270 $dbw = $this->repo->getMasterDb();
271 $row = $dbw->selectRow(
272 'uploadstash',
273 array(
274 'us_chunk_inx',
275 'us_size',
276 'us_path',
278 array( 'us_key' => $this->mFileKey ),
279 __METHOD__
281 // Handle result:
282 if ( $row ) {
283 $this->mChunkIndex = $row->us_chunk_inx;
284 $this->mOffset = $row->us_size;
285 $this->mVirtualTempPath = $row->us_path;
290 * Get the current Chunk index
291 * @return int Index of the current chunk
293 private function getChunkIndex() {
294 if ( $this->mChunkIndex !== null ) {
295 return $this->mChunkIndex;
297 return 0;
301 * Gets the current offset in fromt the stashedupload table
302 * @return int Current byte offset of the chunk file set
304 private function getOffset() {
305 if ( $this->mOffset !== null ) {
306 return $this->mOffset;
308 return 0;
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 = array( 'unknown', 'no error recorded' );
338 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
339 implode( '; ', $error ) );
341 return $storeStatus;
344 private function getChunkFileKey( $index = null ) {
345 if ( $index === null ) {
346 $index = $this->getChunkIndex();
348 return $this->mFileKey . '.' . $index;
352 * Verify that the chunk isn't really an evil html file
354 * @throws UploadChunkVerificationException
356 private function verifyChunk() {
357 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
358 $oldDesiredDestName = $this->mDesiredDestName;
359 $this->mDesiredDestName = $this->mFileKey;
360 $this->mTitle = false;
361 $res = $this->verifyPartialFile();
362 $this->mDesiredDestName = $oldDesiredDestName;
363 $this->mTitle = false;
364 if ( is_array( $res ) ) {
365 throw new UploadChunkVerificationException( $res[0] );
370 class UploadChunkZeroLengthFileException extends MWException {
373 class UploadChunkFileException extends MWException {
376 class UploadChunkVerificationException extends MWException {