Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / upload / UploadFromChunks.php
blobc0c2cb5c31961c6071cc214f063b2c603c0164c7
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 $user
42 * @param UploadStash|bool $stash Default: false
43 * @param FileRepo|bool $repo Default: false
45 public function __construct( User $user, $stash = false, $repo = false ) {
46 $this->user = $user;
48 if ( $repo ) {
49 $this->repo = $repo;
50 } else {
51 $this->repo = RepoGroup::singleton()->getLocalRepo();
54 if ( $stash ) {
55 $this->stash = $stash;
56 } else {
57 if ( $user ) {
58 wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
59 } else {
60 wfDebug( __METHOD__ . " creating new UploadFromChunks instance with no user\n" );
62 $this->stash = new UploadStash( $this->repo, $this->user );
66 /**
67 * {@inheritdoc}
69 public function tryStashFile( User $user, $isPartial = false ) {
70 try {
71 $this->verifyChunk();
72 } catch ( UploadChunkVerificationException $e ) {
73 return Status::newFatal( $e->msg );
76 return parent::tryStashFile( $user, $isPartial );
79 /**
80 * {@inheritdoc}
81 * @throws UploadChunkVerificationException
82 * @deprecated since 1.28 Use tryStashFile() instead
84 public function stashFile( User $user = null ) {
85 wfDeprecated( __METHOD__, '1.28' );
86 $this->verifyChunk();
87 return parent::stashFile( $user );
90 /**
91 * {@inheritdoc}
92 * @throws UploadChunkVerificationException
93 * @deprecated since 1.28
95 public function stashFileGetKey() {
96 wfDeprecated( __METHOD__, '1.28' );
97 $this->verifyChunk();
98 return parent::stashFileGetKey();
102 * {@inheritdoc}
103 * @throws UploadChunkVerificationException
104 * @deprecated since 1.28
106 public function stashSession() {
107 wfDeprecated( __METHOD__, '1.28' );
108 $this->verifyChunk();
109 return parent::stashSession();
113 * Calls the parent doStashFile and updates the uploadsession table to handle "chunks"
115 * @param User|null $user
116 * @return UploadStashFile Stashed file
118 protected function doStashFile( User $user = null ) {
119 // Stash file is the called on creating a new chunk session:
120 $this->mChunkIndex = 0;
121 $this->mOffset = 0;
123 // Create a local stash target
124 $this->mStashFile = parent::doStashFile( $user );
125 // Update the initial file offset (based on file size)
126 $this->mOffset = $this->mStashFile->getSize();
127 $this->mFileKey = $this->mStashFile->getFileKey();
129 // Output a copy of this first to chunk 0 location:
130 $this->outputChunk( $this->mStashFile->getPath() );
132 // Update db table to reflect initial "chunk" state
133 $this->updateChunkStatus();
135 return $this->mStashFile;
139 * Continue chunk uploading
141 * @param string $name
142 * @param string $key
143 * @param WebRequestUpload $webRequestUpload
145 public function continueChunks( $name, $key, $webRequestUpload ) {
146 $this->mFileKey = $key;
147 $this->mUpload = $webRequestUpload;
148 // Get the chunk status form the db:
149 $this->getChunkStatus();
151 $metadata = $this->stash->getMetadata( $key );
152 $this->initializePathInfo( $name,
153 $this->getRealPath( $metadata['us_path'] ),
154 $metadata['us_size'],
155 false
160 * Append the final chunk and ready file for parent::performUpload()
161 * @return Status
163 public function concatenateChunks() {
164 $chunkIndex = $this->getChunkIndex();
165 wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
166 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
168 // Concatenate all the chunks to mVirtualTempPath
169 $fileList = [];
170 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
171 for ( $i = 0; $i <= $chunkIndex; $i++ ) {
172 $fileList[] = $this->getVirtualChunkLocation( $i );
175 // Get the file extension from the last chunk
176 $ext = FileBackend::extensionFromPath( $this->mVirtualTempPath );
177 // Get a 0-byte temp file to perform the concatenation at
178 $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext, wfTempDir() );
179 $tmpPath = false; // fail in concatenate()
180 if ( $tmpFile ) {
181 // keep alive with $this
182 $tmpPath = $tmpFile->bind( $this )->getPath();
185 // Concatenate the chunks at the temp file
186 $tStart = microtime( true );
187 $status = $this->repo->concatenate( $fileList, $tmpPath, FileRepo::DELETE_SOURCE );
188 $tAmount = microtime( true ) - $tStart;
189 if ( !$status->isOK() ) {
190 return $status;
193 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
195 // File system path of the actual full temp file
196 $this->setTempFile( $tmpPath );
198 $ret = $this->verifyUpload();
199 if ( $ret['status'] !== UploadBase::OK ) {
200 wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
201 $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
203 return $status;
206 // Update the mTempPath and mStashFile
207 // (for FileUpload or normal Stash to take over)
208 $tStart = microtime( true );
209 // This is a re-implementation of UploadBase::tryStashFile(), we can't call it because we
210 // override doStashFile() with completely different functionality in this class...
211 $error = $this->runUploadStashFileHook( $this->user );
212 if ( $error ) {
213 call_user_func_array( [ $status, 'fatal' ], $error );
214 return $status;
216 try {
217 $this->mStashFile = parent::doStashFile( $this->user );
218 } catch ( UploadStashException $e ) {
219 $status->fatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
220 return $status;
223 $tAmount = microtime( true ) - $tStart;
224 $this->mStashFile->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
225 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
227 return $status;
231 * Returns the virtual chunk location:
232 * @param int $index
233 * @return string
235 function getVirtualChunkLocation( $index ) {
236 return $this->repo->getVirtualUrl( 'temp' ) .
237 '/' .
238 $this->repo->getHashPath(
239 $this->getChunkFileKey( $index )
241 $this->getChunkFileKey( $index );
245 * Add a chunk to the temporary directory
247 * @param string $chunkPath Path to temporary chunk file
248 * @param int $chunkSize Size of the current chunk
249 * @param int $offset Offset of current chunk ( mutch match database chunk offset )
250 * @return Status
252 public function addChunk( $chunkPath, $chunkSize, $offset ) {
253 // Get the offset before we add the chunk to the file system
254 $preAppendOffset = $this->getOffset();
256 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize() ) {
257 $status = Status::newFatal( 'file-too-large' );
258 } else {
259 // Make sure the client is uploading the correct chunk with a matching offset.
260 if ( $preAppendOffset == $offset ) {
261 // Update local chunk index for the current chunk
262 $this->mChunkIndex++;
263 try {
264 # For some reason mTempPath is set to first part
265 $oldTemp = $this->mTempPath;
266 $this->mTempPath = $chunkPath;
267 $this->verifyChunk();
268 $this->mTempPath = $oldTemp;
269 } catch ( UploadChunkVerificationException $e ) {
270 return Status::newFatal( $e->msg );
272 $status = $this->outputChunk( $chunkPath );
273 if ( $status->isGood() ) {
274 // Update local offset:
275 $this->mOffset = $preAppendOffset + $chunkSize;
276 // Update chunk table status db
277 $this->updateChunkStatus();
279 } else {
280 $status = Status::newFatal( 'invalid-chunk-offset' );
284 return $status;
288 * Update the chunk db table with the current status:
290 private function updateChunkStatus() {
291 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
292 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
294 $dbw = $this->repo->getMasterDB();
295 $dbw->update(
296 'uploadstash',
298 'us_status' => 'chunks',
299 'us_chunk_inx' => $this->getChunkIndex(),
300 'us_size' => $this->getOffset()
302 [ 'us_key' => $this->mFileKey ],
303 __METHOD__
308 * Get the chunk db state and populate update relevant local values
310 private function getChunkStatus() {
311 // get Master db to avoid race conditions.
312 // Otherwise, if chunk upload time < replag there will be spurious errors
313 $dbw = $this->repo->getMasterDB();
314 $row = $dbw->selectRow(
315 'uploadstash',
317 'us_chunk_inx',
318 'us_size',
319 'us_path',
321 [ 'us_key' => $this->mFileKey ],
322 __METHOD__
324 // Handle result:
325 if ( $row ) {
326 $this->mChunkIndex = $row->us_chunk_inx;
327 $this->mOffset = $row->us_size;
328 $this->mVirtualTempPath = $row->us_path;
333 * Get the current Chunk index
334 * @return int Index of the current chunk
336 private function getChunkIndex() {
337 if ( $this->mChunkIndex !== null ) {
338 return $this->mChunkIndex;
341 return 0;
345 * Get the offset at which the next uploaded chunk will be appended to
346 * @return int Current byte offset of the chunk file set
348 public function getOffset() {
349 if ( $this->mOffset !== null ) {
350 return $this->mOffset;
353 return 0;
357 * Output the chunk to disk
359 * @param string $chunkPath
360 * @throws UploadChunkFileException
361 * @return Status
363 private function outputChunk( $chunkPath ) {
364 // Key is fileKey + chunk index
365 $fileKey = $this->getChunkFileKey();
367 // Store the chunk per its indexed fileKey:
368 $hashPath = $this->repo->getHashPath( $fileKey );
369 $storeStatus = $this->repo->quickImport( $chunkPath,
370 $this->repo->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
372 // Check for error in stashing the chunk:
373 if ( !$storeStatus->isOK() ) {
374 $error = $storeStatus->getErrorsArray();
375 $error = reset( $error );
376 if ( !count( $error ) ) {
377 $error = $storeStatus->getWarningsArray();
378 $error = reset( $error );
379 if ( !count( $error ) ) {
380 $error = [ 'unknown', 'no error recorded' ];
383 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
384 implode( '; ', $error ) );
387 return $storeStatus;
390 private function getChunkFileKey( $index = null ) {
391 if ( $index === null ) {
392 $index = $this->getChunkIndex();
395 return $this->mFileKey . '.' . $index;
399 * Verify that the chunk isn't really an evil html file
401 * @throws UploadChunkVerificationException
403 private function verifyChunk() {
404 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
405 $oldDesiredDestName = $this->mDesiredDestName;
406 $this->mDesiredDestName = $this->mFileKey;
407 $this->mTitle = false;
408 $res = $this->verifyPartialFile();
409 $this->mDesiredDestName = $oldDesiredDestName;
410 $this->mTitle = false;
411 if ( is_array( $res ) ) {
412 throw new UploadChunkVerificationException( $res );
417 class UploadChunkZeroLengthFileException extends MWException {
420 class UploadChunkFileException extends MWException {
423 class UploadChunkVerificationException extends MWException {
424 public $msg;
425 public function __construct( $res ) {
426 $this->msg = call_user_func_array( 'wfMessage', $res );
427 parent::__construct( call_user_func_array( 'wfMessage', $res )
428 ->inLanguage( 'en' )->useDatabase( false )->text() );