Change @inheritdoc to @inheritDoc
[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 /** @var LocalRepo */
36 private $repo;
37
38 /**
39 * Setup local pointers to stash, repo and user (similar to UploadFromStash)
40 *
41 * @param User $user
42 * @param UploadStash|bool $stash Default: false
43 * @param FileRepo|bool $repo Default: false
44 */
45 public function __construct( User $user, $stash = false, $repo = false ) {
46 $this->user = $user;
47
48 if ( $repo ) {
49 $this->repo = $repo;
50 } else {
51 $this->repo = RepoGroup::singleton()->getLocalRepo();
52 }
53
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" );
61 }
62 $this->stash = new UploadStash( $this->repo, $this->user );
63 }
64 }
65
66 /**
67 * @inheritDoc
68 */
69 public function tryStashFile( User $user, $isPartial = false ) {
70 try {
71 $this->verifyChunk();
72 } catch ( UploadChunkVerificationException $e ) {
73 return Status::newFatal( $e->msg );
74 }
75
76 return parent::tryStashFile( $user, $isPartial );
77 }
78
79 /**
80 * @inheritDoc
81 * @throws UploadChunkVerificationException
82 * @deprecated since 1.28 Use tryStashFile() instead
83 */
84 public function stashFile( User $user = null ) {
85 wfDeprecated( __METHOD__, '1.28' );
86 $this->verifyChunk();
87 return parent::stashFile( $user );
88 }
89
90 /**
91 * @inheritDoc
92 * @throws UploadChunkVerificationException
93 * @deprecated since 1.28
94 */
95 public function stashFileGetKey() {
96 wfDeprecated( __METHOD__, '1.28' );
97 $this->verifyChunk();
98 return parent::stashFileGetKey();
99 }
100
101 /**
102 * @inheritDoc
103 * @throws UploadChunkVerificationException
104 * @deprecated since 1.28
105 */
106 public function stashSession() {
107 wfDeprecated( __METHOD__, '1.28' );
108 $this->verifyChunk();
109 return parent::stashSession();
110 }
111
112 /**
113 * Calls the parent doStashFile and updates the uploadsession table to handle "chunks"
114 *
115 * @param User|null $user
116 * @return UploadStashFile Stashed file
117 */
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;
122
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();
128
129 // Output a copy of this first to chunk 0 location:
130 $this->outputChunk( $this->mStashFile->getPath() );
131
132 // Update db table to reflect initial "chunk" state
133 $this->updateChunkStatus();
134
135 return $this->mStashFile;
136 }
137
138 /**
139 * Continue chunk uploading
140 *
141 * @param string $name
142 * @param string $key
143 * @param WebRequestUpload $webRequestUpload
144 */
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();
150
151 $metadata = $this->stash->getMetadata( $key );
152 $this->initializePathInfo( $name,
153 $this->getRealPath( $metadata['us_path'] ),
154 $metadata['us_size'],
155 false
156 );
157 }
158
159 /**
160 * Append the final chunk and ready file for parent::performUpload()
161 * @return Status
162 */
163 public function concatenateChunks() {
164 $chunkIndex = $this->getChunkIndex();
165 wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
166 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
167
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 );
173 }
174
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();
183 }
184
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;
191 }
192
193 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
194
195 // File system path of the actual full temp file
196 $this->setTempFile( $tmpPath );
197
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'] ) );
202
203 return $status;
204 }
205
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;
215 }
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;
221 }
222
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." );
226
227 return $status;
228 }
229
230 /**
231 * Returns the virtual chunk location:
232 * @param int $index
233 * @return string
234 */
235 function getVirtualChunkLocation( $index ) {
236 return $this->repo->getVirtualUrl( 'temp' ) .
237 '/' .
238 $this->repo->getHashPath(
239 $this->getChunkFileKey( $index )
240 ) .
241 $this->getChunkFileKey( $index );
242 }
243
244 /**
245 * Add a chunk to the temporary directory
246 *
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
251 */
252 public function addChunk( $chunkPath, $chunkSize, $offset ) {
253 // Get the offset before we add the chunk to the file system
254 $preAppendOffset = $this->getOffset();
255
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 );
271 }
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();
278 }
279 } else {
280 $status = Status::newFatal( 'invalid-chunk-offset' );
281 }
282 }
283
284 return $status;
285 }
286
287 /**
288 * Update the chunk db table with the current status:
289 */
290 private function updateChunkStatus() {
291 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
292 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
293
294 $dbw = $this->repo->getMasterDB();
295 $dbw->update(
296 'uploadstash',
297 [
298 'us_status' => 'chunks',
299 'us_chunk_inx' => $this->getChunkIndex(),
300 'us_size' => $this->getOffset()
301 ],
302 [ 'us_key' => $this->mFileKey ],
303 __METHOD__
304 );
305 }
306
307 /**
308 * Get the chunk db state and populate update relevant local values
309 */
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',
316 [
317 'us_chunk_inx',
318 'us_size',
319 'us_path',
320 ],
321 [ 'us_key' => $this->mFileKey ],
322 __METHOD__
323 );
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;
329 }
330 }
331
332 /**
333 * Get the current Chunk index
334 * @return int Index of the current chunk
335 */
336 private function getChunkIndex() {
337 if ( $this->mChunkIndex !== null ) {
338 return $this->mChunkIndex;
339 }
340
341 return 0;
342 }
343
344 /**
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
347 */
348 public function getOffset() {
349 if ( $this->mOffset !== null ) {
350 return $this->mOffset;
351 }
352
353 return 0;
354 }
355
356 /**
357 * Output the chunk to disk
358 *
359 * @param string $chunkPath
360 * @throws UploadChunkFileException
361 * @return Status
362 */
363 private function outputChunk( $chunkPath ) {
364 // Key is fileKey + chunk index
365 $fileKey = $this->getChunkFileKey();
366
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}" );
371
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' ];
381 }
382 }
383 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
384 implode( '; ', $error ) );
385 }
386
387 return $storeStatus;
388 }
389
390 private function getChunkFileKey( $index = null ) {
391 if ( $index === null ) {
392 $index = $this->getChunkIndex();
393 }
394
395 return $this->mFileKey . '.' . $index;
396 }
397
398 /**
399 * Verify that the chunk isn't really an evil html file
400 *
401 * @throws UploadChunkVerificationException
402 */
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 );
413 }
414 }
415 }
416
417 class UploadChunkZeroLengthFileException extends MWException {
418 }
419
420 class UploadChunkFileException extends MWException {
421 }
422
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() );
429 }
430 }