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