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