- add comment to document us_chunk_inx in sql file
[lhc/web/wiklou.git] / includes / upload / UploadFromChunks.php
1 <?php
2 /**
3 * Implements uploading from chunks
4 *
5 * @file
6 * @ingroup upload
7 * @author Michael Dale
8 */
9
10 class UploadFromChunks extends UploadFromFile {
11 protected $mOffset, $mChunkIndex, $mFileKey, $mVirtualTempPath;
12
13 /**
14 * Setup local pointers to stash, repo and user ( similar to UploadFromStash )
15 *
16 * @param $user User
17 * @param $stash UploadStash
18 * @param $repo FileRepo
19 */
20 public function __construct( $user = false, $stash = false, $repo = false ) {
21 // user object. sometimes this won't exist, as when running from cron.
22 $this->user = $user;
23
24 if( $repo ) {
25 $this->repo = $repo;
26 } else {
27 $this->repo = RepoGroup::singleton()->getLocalRepo();
28 }
29
30 if( $stash ) {
31 $this->stash = $stash;
32 } else {
33 if( $user ) {
34 wfDebug( __METHOD__ . " creating new UploadFromChunks instance for " . $user->getId() . "\n" );
35 } else {
36 wfDebug( __METHOD__ . " creating new UploadFromChunks instance with no user\n" );
37 }
38 $this->stash = new UploadStash( $this->repo, $this->user );
39 }
40
41 return true;
42 }
43 /**
44 * Calls the parent stashFile and updates the uploadsession table to handle "chunks"
45 *
46 * @return UploadStashFile stashed file
47 */
48 public function stashFile() {
49 // Stash file is the called on creating a new chunk session:
50 $this->mChunkIndex = 0;
51 $this->mOffset = 0;
52 // Create a local stash target
53 $this->mLocalFile = parent::stashFile();
54 // Update the initial file offset ( based on file size )
55 $this->mOffset = $this->mLocalFile->getSize();
56 $this->mFileKey = $this->mLocalFile->getFileKey();
57
58 // Output a copy of this first to chunk 0 location:
59 $status = $this->outputChunk( $this->mLocalFile->getLocalRefPath() );
60
61 // Update db table to reflect initial "chunk" state
62 $this->updateChunkStatus();
63 return $this->mLocalFile;
64 }
65
66 /**
67 * Continue chunk uploading
68 */
69 public function continueChunks( $name, $key, $webRequestUpload ) {
70 $this->mFileKey = $key;
71 $this->mUpload = $webRequestUpload;
72 // Get the chunk status form the db:
73 $this->getChunkStatus();
74
75 $metadata = $this->stash->getMetadata( $key );
76 $this->initializePathInfo( $name,
77 $this->getRealPath ( $metadata['us_path'] ),
78 $metadata['us_size'],
79 false
80 );
81 }
82
83 /**
84 * Append the final chunk and ready file for parent::performUpload()
85 * @return void
86 */
87 public function concatenateChunks() {
88 wfDebug( __METHOD__ . " concatenate {$this->mChunkIndex} chunks:" .
89 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
90
91 // Concatenate all the chunks to mVirtualTempPath
92 $fileList = Array();
93 // The first chunk is stored at the mVirtualTempPath path so we start on "chunk 1"
94 for( $i = 0; $i <= $this->getChunkIndex(); $i++ ){
95 $fileList[] = $this->getVirtualChunkLocation( $i );
96 }
97
98 // Concatenate into the mVirtualTempPath location;
99 $status = $this->repo->concatenate( $fileList, $this->mVirtualTempPath, FileRepo::DELETE_SOURCE );
100 if( !$status->isOk() ){
101 return $status;
102 }
103 // Update the mTempPath variable ( for FileUpload or normal Stash to take over )
104 $this->mTempPath = $this->getRealPath( $this->mVirtualTempPath );
105 return $status;
106 }
107
108 /**
109 * Perform the upload, then remove the temp copy afterward
110 * @param $comment string
111 * @param $pageText string
112 * @param $watch bool
113 * @param $user User
114 * @return Status
115 */
116 public function performUpload( $comment, $pageText, $watch, $user ) {
117 $rv = parent::performUpload( $comment, $pageText, $watch, $user );
118 $this->repo->freeTemp( $this->mVirtualTempPath );
119 return $rv;
120 }
121
122 /**
123 * Returns the virtual chunk location:
124 * @param unknown_type $index
125 */
126 function getVirtualChunkLocation( $index ){
127 return $this->repo->getVirtualUrl( 'temp' ) .
128 '/' .
129 $this->repo->getHashPath(
130 $this->getChunkFileKey( $index )
131 ) .
132 $this->getChunkFileKey( $index );
133 }
134 /**
135 * Add a chunk to the temporary directory
136 *
137 * @param $chunkPath path to temporary chunk file
138 * @param $chunkSize size of the current chunk
139 * @param $offset offset of current chunk ( mutch match database chunk offset )
140 * @return Status
141 */
142 public function addChunk( $chunkPath, $chunkSize, $offset ) {
143 // Get the offset before we add the chunk to the file system
144 $preAppendOffset = $this->getOffset();
145
146 if ( $preAppendOffset + $chunkSize > $this->getMaxUploadSize()) {
147 $status = Status::newFatal( 'file-too-large' );
148 } else {
149 // Make sure the client is uploading the correct chunk with a matching offset.
150 if ( $preAppendOffset == $offset ) {
151 // Update local chunk index for the current chunk
152 $this->mChunkIndex++;
153 $status = $this->outputChunk( $chunkPath );
154 if( $status->isGood() ){
155 // Update local offset:
156 $this->mOffset = $preAppendOffset + $chunkSize;
157 // Update chunk table status db
158 $this->updateChunkStatus();
159 }
160 } else {
161 $status = Status::newFatal( 'invalid-chunk-offset' );
162 }
163 }
164 return $status;
165 }
166
167 /**
168 * Update the chunk db table with the current status:
169 */
170 private function updateChunkStatus(){
171 wfDebug( __METHOD__ . " update chunk status for {$this->mFileKey} offset:" .
172 $this->getOffset() . ' inx:' . $this->getChunkIndex() . "\n" );
173
174 $dbw = $this->repo->getMasterDb();
175 $dbw->update(
176 'uploadstash',
177 array(
178 'us_status' => 'chunks',
179 'us_chunk_inx' => $this->getChunkIndex(),
180 'us_size' => $this->getOffset()
181 ),
182 array( 'us_key' => $this->mFileKey ),
183 __METHOD__
184 );
185 }
186 /**
187 * Get the chunk db state and populate update relevant local values
188 */
189 private function getChunkStatus(){
190 // get Master db to avoid race conditions.
191 // Otherwise, if chunk upload time < replag there will be spurious errors
192 $dbw = $this->repo->getMasterDb();
193 $row = $dbw->selectRow(
194 'uploadstash',
195 array(
196 'us_chunk_inx',
197 'us_size',
198 'us_path',
199 ),
200 array( 'us_key' => $this->mFileKey ),
201 __METHOD__
202 );
203 // Handle result:
204 if ( $row ) {
205 $this->mChunkIndex = $row->us_chunk_inx;
206 $this->mOffset = $row->us_size;
207 $this->mVirtualTempPath = $row->us_path;
208 }
209 }
210 /**
211 * Get the current Chunk index
212 * @return Integer index of the current chunk
213 */
214 private function getChunkIndex(){
215 if( $this->mChunkIndex !== null ){
216 return $this->mChunkIndex;
217 }
218 return 0;
219 }
220
221 /**
222 * Gets the current offset in fromt the stashedupload table
223 * @return Integer current byte offset of the chunk file set
224 */
225 private function getOffset(){
226 if ( $this->mOffset !== null ){
227 return $this->mOffset;
228 }
229 return 0;
230 }
231
232 /**
233 * Output the chunk to disk
234 *
235 * @param $chunk
236 * @param unknown_type $path
237 */
238 private function outputChunk( $chunkPath ){
239 // Key is fileKey + chunk index
240 $fileKey = $this->getChunkFileKey();
241
242 // Store the chunk per its indexed fileKey:
243 $hashPath = $this->repo->getHashPath( $fileKey );
244 $storeStatus = $this->repo->store( $chunkPath, 'temp', "$hashPath$fileKey" );
245
246 // Check for error in stashing the chunk:
247 if ( ! $storeStatus->isOK() ) {
248 $error = $storeStatus->getErrorsArray();
249 $error = reset( $error );
250 if ( ! count( $error ) ) {
251 $error = $storeStatus->getWarningsArray();
252 $error = reset( $error );
253 if ( ! count( $error ) ) {
254 $error = array( 'unknown', 'no error recorded' );
255 }
256 }
257 throw new UploadChunkFileException( "error storing file in '$path': " . implode( '; ', $error ) );
258 }
259 return $storeStatus;
260 }
261 private function getChunkFileKey( $index = null ){
262 if( $index === null ){
263 $index = $this->getChunkIndex();
264 }
265 return $this->mFileKey . '.' . $index ;
266 }
267 }
268
269 class UploadChunkZeroLengthFileException extends MWException {};
270 class UploadChunkFileException extends MWException {};