* Introduced FileRepoStatus -- result class for file repo operations.
[lhc/web/wiklou.git] / includes / filerepo / FSRepo.php
1 <?php
2
3 /**
4 * A repository for files accessible via the local filesystem. Does not support
5 * database access or registration.
6 */
7
8 class FSRepo extends FileRepo {
9 var $directory, $deletedDir, $url, $hashLevels, $deletedHashLevels;
10 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
11 var $oldFileFactory = false;
12 var $pathDisclosureProtection = 'simple';
13
14 function __construct( $info ) {
15 parent::__construct( $info );
16
17 // Required settings
18 $this->directory = $info['directory'];
19 $this->url = $info['url'];
20
21 // Optional settings
22 $this->hashLevels = isset( $info['hashLevels'] ) ? $info['hashLevels'] : 2;
23 $this->deletedHashLevels = isset( $info['deletedHashLevels'] ) ?
24 $info['deletedHashLevels'] : $this->hashLevels;
25 $this->deletedDir = isset( $info['deletedDir'] ) ? $info['deletedDir'] : false;
26 }
27
28 /**
29 * Get the public root directory of the repository.
30 */
31 function getRootDirectory() {
32 return $this->directory;
33 }
34
35 /**
36 * Get the public root URL of the repository
37 */
38 function getRootUrl() {
39 return $this->url;
40 }
41
42 /**
43 * Returns true if the repository uses a multi-level directory structure
44 */
45 function isHashed() {
46 return (bool)$this->hashLevels;
47 }
48
49 /**
50 * Get the local directory corresponding to one of the three basic zones
51 */
52 function getZonePath( $zone ) {
53 switch ( $zone ) {
54 case 'public':
55 return $this->directory;
56 case 'temp':
57 return "{$this->directory}/temp";
58 case 'deleted':
59 return $this->deletedDir;
60 default:
61 return false;
62 }
63 }
64
65 /**
66 * Get the URL corresponding to one of the three basic zones
67 */
68 function getZoneUrl( $zone ) {
69 switch ( $zone ) {
70 case 'public':
71 return $this->url;
72 case 'temp':
73 return "{$this->url}/temp";
74 case 'deleted':
75 return false; // no public URL
76 default:
77 return false;
78 }
79 }
80
81 /**
82 * Get a URL referring to this repository, with the private mwrepo protocol.
83 * The suffix, if supplied, is considered to be unencoded, and will be
84 * URL-encoded before being returned.
85 */
86 function getVirtualUrl( $suffix = false ) {
87 $path = 'mwrepo://' . $this->name;
88 if ( $suffix !== false ) {
89 $path .= '/' . rawurlencode( $suffix );
90 }
91 return $path;
92 }
93
94 /**
95 * Get the local path corresponding to a virtual URL
96 */
97 function resolveVirtualUrl( $url ) {
98 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
99 throw new MWException( __METHOD__.': unknown protoocl' );
100 }
101
102 $bits = explode( '/', substr( $url, 9 ), 3 );
103 if ( count( $bits ) != 3 ) {
104 throw new MWException( __METHOD__.": invalid mwrepo URL: $url" );
105 }
106 list( $repo, $zone, $rel ) = $bits;
107 if ( $repo !== $this->name ) {
108 throw new MWException( __METHOD__.": fetching from a foreign repo is not supported" );
109 }
110 $base = $this->getZonePath( $zone );
111 if ( !$base ) {
112 throw new MWException( __METHOD__.": invalid zone: $zone" );
113 }
114 return $base . '/' . rawurldecode( $rel );
115 }
116
117 /**
118 * Store a batch of files
119 *
120 * @param array $triplets (src,zone,dest) triplets as per store()
121 * @param integer $flags Bitwise combination of the following flags:
122 * self::DELETE_SOURCE Delete the source file after upload
123 * self::OVERWRITE Overwrite an existing destination file instead of failing
124 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
125 * same contents as the source
126 */
127 function storeBatch( $triplets, $flags = 0 ) {
128 if ( !is_writable( $this->directory ) ) {
129 return $this->newFatal( 'upload_directory_read_only', $this->directory );
130 }
131 $status = $this->newGood();
132 foreach ( $triplets as $i => $triplet ) {
133 list( $srcPath, $dstZone, $dstRel ) = $triplet;
134
135 $root = $this->getZonePath( $dstZone );
136 if ( !$root ) {
137 throw new MWException( "Invalid zone: $dstZone" );
138 }
139 if ( !$this->validateFilename( $dstRel ) ) {
140 throw new MWException( 'Validation error in $dstRel' );
141 }
142 $dstPath = "$root/$dstRel";
143 $dstDir = dirname( $dstPath );
144
145 if ( !is_dir( $dstDir ) && !wfMkdirParents( $dstDir ) ) {
146 return $this->newFatal( 'directorycreateerror', $dstDir );
147 }
148
149 if ( self::isVirtualUrl( $srcPath ) ) {
150 $srcPath = $triplets[$i][0] = $this->resolveVirtualUrl( $srcPath );
151 }
152 if ( !is_file( $srcPath ) ) {
153 // Make a list of files that don't exist for return to the caller
154 $status->fatal( 'filenotfound', $srcPath );
155 continue;
156 }
157 if ( !( $flags & self::OVERWRITE ) && file_exists( $dstPath ) ) {
158 if ( $flags & self::OVERWRITE_SAME ) {
159 $hashSource = sha1_file( $srcPath );
160 $hashDest = sha1_file( $dstPath );
161 if ( $hashSource != $hashDest ) {
162 $status->fatal( 'fileexists', $dstPath );
163 }
164 } else {
165 $status->fatal( 'fileexists', $dstPath );
166 }
167 }
168 }
169
170 $deleteDest = wfIsWindows() && ( $flags & self::OVERWRITE );
171
172 // Abort now on failure
173 if ( !$status->ok ) {
174 return $status;
175 }
176
177 foreach ( $triplets as $triplet ) {
178 list( $srcPath, $dstZone, $dstRel ) = $triplet;
179 $root = $this->getZonePath( $dstZone );
180 $dstPath = "$root/$dstRel";
181 $good = true;
182
183 if ( $flags & self::DELETE_SOURCE ) {
184 if ( $deleteDest ) {
185 unlink( $dstPath );
186 }
187 if ( !rename( $srcPath, $dstPath ) ) {
188 $status->error( 'filerenameerror', $srcPath, $dstPath );
189 $good = false;
190 }
191 } else {
192 if ( !copy( $srcPath, $dstPath ) ) {
193 $status->error( 'filecopyerror', $srcPath, $dstPath );
194 $good = false;
195 }
196 }
197 if ( $good ) {
198 chmod( $dstPath, 0644 );
199 $status->successCount++;
200 } else {
201 $status->failCount++;
202 }
203 }
204 return $status;
205 }
206
207 /**
208 * Pick a random name in the temp zone and store a file to it.
209 * @param string $originalName The base name of the file as specified
210 * by the user. The file extension will be maintained.
211 * @param string $srcPath The current location of the file.
212 * @return FileRepoStatus object with the URL in the value.
213 */
214 function storeTemp( $originalName, $srcPath ) {
215 $date = gmdate( "YmdHis" );
216 $hashPath = $this->getHashPath( $originalName );
217 $dstRel = "$hashPath$date!$originalName";
218 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
219
220 $result = $this->store( $srcPath, 'temp', $dstRel );
221 $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
222 return $result;
223 }
224
225 /**
226 * Remove a temporary file or mark it for garbage collection
227 * @param string $virtualUrl The virtual URL returned by storeTemp
228 * @return boolean True on success, false on failure
229 */
230 function freeTemp( $virtualUrl ) {
231 $temp = "mwrepo://{$this->name}/temp";
232 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
233 wfDebug( __METHOD__.": Invalid virtual URL\n" );
234 return false;
235 }
236 $path = $this->resolveVirtualUrl( $virtualUrl );
237 wfSuppressWarnings();
238 $success = unlink( $path );
239 wfRestoreWarnings();
240 return $success;
241 }
242
243 /**
244 * Publish a batch of files
245 * @param array $triplets (source,dest,archive) triplets as per publish()
246 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
247 * that the source files should be deleted if possible
248 */
249 function publishBatch( $triplets, $flags = 0 ) {
250 // Perform initial checks
251 if ( !is_writable( $this->directory ) ) {
252 return $this->newFatal( 'upload_directory_read_only', $this->directory );
253 }
254 $status = $this->newGood( array() );
255 foreach ( $triplets as $i => $triplet ) {
256 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
257
258 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
259 $triplets[$i][0] = $srcPath = $this->resolveVirtualUrl( $srcPath );
260 }
261 if ( !$this->validateFilename( $dstRel ) ) {
262 throw new MWException( 'Validation error in $dstRel' );
263 }
264 if ( !$this->validateFilename( $archiveRel ) ) {
265 throw new MWException( 'Validation error in $archiveRel' );
266 }
267 $dstPath = "{$this->directory}/$dstRel";
268 $archivePath = "{$this->directory}/$archiveRel";
269
270 $dstDir = dirname( $dstPath );
271 $archiveDir = dirname( $archivePath );
272 // Abort immediately on directory creation errors since they're likely to be repetitive
273 if ( !is_dir( $dstDir ) && !wfMkdirParents( $dstDir ) ) {
274 return $this->newFatal( 'directorycreateerror', $dstDir );
275 }
276 if ( !is_dir( $archiveDir ) && !wfMkdirParents( $archiveDir ) ) {
277 return $this->newFatal( 'directorycreateerror', $archiveDir );
278 }
279 if ( !is_file( $srcPath ) ) {
280 // Make a list of files that don't exist for return to the caller
281 $status->fatal( 'filenotfound', $srcPath );
282 }
283 }
284
285 if ( !$status->ok ) {
286 return $status;
287 }
288
289 foreach ( $triplets as $i => $triplet ) {
290 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
291 $dstPath = "{$this->directory}/$dstRel";
292 $archivePath = "{$this->directory}/$archiveRel";
293
294 // Archive destination file if it exists
295 if( is_file( $dstPath ) ) {
296 // Check if the archive file exists
297 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
298 // unlinks the destination file if it exists. DB-based synchronisation in
299 // publishBatch's caller should prevent races. In Windows there's no
300 // problem because the rename primitive fails if the destination exists.
301 if ( is_file( $archivePath ) ) {
302 $success = false;
303 } else {
304 wfSuppressWarnings();
305 $success = rename( $dstPath, $archivePath );
306 wfRestoreWarnings();
307 }
308
309 if( !$success ) {
310 $status->error( 'filerenameerror',$dstPath, $archivePath );
311 $status->failCount++;
312 continue;
313 } else {
314 wfDebug(__METHOD__.": moved file $dstPath to $archivePath\n");
315 }
316 $status->value[$i] = 'archived';
317 } else {
318 $status->value[$i] = 'new';
319 }
320
321 $good = true;
322 wfSuppressWarnings();
323 if ( $flags & self::DELETE_SOURCE ) {
324 if ( !rename( $srcPath, $dstPath ) ) {
325 $status->error( 'filerenameerror', $srcPath, $dstPath );
326 $good = false;
327 }
328 } else {
329 if ( !copy( $srcPath, $dstPath ) ) {
330 $status->error( 'filecopyerror', $srcPath, $dstPath );
331 $good = false;
332 }
333 }
334 wfRestoreWarnings();
335
336 if ( $good ) {
337 $status->successCount++;
338 wfDebug(__METHOD__.": wrote tempfile $srcPath to $dstPath\n");
339 // Thread-safe override for umask
340 chmod( $dstPath, 0644 );
341 } else {
342 $status->failCount++;
343 }
344 }
345 return $status;
346 }
347
348 /**
349 * Move a group of files to the deletion archive.
350 * If no valid deletion archive is configured, this may either delete the
351 * file or throw an exception, depending on the preference of the repository.
352 *
353 * @param array $sourceDestPairs Array of source/destination pairs. Each element
354 * is a two-element array containing the source file path relative to the
355 * public root in the first element, and the archive file path relative
356 * to the deleted zone root in the second element.
357 * @return FileRepoStatus
358 */
359 function deleteBatch( $sourceDestPairs ) {
360 $status = $this->newGood();
361 if ( !$this->deletedDir ) {
362 throw new MWException( __METHOD__.': no valid deletion archive directory' );
363 }
364
365 /**
366 * Validate filenames and create archive directories
367 */
368 foreach ( $sourceDestPairs as $pair ) {
369 list( $srcRel, $archiveRel ) = $pair;
370 if ( !$this->validateFilename( $srcRel ) ) {
371 throw new MWException( __METHOD__.':Validation error in $srcRel' );
372 }
373 if ( !$this->validateFilename( $archiveRel ) ) {
374 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
375 }
376 $archivePath = "{$this->deletedDir}/$archiveRel";
377 $archiveDir = dirname( $archivePath );
378 if ( !wfMkdirParents( $archiveDir ) ) {
379 $status->fatal( 'directorycreateerror', $archiveDir );
380 continue;
381 }
382 // Check if the archive directory is writable
383 // This doesn't appear to work on NTFS
384 if ( !is_writable( $archiveDir ) ) {
385 $status->fatal( 'filedelete-archive-read-only', $archiveDir );
386 }
387 }
388 if ( !$status->ok ) {
389 // Abort early
390 return $status;
391 }
392
393 /**
394 * Move the files
395 * We're now committed to returning an OK result, which will lead to
396 * the files being moved in the DB also.
397 */
398 foreach ( $sourceDestPairs as $pair ) {
399 list( $srcRel, $archiveRel ) = $pair;
400 $srcPath = "{$this->directory}/$srcRel";
401 $archivePath = "{$this->deletedDir}/$archiveRel";
402 $good = true;
403 if ( file_exists( $archivePath ) ) {
404 # A file with this content hash is already archived
405 if ( !@unlink( $srcPath ) ) {
406 $status->error( 'filedeleteerror', $srcPath );
407 $good = false;
408 }
409 } else{
410 if ( !@rename( $srcPath, $archivePath ) ) {
411 $status->error( 'filerenameerror', $srcPath, $archivePath );
412 $good = false;
413 } else {
414 chmod( $archivePath, 0644 );
415 }
416 }
417 if ( $good ) {
418 $status->successCount++;
419 } else {
420 $status->failCount++;
421 }
422 }
423 return $status;
424 }
425
426 /**
427 * Get a relative path including trailing slash, e.g. f/fa/
428 * If the repo is not hashed, returns an empty string
429 */
430 function getHashPath( $name ) {
431 return FileRepo::getHashPathForLevel( $name, $this->hashLevels );
432 }
433
434 /**
435 * Get a relative path for a deletion archive key,
436 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
437 */
438 function getDeletedHashPath( $key ) {
439 $path = '';
440 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
441 $path .= $key[$i] . '/';
442 }
443 return $path;
444 }
445
446 /**
447 * Call a callback function for every file in the repository.
448 * Uses the filesystem even in child classes.
449 */
450 function enumFilesInFS( $callback ) {
451 $numDirs = 1 << ( $this->hashLevels * 4 );
452 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
453 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
454 $path = $this->directory;
455 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
456 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
457 }
458 if ( !file_exists( $path ) || !is_dir( $path ) ) {
459 continue;
460 }
461 $dir = opendir( $path );
462 while ( false !== ( $name = readdir( $dir ) ) ) {
463 call_user_func( $callback, $path . '/' . $name );
464 }
465 }
466 }
467
468 /**
469 * Call a callback function for every file in the repository
470 * May use either the database or the filesystem
471 */
472 function enumFiles( $callback ) {
473 $this->enumFilesInFS( $callback );
474 }
475
476 /**
477 * Get properties of a file with a given virtual URL
478 * The virtual URL must refer to this repo
479 */
480 function getFileProps( $virtualUrl ) {
481 $path = $this->resolveVirtualUrl( $virtualUrl );
482 return File::getPropsFromPath( $path );
483 }
484
485 /**
486 * Path disclosure protection functions
487 *
488 * Get a callback function to use for cleaning error message parameters
489 */
490 function getErrorCleanupFunction() {
491 switch ( $this->pathDisclosureProtection ) {
492 case 'simple':
493 $callback = array( $this, 'simpleClean' );
494 break;
495 default:
496 $callback = parent::getErrorCleanupFunction();
497 }
498 return $callback;
499 }
500
501 function simpleClean( $param ) {
502 if ( !isset( $this->simpleCleanPairs ) ) {
503 global $IP;
504 $this->simpleCleanPairs = array(
505 $this->directory => 'public',
506 "{$this->directory}/temp" => 'temp',
507 $IP => '$IP',
508 dirname( __FILE__ ) => '$IP/extensions/WebStore',
509 );
510 if ( $this->deletedDir ) {
511 $this->simpleCleanPairs[$this->deletedDir] = 'deleted';
512 }
513 }
514 return strtr( $param, $this->simpleCleanPairs );
515 }
516
517 }
518
519