Merge "Implement static public Parser::getExternalLinkRel"
[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, $mChunkIndex, $mFileKey, $mVirtualTempPath;
32
33 /**
34 * Setup local pointers to stash, repo and user ( similar to UploadFromStash )
35 *
36 * @param $user User
37 * @param $stash UploadStash
38 * @param $repo FileRepo
39 */
40 public function __construct( $user = false, $stash = false, $repo = false ) {
41 // user object. sometimes this won't exist, as when running from cron.
42 $this->user = $user;
43
44 if( $repo ) {
45 $this->repo = $repo;
46 } else {
47 $this->repo = RepoGroup::singleton()->getLocalRepo();
48 }
49
50 if( $stash ) {
51 $this->stash = $stash;
52 } else {
53 if( $user ) {
54 wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
55 } else {
56 wfDebug( __METHOD__ . " creating new UploadFromChunks instance with no user\n" );
57 }
58 $this->stash = new UploadStash( $this->repo, $this->user );
59 }
60
61 return true;
62 }
63 /**
64 * Calls the parent stashFile and updates the uploadsession table to handle "chunks"
65 *
66 * @return UploadStashFile stashed file
67 */
68 public function stashFile() {
69 // Stash file is the called on creating a new chunk session:
70 $this->mChunkIndex = 0;
71 $this->mOffset = 0;
72 // Create a local stash target
73 $this->mLocalFile = parent::stashFile();
74 // Update the initial file offset ( based on file size )
75 $this->mOffset = $this->mLocalFile->getSize();
76 $this->mFileKey = $this->mLocalFile->getFileKey();
77
78 // Output a copy of this first to chunk 0 location:
79 $this->outputChunk( $this->mLocalFile->getPath() );
80
81 // Update db table to reflect initial "chunk" state
82 $this->updateChunkStatus();
83 return $this->mLocalFile;
84 }
85
86 /**
87 * Continue chunk uploading
88 */
89 public function continueChunks( $name, $key, $webRequestUpload ) {
90 $this->mFileKey = $key;
91 $this->mUpload = $webRequestUpload;
92 // Get the chunk status form the db:
93 $this->getChunkStatus();
94
95 $metadata = $this->stash->getMetadata( $key );
96 $this->initializePathInfo( $name,
97 $this->getRealPath( $metadata['us_path'] ),
98 $metadata['us_size'],
99 false
100 );
101 }
102
103 /**
104 * Append the final chunk and ready file for parent::performUpload()
105 * @return FileRepoStatus
106 */
107 public function concatenateChunks() {
108 wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
109 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
110
111 // Concatenate all the chunks to mVirtualTempPath
112 $fileList = Array();
113 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
114 for( $i = 0; $i <= $this->getChunkIndex(); $i++ ){
115 $fileList[] = $this->getVirtualChunkLocation( $i );
116 }
117
118 // Get the file extension from the last chunk
119 $ext = FileBackend::extensionFromPath( $this->mVirtualTempPath );
120 // Get a 0-byte temp file to perform the concatenation at
121 $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext );
122 $tmpPath = $tmpFile
123 ? $tmpFile->bind( $this )->getPath() // keep alive with $this
124 : false; // fail in concatenate()
125 // Concatenate the chunks at the temp file
126 $tStart = microtime( true );
127 $status = $this->repo->concatenate( $fileList, $tmpPath, FileRepo::DELETE_SOURCE );
128 $tAmount = microtime( true ) - $tStart;
129 if( !$status->isOk() ){
130 return $status;
131 }
132 wfDebugLog( 'fileconcatenate', "Combined $i chunks in $tAmount seconds.\n" );
133 // Update the mTempPath and mLocalFile
134 // ( for FileUpload or normal Stash to take over )
135 $this->mTempPath = $tmpPath; // file system path
136 $tStart = microtime( true );
137 $this->mLocalFile = parent::stashFile();
138 $tAmount = microtime( true ) - $tStart;
139 $this->mLocalFile->setLocalReference( $tmpFile ); // reuse (e.g. for getImageInfo())
140 wfDebugLog( 'fileconcatenate', "Stashed combined file ($i chunks) in $tAmount seconds.\n" );
141
142 return $status;
143 }
144
145 /**
146 * Perform the upload, then remove the temp copy afterward
147 * @param $comment string
148 * @param $pageText string
149 * @param $watch bool
150 * @param $user User
151 * @return Status
152 */
153 public function performUpload( $comment, $pageText, $watch, $user ) {
154 $rv = parent::performUpload( $comment, $pageText, $watch, $user );
155 return $rv;
156 }
157
158 /**
159 * Returns the virtual chunk location:
160 * @param $index
161 * @return string
162 */
163 function getVirtualChunkLocation( $index ){
164 return $this->repo->getVirtualUrl( 'temp' ) .
165 '/' .
166 $this->repo->getHashPath(
167 $this->getChunkFileKey( $index )
168 ) .
169 $this->getChunkFileKey( $index );
170 }
171
172 /**
173 * Add a chunk to the temporary directory
174 *
175 * @param $chunkPath string path to temporary chunk file
176 * @param $chunkSize int size of the current chunk
177 * @param $offset int offset of current chunk ( mutch match database chunk offset )
178 * @return Status
179 */
180 public function addChunk( $chunkPath, $chunkSize, $offset ) {
181 // Get the offset before we add the chunk to the file system
182 $preAppendOffset = $this->getOffset();
183
184 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize()) {
185 $status = Status::newFatal( 'file-too-large' );
186 } else {
187 // Make sure the client is uploading the correct chunk with a matching offset.
188 if ( $preAppendOffset == $offset ) {
189 // Update local chunk index for the current chunk
190 $this->mChunkIndex++;
191 $status = $this->outputChunk( $chunkPath );
192 if( $status->isGood() ){
193 // Update local offset:
194 $this->mOffset = $preAppendOffset + $chunkSize;
195 // Update chunk table status db
196 $this->updateChunkStatus();
197 }
198 } else {
199 $status = Status::newFatal( 'invalid-chunk-offset' );
200 }
201 }
202 return $status;
203 }
204
205 /**
206 * Update the chunk db table with the current status:
207 */
208 private function updateChunkStatus(){
209 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
210 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
211
212 $dbw = $this->repo->getMasterDb();
213 // Use a quick transaction since we will upload the full temp file into shared
214 // storage, which takes time for large files. We don't want to hold locks then.
215 $dbw->begin();
216 $dbw->update(
217 'uploadstash',
218 array(
219 'us_status' => 'chunks',
220 'us_chunk_inx' => $this->getChunkIndex(),
221 'us_size' => $this->getOffset()
222 ),
223 array( 'us_key' => $this->mFileKey ),
224 __METHOD__
225 );
226 $dbw->commit();
227 }
228
229 /**
230 * Get the chunk db state and populate update relevant local values
231 */
232 private function getChunkStatus(){
233 // get Master db to avoid race conditions.
234 // Otherwise, if chunk upload time < replag there will be spurious errors
235 $dbw = $this->repo->getMasterDb();
236 $row = $dbw->selectRow(
237 'uploadstash',
238 array(
239 'us_chunk_inx',
240 'us_size',
241 'us_path',
242 ),
243 array( 'us_key' => $this->mFileKey ),
244 __METHOD__
245 );
246 // Handle result:
247 if ( $row ) {
248 $this->mChunkIndex = $row->us_chunk_inx;
249 $this->mOffset = $row->us_size;
250 $this->mVirtualTempPath = $row->us_path;
251 }
252 }
253
254 /**
255 * Get the current Chunk index
256 * @return Integer index of the current chunk
257 */
258 private function getChunkIndex(){
259 if( $this->mChunkIndex !== null ){
260 return $this->mChunkIndex;
261 }
262 return 0;
263 }
264
265 /**
266 * Gets the current offset in fromt the stashedupload table
267 * @return Integer current byte offset of the chunk file set
268 */
269 private function getOffset(){
270 if ( $this->mOffset !== null ){
271 return $this->mOffset;
272 }
273 return 0;
274 }
275
276 /**
277 * Output the chunk to disk
278 *
279 * @param $chunkPath string
280 * @throws UploadChunkFileException
281 * @return FileRepoStatus
282 */
283 private function outputChunk( $chunkPath ){
284 // Key is fileKey + chunk index
285 $fileKey = $this->getChunkFileKey();
286
287 // Store the chunk per its indexed fileKey:
288 $hashPath = $this->repo->getHashPath( $fileKey );
289 $storeStatus = $this->repo->quickImport( $chunkPath,
290 $this->repo->getZonePath( 'temp' ) . "/{$hashPath}{$fileKey}" );
291
292 // Check for error in stashing the chunk:
293 if ( ! $storeStatus->isOK() ) {
294 $error = $storeStatus->getErrorsArray();
295 $error = reset( $error );
296 if ( ! count( $error ) ) {
297 $error = $storeStatus->getWarningsArray();
298 $error = reset( $error );
299 if ( ! count( $error ) ) {
300 $error = array( 'unknown', 'no error recorded' );
301 }
302 }
303 throw new UploadChunkFileException( "error storing file in '$chunkPath': " . implode( '; ', $error ) );
304 }
305 return $storeStatus;
306 }
307
308 private function getChunkFileKey( $index = null ){
309 if( $index === null ){
310 $index = $this->getChunkIndex();
311 }
312 return $this->mFileKey . '.' . $index ;
313 }
314 }
315
316 class UploadChunkZeroLengthFileException extends MWException {};
317 class UploadChunkFileException extends MWException {};