merged master
[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 $status = $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->getPath()
124 : false; // fail in concatenate()
125 // Concatenate the chunks at the temp file
126 $status = $this->repo->concatenate( $fileList, $tmpPath, FileRepo::DELETE_SOURCE );
127 if( !$status->isOk() ){
128 return $status;
129 }
130 // Update the mTempPath and mLocalFile
131 // ( for FileUpload or normal Stash to take over )
132 $this->mTempPath = $tmpPath; // file system path
133 $this->mLocalFile = parent::stashFile();
134
135 return $status;
136 }
137
138 /**
139 * Perform the upload, then remove the temp copy afterward
140 * @param $comment string
141 * @param $pageText string
142 * @param $watch bool
143 * @param $user User
144 * @return Status
145 */
146 public function performUpload( $comment, $pageText, $watch, $user ) {
147 $rv = parent::performUpload( $comment, $pageText, $watch, $user );
148 return $rv;
149 }
150
151 /**
152 * Returns the virtual chunk location:
153 * @param $index
154 * @return string
155 */
156 function getVirtualChunkLocation( $index ){
157 return $this->repo->getVirtualUrl( 'temp' ) .
158 '/' .
159 $this->repo->getHashPath(
160 $this->getChunkFileKey( $index )
161 ) .
162 $this->getChunkFileKey( $index );
163 }
164
165 /**
166 * Add a chunk to the temporary directory
167 *
168 * @param $chunkPath string path to temporary chunk file
169 * @param $chunkSize int size of the current chunk
170 * @param $offset int offset of current chunk ( mutch match database chunk offset )
171 * @return Status
172 */
173 public function addChunk( $chunkPath, $chunkSize, $offset ) {
174 // Get the offset before we add the chunk to the file system
175 $preAppendOffset = $this->getOffset();
176
177 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize()) {
178 $status = Status::newFatal( 'file-too-large' );
179 } else {
180 // Make sure the client is uploading the correct chunk with a matching offset.
181 if ( $preAppendOffset == $offset ) {
182 // Update local chunk index for the current chunk
183 $this->mChunkIndex++;
184 $status = $this->outputChunk( $chunkPath );
185 if( $status->isGood() ){
186 // Update local offset:
187 $this->mOffset = $preAppendOffset + $chunkSize;
188 // Update chunk table status db
189 $this->updateChunkStatus();
190 }
191 } else {
192 $status = Status::newFatal( 'invalid-chunk-offset' );
193 }
194 }
195 return $status;
196 }
197
198 /**
199 * Update the chunk db table with the current status:
200 */
201 private function updateChunkStatus(){
202 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
203 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
204
205 $dbw = $this->repo->getMasterDb();
206 $dbw->update(
207 'uploadstash',
208 array(
209 'us_status' => 'chunks',
210 'us_chunk_inx' => $this->getChunkIndex(),
211 'us_size' => $this->getOffset()
212 ),
213 array( 'us_key' => $this->mFileKey ),
214 __METHOD__
215 );
216 }
217 /**
218 * Get the chunk db state and populate update relevant local values
219 */
220 private function getChunkStatus(){
221 // get Master db to avoid race conditions.
222 // Otherwise, if chunk upload time < replag there will be spurious errors
223 $dbw = $this->repo->getMasterDb();
224 $row = $dbw->selectRow(
225 'uploadstash',
226 array(
227 'us_chunk_inx',
228 'us_size',
229 'us_path',
230 ),
231 array( 'us_key' => $this->mFileKey ),
232 __METHOD__
233 );
234 // Handle result:
235 if ( $row ) {
236 $this->mChunkIndex = $row->us_chunk_inx;
237 $this->mOffset = $row->us_size;
238 $this->mVirtualTempPath = $row->us_path;
239 }
240 }
241 /**
242 * Get the current Chunk index
243 * @return Integer index of the current chunk
244 */
245 private function getChunkIndex(){
246 if( $this->mChunkIndex !== null ){
247 return $this->mChunkIndex;
248 }
249 return 0;
250 }
251
252 /**
253 * Gets the current offset in fromt the stashedupload table
254 * @return Integer current byte offset of the chunk file set
255 */
256 private function getOffset(){
257 if ( $this->mOffset !== null ){
258 return $this->mOffset;
259 }
260 return 0;
261 }
262
263 /**
264 * Output the chunk to disk
265 *
266 * @param $chunkPath string
267 * @return FileRepoStatus
268 */
269 private function outputChunk( $chunkPath ){
270 // Key is fileKey + chunk index
271 $fileKey = $this->getChunkFileKey();
272
273 // Store the chunk per its indexed fileKey:
274 $hashPath = $this->repo->getHashPath( $fileKey );
275 $storeStatus = $this->repo->store( $chunkPath, 'temp', "$hashPath$fileKey" );
276
277 // Check for error in stashing the chunk:
278 if ( ! $storeStatus->isOK() ) {
279 $error = $storeStatus->getErrorsArray();
280 $error = reset( $error );
281 if ( ! count( $error ) ) {
282 $error = $storeStatus->getWarningsArray();
283 $error = reset( $error );
284 if ( ! count( $error ) ) {
285 $error = array( 'unknown', 'no error recorded' );
286 }
287 }
288 throw new UploadChunkFileException( "error storing file in '$chunkPath': " . implode( '; ', $error ) );
289 }
290 return $storeStatus;
291 }
292 private function getChunkFileKey( $index = null ){
293 if( $index === null ){
294 $index = $this->getChunkIndex();
295 }
296 return $this->mFileKey . '.' . $index ;
297 }
298 }
299
300 class UploadChunkZeroLengthFileException extends MWException {};
301 class UploadChunkFileException extends MWException {};