Fixed spacing
[lhc/web/wiklou.git] / includes / upload / UploadFromChunks.php
1 <?php
2 /**
3 * Backend for uploading files from chunks.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Upload
22 */
23
24 /**
25 * Implements uploading from chunks
26 *
27 * @ingroup Upload
28 * @author Michael Dale
29 */
30 class UploadFromChunks extends UploadFromFile {
31 protected $mOffset;
32 protected $mChunkIndex;
33 protected $mFileKey;
34 protected $mVirtualTempPath;
35
36 /**
37 * Setup local pointers to stash, repo and user (similar to UploadFromStash)
38 *
39 * @param $user User|null Default: null
40 * @param $stash UploadStash|bool Default: false
41 * @param $repo FileRepo|bool Default: false
42 */
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;
46
47 if ( $repo ) {
48 $this->repo = $repo;
49 } else {
50 $this->repo = RepoGroup::singleton()->getLocalRepo();
51 }
52
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" );
60 }
61 $this->stash = new UploadStash( $this->repo, $this->user );
62 }
63
64 return true;
65 }
66
67 /**
68 * Calls the parent stashFile and updates the uploadsession table to handle "chunks"
69 *
70 * @return UploadStashFile stashed file
71 */
72 public function stashFile( User $user = null ) {
73 // Stash file is the called on creating a new chunk session:
74 $this->mChunkIndex = 0;
75 $this->mOffset = 0;
76
77 $this->verifyChunk();
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();
83
84 // Output a copy of this first to chunk 0 location:
85 $this->outputChunk( $this->mLocalFile->getPath() );
86
87 // Update db table to reflect initial "chunk" state
88 $this->updateChunkStatus();
89 return $this->mLocalFile;
90 }
91
92 /**
93 * Continue chunk uploading
94 */
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();
100
101 $metadata = $this->stash->getMetadata( $key );
102 $this->initializePathInfo( $name,
103 $this->getRealPath( $metadata['us_path'] ),
104 $metadata['us_size'],
105 false
106 );
107 }
108
109 /**
110 * Append the final chunk and ready file for parent::performUpload()
111 * @return FileRepoStatus
112 */
113 public function concatenateChunks() {
114 $chunkIndex = $this->getChunkIndex();
115 wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
116 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
117
118 // Concatenate all the chunks to mVirtualTempPath
119 $fileList = array();
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 );
123 }
124
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()
130 if ( $tmpFile ) {
131 // keep alive with $this
132 $tmpPath = $tmpFile->bind( $this )->getPath();
133 }
134
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() ) {
140 return $status;
141 }
142 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds.\n" );
143
144 // File system path
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'] ) );
152 return $status;
153 }
154
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" );
162
163 return $status;
164 }
165
166 /**
167 * Perform the upload, then remove the temp copy afterward
168 * @param $comment string
169 * @param $pageText string
170 * @param $watch bool
171 * @param $user User
172 * @return Status
173 */
174 public function performUpload( $comment, $pageText, $watch, $user ) {
175 $rv = parent::performUpload( $comment, $pageText, $watch, $user );
176 return $rv;
177 }
178
179 /**
180 * Returns the virtual chunk location:
181 * @param $index
182 * @return string
183 */
184 function getVirtualChunkLocation( $index ) {
185 return $this->repo->getVirtualUrl( 'temp' ) .
186 '/' .
187 $this->repo->getHashPath(
188 $this->getChunkFileKey( $index )
189 ) .
190 $this->getChunkFileKey( $index );
191 }
192
193 /**
194 * Add a chunk to the temporary directory
195 *
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 )
199 * @return Status
200 */
201 public function addChunk( $chunkPath, $chunkSize, $offset ) {
202 // Get the offset before we add the chunk to the file system
203 $preAppendOffset = $this->getOffset();
204
205 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize() ) {
206 $status = Status::newFatal( 'file-too-large' );
207 } else {
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++;
212 try {
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() );
220 }
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();
227 }
228 } else {
229 $status = Status::newFatal( 'invalid-chunk-offset' );
230 }
231 }
232 return $status;
233 }
234
235 /**
236 * Update the chunk db table with the current status:
237 */
238 private function updateChunkStatus() {
239 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
240 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
241
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__ );
246 $dbw->update(
247 'uploadstash',
248 array(
249 'us_status' => 'chunks',
250 'us_chunk_inx' => $this->getChunkIndex(),
251 'us_size' => $this->getOffset()
252 ),
253 array( 'us_key' => $this->mFileKey ),
254 __METHOD__
255 );
256 $dbw->commit( __METHOD__ );
257 }
258
259 /**
260 * Get the chunk db state and populate update relevant local values
261 */
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(
267 'uploadstash',
268 array(
269 'us_chunk_inx',
270 'us_size',
271 'us_path',
272 ),
273 array( 'us_key' => $this->mFileKey ),
274 __METHOD__
275 );
276 // Handle result:
277 if ( $row ) {
278 $this->mChunkIndex = $row->us_chunk_inx;
279 $this->mOffset = $row->us_size;
280 $this->mVirtualTempPath = $row->us_path;
281 }
282 }
283
284 /**
285 * Get the current Chunk index
286 * @return Integer index of the current chunk
287 */
288 private function getChunkIndex() {
289 if ( $this->mChunkIndex !== null ) {
290 return $this->mChunkIndex;
291 }
292 return 0;
293 }
294
295 /**
296 * Gets the current offset in fromt the stashedupload table
297 * @return Integer current byte offset of the chunk file set
298 */
299 private function getOffset() {
300 if ( $this->mOffset !== null ) {
301 return $this->mOffset;
302 }
303 return 0;
304 }
305
306 /**
307 * Output the chunk to disk
308 *
309 * @param $chunkPath string
310 * @throws UploadChunkFileException
311 * @return FileRepoStatus
312 */
313 private function outputChunk( $chunkPath ) {
314 // Key is fileKey + chunk index
315 $fileKey = $this->getChunkFileKey();
316
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}" );
321
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' );
331 }
332 }
333 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
334 implode( '; ', $error ) );
335 }
336 return $storeStatus;
337 }
338
339 private function getChunkFileKey( $index = null ) {
340 if ( $index === null ) {
341 $index = $this->getChunkIndex();
342 }
343 return $this->mFileKey . '.' . $index;
344 }
345
346 /**
347 * Verify that the chunk isn't really an evil html file
348 *
349 * @throws UploadChunkVerificationException
350 */
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] );
361 }
362 }
363 }
364
365 class UploadChunkZeroLengthFileException extends MWException {
366 }
367
368 class UploadChunkFileException extends MWException {
369 }
370
371 class UploadChunkVerificationException extends MWException {
372 }