Merge "Fix API output formatting (change lines delimited with * as bold)"
[mediawiki.git] / includes / upload / UploadFromChunks.php
blob5a838ab69b831307144bc65cdd1b2a087b84cdc9
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, $mChunkIndex, $mFileKey, $mVirtualTempPath;
33 /**
34 * Setup local pointers to stash, repo and user ( similar to UploadFromStash )
36 * @param $user User
37 * @param $stash UploadStash
38 * @param $repo FileRepo
40 public function __construct( $user = null, $stash = false, $repo = false ) {
41 // user object. sometimes this won't exist, as when running from cron.
42 $this->user = $user;
44 if( $repo ) {
45 $this->repo = $repo;
46 } else {
47 $this->repo = RepoGroup::singleton()->getLocalRepo();
50 if( $stash ) {
51 $this->stash = $stash;
52 } else {
53 if( $user ) {
54 wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
55 } else {
56 wfDebug( __METHOD__ . " creating new UploadFromChunks instance with no user\n" );
58 $this->stash = new UploadStash( $this->repo, $this->user );
61 return true;
64 /**
65 * Calls the parent stashFile and updates the uploadsession table to handle "chunks"
67 * @return UploadStashFile stashed file
69 public function stashFile() {
70 // Stash file is the called on creating a new chunk session:
71 $this->mChunkIndex = 0;
72 $this->mOffset = 0;
73 // Create a local stash target
74 $this->mLocalFile = parent::stashFile();
75 // Update the initial file offset ( based on file size )
76 $this->mOffset = $this->mLocalFile->getSize();
77 $this->mFileKey = $this->mLocalFile->getFileKey();
79 // Output a copy of this first to chunk 0 location:
80 $this->outputChunk( $this->mLocalFile->getPath() );
82 // Update db table to reflect initial "chunk" state
83 $this->updateChunkStatus();
84 return $this->mLocalFile;
87 /**
88 * Continue chunk uploading
90 public function continueChunks( $name, $key, $webRequestUpload ) {
91 $this->mFileKey = $key;
92 $this->mUpload = $webRequestUpload;
93 // Get the chunk status form the db:
94 $this->getChunkStatus();
96 $metadata = $this->stash->getMetadata( $key );
97 $this->initializePathInfo( $name,
98 $this->getRealPath( $metadata['us_path'] ),
99 $metadata['us_size'],
100 false
105 * Append the final chunk and ready file for parent::performUpload()
106 * @return FileRepoStatus
108 public function concatenateChunks() {
109 wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
110 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
112 // Concatenate all the chunks to mVirtualTempPath
113 $fileList = Array();
114 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
115 for( $i = 0; $i <= $this->getChunkIndex(); $i++ ) {
116 $fileList[] = $this->getVirtualChunkLocation( $i );
119 // Get the file extension from the last chunk
120 $ext = FileBackend::extensionFromPath( $this->mVirtualTempPath );
121 // Get a 0-byte temp file to perform the concatenation at
122 $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext );
123 $tmpPath = $tmpFile
124 ? $tmpFile->bind( $this )->getPath() // keep alive with $this
125 : false; // fail in concatenate()
126 // Concatenate the chunks at the temp file
127 $tStart = microtime( true );
128 $status = $this->repo->concatenate( $fileList, $tmpPath, FileRepo::DELETE_SOURCE );
129 $tAmount = microtime( true ) - $tStart;
130 if( !$status->isOk() ) {
131 return $status;
133 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds.\n" );
134 // Update the mTempPath and mLocalFile
135 // ( for FileUpload or normal Stash to take over )
136 $this->mTempPath = $tmpPath; // file system path
137 $tStart = microtime( true );
138 $this->mLocalFile = parent::stashFile( $this->user );
139 $tAmount = microtime( true ) - $tStart;
140 $this->mLocalFile->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
141 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds.\n" );
143 return $status;
147 * Perform the upload, then remove the temp copy afterward
148 * @param $comment string
149 * @param $pageText string
150 * @param $watch bool
151 * @param $user User
152 * @return Status
154 public function performUpload( $comment, $pageText, $watch, $user ) {
155 $rv = parent::performUpload( $comment, $pageText, $watch, $user );
156 return $rv;
160 * Returns the virtual chunk location:
161 * @param $index
162 * @return string
164 function getVirtualChunkLocation( $index ) {
165 return $this->repo->getVirtualUrl( 'temp' ) .
166 '/' .
167 $this->repo->getHashPath(
168 $this->getChunkFileKey( $index )
170 $this->getChunkFileKey( $index );
174 * Add a chunk to the temporary directory
176 * @param $chunkPath string path to temporary chunk file
177 * @param $chunkSize int size of the current chunk
178 * @param $offset int offset of current chunk ( mutch match database chunk offset )
179 * @return Status
181 public function addChunk( $chunkPath, $chunkSize, $offset ) {
182 // Get the offset before we add the chunk to the file system
183 $preAppendOffset = $this->getOffset();
185 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize()) {
186 $status = Status::newFatal( 'file-too-large' );
187 } else {
188 // Make sure the client is uploading the correct chunk with a matching offset.
189 if ( $preAppendOffset == $offset ) {
190 // Update local chunk index for the current chunk
191 $this->mChunkIndex++;
192 $status = $this->outputChunk( $chunkPath );
193 if( $status->isGood() ) {
194 // Update local offset:
195 $this->mOffset = $preAppendOffset + $chunkSize;
196 // Update chunk table status db
197 $this->updateChunkStatus();
199 } else {
200 $status = Status::newFatal( 'invalid-chunk-offset' );
203 return $status;
207 * Update the chunk db table with the current status:
209 private function updateChunkStatus() {
210 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
211 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
213 $dbw = $this->repo->getMasterDb();
214 // Use a quick transaction since we will upload the full temp file into shared
215 // storage, which takes time for large files. We don't want to hold locks then.
216 $dbw->begin( __METHOD__ );
217 $dbw->update(
218 'uploadstash',
219 array(
220 'us_status' => 'chunks',
221 'us_chunk_inx' => $this->getChunkIndex(),
222 'us_size' => $this->getOffset()
224 array( 'us_key' => $this->mFileKey ),
225 __METHOD__
227 $dbw->commit( __METHOD__ );
231 * Get the chunk db state and populate update relevant local values
233 private function getChunkStatus() {
234 // get Master db to avoid race conditions.
235 // Otherwise, if chunk upload time < replag there will be spurious errors
236 $dbw = $this->repo->getMasterDb();
237 $row = $dbw->selectRow(
238 'uploadstash',
239 array(
240 'us_chunk_inx',
241 'us_size',
242 'us_path',
244 array( 'us_key' => $this->mFileKey ),
245 __METHOD__
247 // Handle result:
248 if ( $row ) {
249 $this->mChunkIndex = $row->us_chunk_inx;
250 $this->mOffset = $row->us_size;
251 $this->mVirtualTempPath = $row->us_path;
256 * Get the current Chunk index
257 * @return Integer index of the current chunk
259 private function getChunkIndex() {
260 if( $this->mChunkIndex !== null ) {
261 return $this->mChunkIndex;
263 return 0;
267 * Gets the current offset in fromt the stashedupload table
268 * @return Integer current byte offset of the chunk file set
270 private function getOffset() {
271 if ( $this->mOffset !== null ) {
272 return $this->mOffset;
274 return 0;
278 * Output the chunk to disk
280 * @param $chunkPath string
281 * @throws UploadChunkFileException
282 * @return FileRepoStatus
284 private function outputChunk( $chunkPath ) {
285 // Key is fileKey + chunk index
286 $fileKey = $this->getChunkFileKey();
288 // Store the chunk per its indexed fileKey:
289 $hashPath = $this->repo->getHashPath( $fileKey );
290 $storeStatus = $this->repo->quickImport( $chunkPath,
291 $this->repo->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
293 // Check for error in stashing the chunk:
294 if ( ! $storeStatus->isOK() ) {
295 $error = $storeStatus->getErrorsArray();
296 $error = reset( $error );
297 if ( ! count( $error ) ) {
298 $error = $storeStatus->getWarningsArray();
299 $error = reset( $error );
300 if ( ! count( $error ) ) {
301 $error = array( 'unknown', 'no error recorded' );
304 throw new UploadChunkFileException( "error storing file in '$chunkPath': " . implode( '; ', $error ) );
306 return $storeStatus;
309 private function getChunkFileKey( $index = null ) {
310 if( $index === null ) {
311 $index = $this->getChunkIndex();
313 return $this->mFileKey . '.' . $index;
317 class UploadChunkZeroLengthFileException extends MWException {};
318 class UploadChunkFileException extends MWException {};