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