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