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