Merge "Add change-tags to MessagePoster"
[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 /** @var LocalRepo */
32 private $repo;
33 /** @var UploadStash */
34 public $stash;
35 /** @var User */
36 public $user;
37
38 protected $mOffset;
39 protected $mChunkIndex;
40 protected $mFileKey;
41 protected $mVirtualTempPath;
42
43 /** @noinspection PhpMissingParentConstructorInspection */
44
45 /**
46 * Setup local pointers to stash, repo and user (similar to UploadFromStash)
47 *
48 * @param User $user
49 * @param UploadStash|bool $stash Default: false
50 * @param FileRepo|bool $repo Default: false
51 */
52 public function __construct( User $user, $stash = false, $repo = false ) {
53 $this->user = $user;
54
55 if ( $repo ) {
56 $this->repo = $repo;
57 } else {
58 $this->repo = RepoGroup::singleton()->getLocalRepo();
59 }
60
61 if ( $stash ) {
62 $this->stash = $stash;
63 } else {
64 wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
65 $this->stash = new UploadStash( $this->repo, $this->user );
66 }
67 }
68
69 /**
70 * @inheritDoc
71 */
72 public function tryStashFile( User $user, $isPartial = false ) {
73 try {
74 $this->verifyChunk();
75 } catch ( UploadChunkVerificationException $e ) {
76 return Status::newFatal( $e->msg );
77 }
78
79 return parent::tryStashFile( $user, $isPartial );
80 }
81
82 /**
83 * @inheritDoc
84 * @throws UploadChunkVerificationException
85 * @deprecated since 1.28 Use tryStashFile() instead
86 */
87 public function stashFile( User $user = null ) {
88 wfDeprecated( __METHOD__, '1.28' );
89 $this->verifyChunk();
90 return parent::stashFile( $user );
91 }
92
93 /**
94 * @inheritDoc
95 * @throws UploadChunkVerificationException
96 * @deprecated since 1.28
97 */
98 public function stashFileGetKey() {
99 wfDeprecated( __METHOD__, '1.28' );
100 $this->verifyChunk();
101 return parent::stashFileGetKey();
102 }
103
104 /**
105 * @inheritDoc
106 * @throws UploadChunkVerificationException
107 * @deprecated since 1.28
108 */
109 public function stashSession() {
110 wfDeprecated( __METHOD__, '1.28' );
111 $this->verifyChunk();
112 return parent::stashSession();
113 }
114
115 /**
116 * Calls the parent doStashFile and updates the uploadsession table to handle "chunks"
117 *
118 * @param User|null $user
119 * @return UploadStashFile Stashed file
120 */
121 protected function doStashFile( User $user = null ) {
122 // Stash file is the called on creating a new chunk session:
123 $this->mChunkIndex = 0;
124 $this->mOffset = 0;
125
126 // Create a local stash target
127 $this->mStashFile = parent::doStashFile( $user );
128 // Update the initial file offset (based on file size)
129 $this->mOffset = $this->mStashFile->getSize();
130 $this->mFileKey = $this->mStashFile->getFileKey();
131
132 // Output a copy of this first to chunk 0 location:
133 $this->outputChunk( $this->mStashFile->getPath() );
134
135 // Update db table to reflect initial "chunk" state
136 $this->updateChunkStatus();
137
138 return $this->mStashFile;
139 }
140
141 /**
142 * Continue chunk uploading
143 *
144 * @param string $name
145 * @param string $key
146 * @param WebRequestUpload $webRequestUpload
147 */
148 public function continueChunks( $name, $key, $webRequestUpload ) {
149 $this->mFileKey = $key;
150 $this->mUpload = $webRequestUpload;
151 // Get the chunk status form the db:
152 $this->getChunkStatus();
153
154 $metadata = $this->stash->getMetadata( $key );
155 $this->initializePathInfo( $name,
156 $this->getRealPath( $metadata['us_path'] ),
157 $metadata['us_size'],
158 false
159 );
160 }
161
162 /**
163 * Append the final chunk and ready file for parent::performUpload()
164 * @return Status
165 */
166 public function concatenateChunks() {
167 $chunkIndex = $this->getChunkIndex();
168 wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
169 $this->getOffset() . ' inx:' . $chunkIndex . "\n" );
170
171 // Concatenate all the chunks to mVirtualTempPath
172 $fileList = [];
173 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
174 for ( $i = 0; $i <= $chunkIndex; $i++ ) {
175 $fileList[] = $this->getVirtualChunkLocation( $i );
176 }
177
178 // Get the file extension from the last chunk
179 $ext = FileBackend::extensionFromPath( $this->mVirtualTempPath );
180 // Get a 0-byte temp file to perform the concatenation at
181 $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext, wfTempDir() );
182 $tmpPath = false; // fail in concatenate()
183 if ( $tmpFile ) {
184 // keep alive with $this
185 $tmpPath = $tmpFile->bind( $this )->getPath();
186 }
187
188 // Concatenate the chunks at the temp file
189 $tStart = microtime( true );
190 $status = $this->repo->concatenate( $fileList, $tmpPath, FileRepo::DELETE_SOURCE );
191 $tAmount = microtime( true ) - $tStart;
192 if ( !$status->isOK() ) {
193 return $status;
194 }
195
196 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds." );
197
198 // File system path of the actual full temp file
199 $this->setTempFile( $tmpPath );
200
201 $ret = $this->verifyUpload();
202 if ( $ret['status'] !== UploadBase::OK ) {
203 wfDebugLog( 'fileconcatenate', "Verification failed for chunked upload" );
204 $status->fatal( $this->getVerificationErrorCode( $ret['status'] ) );
205
206 return $status;
207 }
208
209 // Update the mTempPath and mStashFile
210 // (for FileUpload or normal Stash to take over)
211 $tStart = microtime( true );
212 // This is a re-implementation of UploadBase::tryStashFile(), we can't call it because we
213 // override doStashFile() with completely different functionality in this class...
214 $error = $this->runUploadStashFileHook( $this->user );
215 if ( $error ) {
216 $status->fatal( ...$error );
217 return $status;
218 }
219 try {
220 $this->mStashFile = parent::doStashFile( $this->user );
221 } catch ( UploadStashException $e ) {
222 $status->fatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
223 return $status;
224 }
225
226 $tAmount = microtime( true ) - $tStart;
227 $this->mStashFile->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
228 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds." );
229
230 return $status;
231 }
232
233 /**
234 * Returns the virtual chunk location:
235 * @param int $index
236 * @return string
237 */
238 function getVirtualChunkLocation( $index ) {
239 return $this->repo->getVirtualUrl( 'temp' ) .
240 '/' .
241 $this->repo->getHashPath(
242 $this->getChunkFileKey( $index )
243 ) .
244 $this->getChunkFileKey( $index );
245 }
246
247 /**
248 * Add a chunk to the temporary directory
249 *
250 * @param string $chunkPath Path to temporary chunk file
251 * @param int $chunkSize Size of the current chunk
252 * @param int $offset Offset of current chunk ( mutch match database chunk offset )
253 * @return Status
254 */
255 public function addChunk( $chunkPath, $chunkSize, $offset ) {
256 // Get the offset before we add the chunk to the file system
257 $preAppendOffset = $this->getOffset();
258
259 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize() ) {
260 $status = Status::newFatal( 'file-too-large' );
261 } else {
262 // Make sure the client is uploading the correct chunk with a matching offset.
263 if ( $preAppendOffset == $offset ) {
264 // Update local chunk index for the current chunk
265 $this->mChunkIndex++;
266 try {
267 # For some reason mTempPath is set to first part
268 $oldTemp = $this->mTempPath;
269 $this->mTempPath = $chunkPath;
270 $this->verifyChunk();
271 $this->mTempPath = $oldTemp;
272 } catch ( UploadChunkVerificationException $e ) {
273 return Status::newFatal( $e->msg );
274 }
275 $status = $this->outputChunk( $chunkPath );
276 if ( $status->isGood() ) {
277 // Update local offset:
278 $this->mOffset = $preAppendOffset + $chunkSize;
279 // Update chunk table status db
280 $this->updateChunkStatus();
281 }
282 } else {
283 $status = Status::newFatal( 'invalid-chunk-offset' );
284 }
285 }
286
287 return $status;
288 }
289
290 /**
291 * Update the chunk db table with the current status:
292 */
293 private function updateChunkStatus() {
294 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
295 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
296
297 $dbw = $this->repo->getMasterDB();
298 $dbw->update(
299 'uploadstash',
300 [
301 'us_status' => 'chunks',
302 'us_chunk_inx' => $this->getChunkIndex(),
303 'us_size' => $this->getOffset()
304 ],
305 [ 'us_key' => $this->mFileKey ],
306 __METHOD__
307 );
308 }
309
310 /**
311 * Get the chunk db state and populate update relevant local values
312 */
313 private function getChunkStatus() {
314 // get Master db to avoid race conditions.
315 // Otherwise, if chunk upload time < replag there will be spurious errors
316 $dbw = $this->repo->getMasterDB();
317 $row = $dbw->selectRow(
318 'uploadstash',
319 [
320 'us_chunk_inx',
321 'us_size',
322 'us_path',
323 ],
324 [ 'us_key' => $this->mFileKey ],
325 __METHOD__
326 );
327 // Handle result:
328 if ( $row ) {
329 $this->mChunkIndex = $row->us_chunk_inx;
330 $this->mOffset = $row->us_size;
331 $this->mVirtualTempPath = $row->us_path;
332 }
333 }
334
335 /**
336 * Get the current Chunk index
337 * @return int Index of the current chunk
338 */
339 private function getChunkIndex() {
340 if ( $this->mChunkIndex !== null ) {
341 return $this->mChunkIndex;
342 }
343
344 return 0;
345 }
346
347 /**
348 * Get the offset at which the next uploaded chunk will be appended to
349 * @return int Current byte offset of the chunk file set
350 */
351 public function getOffset() {
352 if ( $this->mOffset !== null ) {
353 return $this->mOffset;
354 }
355
356 return 0;
357 }
358
359 /**
360 * Output the chunk to disk
361 *
362 * @param string $chunkPath
363 * @throws UploadChunkFileException
364 * @return Status
365 */
366 private function outputChunk( $chunkPath ) {
367 // Key is fileKey + chunk index
368 $fileKey = $this->getChunkFileKey();
369
370 // Store the chunk per its indexed fileKey:
371 $hashPath = $this->repo->getHashPath( $fileKey );
372 $storeStatus = $this->repo->quickImport( $chunkPath,
373 $this->repo->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
374
375 // Check for error in stashing the chunk:
376 if ( !$storeStatus->isOK() ) {
377 $error = $storeStatus->getErrorsArray();
378 $error = reset( $error );
379 if ( !count( $error ) ) {
380 $error = $storeStatus->getWarningsArray();
381 $error = reset( $error );
382 if ( !count( $error ) ) {
383 $error = [ 'unknown', 'no error recorded' ];
384 }
385 }
386 throw new UploadChunkFileException( "Error storing file in '$chunkPath': " .
387 implode( '; ', $error ) );
388 }
389
390 return $storeStatus;
391 }
392
393 private function getChunkFileKey( $index = null ) {
394 if ( $index === null ) {
395 $index = $this->getChunkIndex();
396 }
397
398 return $this->mFileKey . '.' . $index;
399 }
400
401 /**
402 * Verify that the chunk isn't really an evil html file
403 *
404 * @throws UploadChunkVerificationException
405 */
406 private function verifyChunk() {
407 // Rest mDesiredDestName here so we verify the name as if it were mFileKey
408 $oldDesiredDestName = $this->mDesiredDestName;
409 $this->mDesiredDestName = $this->mFileKey;
410 $this->mTitle = false;
411 $res = $this->verifyPartialFile();
412 $this->mDesiredDestName = $oldDesiredDestName;
413 $this->mTitle = false;
414 if ( is_array( $res ) ) {
415 throw new UploadChunkVerificationException( $res );
416 }
417 }
418 }