3 * A repository for files accessible via the local filesystem.
10 * A repository for files accessible via the local filesystem. Does not support
11 * database access or registration.
14 class FSRepo
extends FileRepo
{
15 var $directory, $deletedDir, $deletedHashLevels, $fileMode;
16 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
17 var $oldFileFactory = false;
18 var $pathDisclosureProtection = 'simple';
20 function __construct( $info ) {
21 parent
::__construct( $info );
24 $this->directory
= $info['directory'];
25 $this->url
= $info['url'];
28 $this->hashLevels
= isset( $info['hashLevels'] ) ?
$info['hashLevels'] : 2;
29 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] ) ?
30 $info['deletedHashLevels'] : $this->hashLevels
;
31 $this->deletedDir
= isset( $info['deletedDir'] ) ?
$info['deletedDir'] : false;
32 $this->fileMode
= isset( $info['fileMode'] ) ?
$info['fileMode'] : 0644;
33 if ( isset( $info['thumbDir'] ) ) {
34 $this->thumbDir
= $info['thumbDir'];
36 $this->thumbDir
= "{$this->directory}/thumb";
38 if ( isset( $info['thumbUrl'] ) ) {
39 $this->thumbUrl
= $info['thumbUrl'];
41 $this->thumbUrl
= "{$this->url}/thumb";
46 * Get the public root directory of the repository.
48 function getRootDirectory() {
49 return $this->directory
;
53 * Get the public root URL of the repository
55 function getRootUrl() {
60 * Returns true if the repository uses a multi-level directory structure
63 return (bool)$this->hashLevels
;
67 * Get the local directory corresponding to one of the three basic zones
73 function getZonePath( $zone ) {
76 return $this->directory
;
78 return "{$this->directory}/temp";
80 return $this->deletedDir
;
82 return $this->thumbDir
;
89 * @see FileRepo::getZoneUrl()
95 function getZoneUrl( $zone ) {
100 return "{$this->url}/temp";
102 return parent
::getZoneUrl( $zone ); // no public URL
104 return $this->thumbUrl
;
106 return parent
::getZoneUrl( $zone );
111 * Get a URL referring to this repository, with the private mwrepo protocol.
112 * The suffix, if supplied, is considered to be unencoded, and will be
113 * URL-encoded before being returned.
115 * @param $suffix string
119 function getVirtualUrl( $suffix = false ) {
120 $path = 'mwrepo://' . $this->name
;
121 if ( $suffix !== false ) {
122 $path .= '/' . rawurlencode( $suffix );
128 * Get the local path corresponding to a virtual URL
134 function resolveVirtualUrl( $url ) {
135 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
136 throw new MWException( __METHOD__
.': unknown protocol' );
139 $bits = explode( '/', substr( $url, 9 ), 3 );
140 if ( count( $bits ) != 3 ) {
141 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
143 list( $repo, $zone, $rel ) = $bits;
144 if ( $repo !== $this->name
) {
145 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
147 $base = $this->getZonePath( $zone );
149 throw new MWException( __METHOD__
.": invalid zone: $zone" );
151 return $base . '/' . rawurldecode( $rel );
155 * Store a batch of files
157 * @param $triplets Array: (src,zone,dest) triplets as per store()
158 * @param $flags Integer: bitwise combination of the following flags:
159 * self::DELETE_SOURCE Delete the source file after upload
160 * self::OVERWRITE Overwrite an existing destination file instead of failing
161 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
162 * same contents as the source
164 function storeBatch( $triplets, $flags = 0 ) {
165 wfDebug( __METHOD__
. ': Storing ' . count( $triplets ) .
166 " triplets; flags: {$flags}\n" );
168 // Try creating directories
169 if ( !wfMkdirParents( $this->directory
) ) {
170 return $this->newFatal( 'upload_directory_missing', $this->directory
);
172 if ( !is_writable( $this->directory
) ) {
173 return $this->newFatal( 'upload_directory_read_only', $this->directory
);
176 // Validate each triplet
177 $status = $this->newGood();
178 foreach ( $triplets as $i => $triplet ) {
179 list( $srcPath, $dstZone, $dstRel ) = $triplet;
181 // Resolve destination path
182 $root = $this->getZonePath( $dstZone );
184 throw new MWException( "Invalid zone: $dstZone" );
186 if ( !$this->validateFilename( $dstRel ) ) {
187 throw new MWException( 'Validation error in $dstRel' );
189 $dstPath = "$root/$dstRel";
190 $dstDir = dirname( $dstPath );
192 // Create destination directories for this triplet
193 if ( !is_dir( $dstDir ) ) {
194 if ( !wfMkdirParents( $dstDir ) ) {
195 return $this->newFatal( 'directorycreateerror', $dstDir );
197 if ( $dstZone == 'deleted' ) {
198 $this->initDeletedDir( $dstDir );
203 if ( self
::isVirtualUrl( $srcPath ) ) {
204 $srcPath = $triplets[$i][0] = $this->resolveVirtualUrl( $srcPath );
206 if ( !is_file( $srcPath ) ) {
207 // Make a list of files that don't exist for return to the caller
208 $status->fatal( 'filenotfound', $srcPath );
213 if ( !( $flags & self
::OVERWRITE
) && file_exists( $dstPath ) ) {
214 if ( $flags & self
::OVERWRITE_SAME
) {
215 $hashSource = sha1_file( $srcPath );
216 $hashDest = sha1_file( $dstPath );
217 if ( $hashSource != $hashDest ) {
218 $status->fatal( 'fileexistserror', $dstPath );
221 $status->fatal( 'fileexistserror', $dstPath );
226 // Windows does not support moving over existing files, so explicitly delete them
227 $deleteDest = wfIsWindows() && ( $flags & self
::OVERWRITE
);
229 // Abort now on failure
230 if ( !$status->ok
) {
234 // Execute the store operation for each triplet
235 foreach ( $triplets as $i => $triplet ) {
236 list( $srcPath, $dstZone, $dstRel ) = $triplet;
237 $root = $this->getZonePath( $dstZone );
238 $dstPath = "$root/$dstRel";
241 if ( $flags & self
::DELETE_SOURCE
) {
245 if ( !rename( $srcPath, $dstPath ) ) {
246 $status->error( 'filerenameerror', $srcPath, $dstPath );
250 if ( !copy( $srcPath, $dstPath ) ) {
251 $status->error( 'filecopyerror', $srcPath, $dstPath );
254 if ( !( $flags & self
::SKIP_VALIDATION
) ) {
255 wfSuppressWarnings();
256 $hashSource = sha1_file( $srcPath );
257 $hashDest = sha1_file( $dstPath );
260 if ( $hashDest === false ||
$hashSource !== $hashDest ) {
261 wfDebug( __METHOD__
. ': File copy validation failed: ' .
262 "$srcPath ($hashSource) to $dstPath ($hashDest)\n" );
264 $status->error( 'filecopyerror', $srcPath, $dstPath );
270 $this->chmod( $dstPath );
271 $status->successCount++
;
273 $status->failCount++
;
275 $status->success
[$i] = $good;
281 * Deletes a batch of files. Each file can be a (zone, rel) pairs, a
282 * virtual url or a real path. It will try to delete each file, but
283 * ignores any errors that may occur
285 * @param $pairs array List of files to delete
287 function cleanupBatch( $files ) {
288 foreach ( $files as $file ) {
289 if ( is_array( $file ) ) {
290 // This is a pair, extract it
291 list( $zone, $rel ) = $file;
292 $root = $this->getZonePath( $zone );
293 $path = "$root/$rel";
295 if ( self
::isVirtualUrl( $file ) ) {
296 // This is a virtual url, resolve it
297 $path = $this->resolveVirtualUrl( $file );
299 // This is a full file name
304 wfSuppressWarnings();
310 function append( $srcPath, $toAppendPath, $flags = 0 ) {
311 $status = $this->newGood();
313 // Resolve the virtual URL
314 if ( self
::isVirtualUrl( $toAppendPath ) ) {
315 $toAppendPath = $this->resolveVirtualUrl( $toAppendPath );
317 // Make sure the files are there
318 if ( !is_file( $toAppendPath ) )
319 $status->fatal( 'filenotfound', $toAppendPath );
321 if ( !is_file( $srcPath ) )
322 $status->fatal( 'filenotfound', $srcPath );
324 if ( !$status->isOk() ) return $status;
327 $chunk = file_get_contents( $srcPath );
328 if( $chunk === false ) {
329 $status->fatal( 'fileappenderrorread', $srcPath );
332 if( $status->isOk() ) {
333 if ( file_put_contents( $toAppendPath, $chunk, FILE_APPEND
) ) {
334 $status->value
= $toAppendPath;
336 $status->fatal( 'fileappenderror', $srcPath, $toAppendPath);
340 if ( $flags & self
::DELETE_SOURCE
) {
347 /* We can actually append to the files, so no-op needed here. */
348 function appendFinish( $toAppendPath ) {}
351 * Checks existence of specified array of files.
353 * @param $files Array: URLs of files to check
354 * @param $flags Integer: bitwise combination of the following flags:
355 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
356 * @return Either array of files and existence flags, or false
358 function fileExistsBatch( $files, $flags = 0 ) {
359 if ( !file_exists( $this->directory
) ||
!is_readable( $this->directory
) ) {
363 foreach ( $files as $key => $file ) {
364 if ( self
::isVirtualUrl( $file ) ) {
365 $file = $this->resolveVirtualUrl( $file );
367 if( $flags & self
::FILES_ONLY
) {
368 $result[$key] = is_file( $file );
370 $result[$key] = file_exists( $file );
378 * Take all available measures to prevent web accessibility of new deleted
379 * directories, in case the user has not configured offline storage
381 protected function initDeletedDir( $dir ) {
382 // Add a .htaccess file to the root of the deleted zone
383 $root = $this->getZonePath( 'deleted' );
384 if ( !file_exists( "$root/.htaccess" ) ) {
385 file_put_contents( "$root/.htaccess", "Deny from all\n" );
387 // Seed new directories with a blank index.html, to prevent crawling
388 file_put_contents( "$dir/index.html", '' );
392 * Pick a random name in the temp zone and store a file to it.
393 * @param $originalName String: the base name of the file as specified
394 * by the user. The file extension will be maintained.
395 * @param $srcPath String: the current location of the file.
396 * @return FileRepoStatus object with the URL in the value.
398 function storeTemp( $originalName, $srcPath ) {
399 $date = gmdate( "YmdHis" );
400 $hashPath = $this->getHashPath( $originalName );
401 $dstRel = "$hashPath$date!$originalName";
402 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
404 $result = $this->store( $srcPath, 'temp', $dstRel );
405 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
410 * Remove a temporary file or mark it for garbage collection
411 * @param $virtualUrl String: the virtual URL returned by storeTemp
412 * @return Boolean: true on success, false on failure
414 function freeTemp( $virtualUrl ) {
415 $temp = "mwrepo://{$this->name}/temp";
416 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
417 wfDebug( __METHOD__
.": Invalid virtual URL\n" );
420 $path = $this->resolveVirtualUrl( $virtualUrl );
421 wfSuppressWarnings();
422 $success = unlink( $path );
428 * Publish a batch of files
429 * @param $triplets Array: (source,dest,archive) triplets as per publish()
430 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
431 * that the source files should be deleted if possible
433 function publishBatch( $triplets, $flags = 0 ) {
434 // Perform initial checks
435 if ( !wfMkdirParents( $this->directory
) ) {
436 return $this->newFatal( 'upload_directory_missing', $this->directory
);
438 if ( !is_writable( $this->directory
) ) {
439 return $this->newFatal( 'upload_directory_read_only', $this->directory
);
441 $status = $this->newGood( array() );
442 foreach ( $triplets as $i => $triplet ) {
443 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
445 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
446 $triplets[$i][0] = $srcPath = $this->resolveVirtualUrl( $srcPath );
448 if ( !$this->validateFilename( $dstRel ) ) {
449 throw new MWException( 'Validation error in $dstRel' );
451 if ( !$this->validateFilename( $archiveRel ) ) {
452 throw new MWException( 'Validation error in $archiveRel' );
454 $dstPath = "{$this->directory}/$dstRel";
455 $archivePath = "{$this->directory}/$archiveRel";
457 $dstDir = dirname( $dstPath );
458 $archiveDir = dirname( $archivePath );
459 // Abort immediately on directory creation errors since they're likely to be repetitive
460 if ( !is_dir( $dstDir ) && !wfMkdirParents( $dstDir ) ) {
461 return $this->newFatal( 'directorycreateerror', $dstDir );
463 if ( !is_dir( $archiveDir ) && !wfMkdirParents( $archiveDir ) ) {
464 return $this->newFatal( 'directorycreateerror', $archiveDir );
466 if ( !is_file( $srcPath ) ) {
467 // Make a list of files that don't exist for return to the caller
468 $status->fatal( 'filenotfound', $srcPath );
472 if ( !$status->ok
) {
476 foreach ( $triplets as $i => $triplet ) {
477 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
478 $dstPath = "{$this->directory}/$dstRel";
479 $archivePath = "{$this->directory}/$archiveRel";
481 // Archive destination file if it exists
482 if( is_file( $dstPath ) ) {
483 // Check if the archive file exists
484 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
485 // unlinks the destination file if it exists. DB-based synchronisation in
486 // publishBatch's caller should prevent races. In Windows there's no
487 // problem because the rename primitive fails if the destination exists.
488 if ( is_file( $archivePath ) ) {
491 wfSuppressWarnings();
492 $success = rename( $dstPath, $archivePath );
497 $status->error( 'filerenameerror',$dstPath, $archivePath );
498 $status->failCount++
;
501 wfDebug(__METHOD__
.": moved file $dstPath to $archivePath\n");
503 $status->value
[$i] = 'archived';
505 $status->value
[$i] = 'new';
509 wfSuppressWarnings();
510 if ( $flags & self
::DELETE_SOURCE
) {
511 if ( !rename( $srcPath, $dstPath ) ) {
512 $status->error( 'filerenameerror', $srcPath, $dstPath );
516 if ( !copy( $srcPath, $dstPath ) ) {
517 $status->error( 'filecopyerror', $srcPath, $dstPath );
524 $status->successCount++
;
525 wfDebug(__METHOD__
.": wrote tempfile $srcPath to $dstPath\n");
526 // Thread-safe override for umask
527 $this->chmod( $dstPath );
529 $status->failCount++
;
536 * Move a group of files to the deletion archive.
537 * If no valid deletion archive is configured, this may either delete the
538 * file or throw an exception, depending on the preference of the repository.
540 * @param $sourceDestPairs Array of source/destination pairs. Each element
541 * is a two-element array containing the source file path relative to the
542 * public root in the first element, and the archive file path relative
543 * to the deleted zone root in the second element.
544 * @return FileRepoStatus
546 function deleteBatch( $sourceDestPairs ) {
547 $status = $this->newGood();
548 if ( !$this->deletedDir
) {
549 throw new MWException( __METHOD__
.': no valid deletion archive directory' );
553 * Validate filenames and create archive directories
555 foreach ( $sourceDestPairs as $pair ) {
556 list( $srcRel, $archiveRel ) = $pair;
557 if ( !$this->validateFilename( $srcRel ) ) {
558 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
560 if ( !$this->validateFilename( $archiveRel ) ) {
561 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
563 $archivePath = "{$this->deletedDir}/$archiveRel";
564 $archiveDir = dirname( $archivePath );
565 if ( !is_dir( $archiveDir ) ) {
566 if ( !wfMkdirParents( $archiveDir ) ) {
567 $status->fatal( 'directorycreateerror', $archiveDir );
570 $this->initDeletedDir( $archiveDir );
572 // Check if the archive directory is writable
573 // This doesn't appear to work on NTFS
574 if ( !is_writable( $archiveDir ) ) {
575 $status->fatal( 'filedelete-archive-read-only', $archiveDir );
578 if ( !$status->ok
) {
585 * We're now committed to returning an OK result, which will lead to
586 * the files being moved in the DB also.
588 foreach ( $sourceDestPairs as $pair ) {
589 list( $srcRel, $archiveRel ) = $pair;
590 $srcPath = "{$this->directory}/$srcRel";
591 $archivePath = "{$this->deletedDir}/$archiveRel";
593 if ( file_exists( $archivePath ) ) {
594 # A file with this content hash is already archived
595 if ( !@unlink
( $srcPath ) ) {
596 $status->error( 'filedeleteerror', $srcPath );
600 if ( !@rename
( $srcPath, $archivePath ) ) {
601 $status->error( 'filerenameerror', $srcPath, $archivePath );
604 $this->chmod( $archivePath );
608 $status->successCount++
;
610 $status->failCount++
;
617 * Get a relative path for a deletion archive key,
618 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
620 function getDeletedHashPath( $key ) {
622 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
623 $path .= $key[$i] . '/';
629 * Call a callback function for every file in the repository.
630 * Uses the filesystem even in child classes.
632 function enumFilesInFS( $callback ) {
633 $numDirs = 1 << ( $this->hashLevels
* 4 );
634 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
635 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
636 $path = $this->directory
;
637 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
638 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
640 if ( !file_exists( $path ) ||
!is_dir( $path ) ) {
643 $dir = opendir( $path );
645 while ( false !== ( $name = readdir( $dir ) ) ) {
646 call_user_func( $callback, $path . '/' . $name );
654 * Call a callback function for every file in the repository
655 * May use either the database or the filesystem
657 function enumFiles( $callback ) {
658 $this->enumFilesInFS( $callback );
662 * Get properties of a file with a given virtual URL
663 * The virtual URL must refer to this repo
665 function getFileProps( $virtualUrl ) {
666 $path = $this->resolveVirtualUrl( $virtualUrl );
667 return File
::getPropsFromPath( $path );
671 * Path disclosure protection functions
673 * Get a callback function to use for cleaning error message parameters
675 function getErrorCleanupFunction() {
676 switch ( $this->pathDisclosureProtection
) {
678 $callback = array( $this, 'simpleClean' );
681 $callback = parent
::getErrorCleanupFunction();
686 function simpleClean( $param ) {
687 if ( !isset( $this->simpleCleanPairs
) ) {
689 $this->simpleCleanPairs
= array(
690 $this->directory
=> 'public',
691 "{$this->directory}/temp" => 'temp',
693 dirname( __FILE__
) => '$IP/extensions/WebStore',
695 if ( $this->deletedDir
) {
696 $this->simpleCleanPairs
[$this->deletedDir
] = 'deleted';
699 return strtr( $param, $this->simpleCleanPairs
);
703 * Chmod a file, supressing the warnings.
704 * @param $path String: the path to change
706 protected function chmod( $path ) {
707 wfSuppressWarnings();
708 chmod( $path, $this->fileMode
);