4 * A repository for files accessible via the local filesystem. Does not support
5 * database access or registration.
8 class FSRepo
extends FileRepo
{
9 var $directory, $deletedDir, $url, $deletedHashLevels, $fileMode;
10 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
11 var $oldFileFactory = false;
12 var $pathDisclosureProtection = 'simple';
14 function __construct( $info ) {
15 parent
::__construct( $info );
18 $this->directory
= $info['directory'];
19 $this->url
= $info['url'];
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 $this->fileMode
= isset( $info['fileMode'] ) ?
$info['fileMode'] : 0644;
27 if ( isset( $info['thumbDir'] ) ) {
28 $this->thumbDir
= $info['thumbDir'];
30 $this->thumbDir
= "{$this->directory}/thumb";
32 if ( isset( $info['thumbUrl'] ) ) {
33 $this->thumbUrl
= $info['thumbUrl'];
35 $this->thumbUrl
= "{$this->url}/thumb";
40 * Get the public root directory of the repository.
42 function getRootDirectory() {
43 return $this->directory
;
47 * Get the public root URL of the repository
49 function getRootUrl() {
54 * Returns true if the repository uses a multi-level directory structure
57 return (bool)$this->hashLevels
;
61 * Get the local directory corresponding to one of the three basic zones
63 function getZonePath( $zone ) {
66 return $this->directory
;
68 return "{$this->directory}/temp";
70 return $this->deletedDir
;
72 return $this->thumbDir
;
79 * Get the URL corresponding to one of the three basic zones
81 function getZoneUrl( $zone ) {
86 return "{$this->url}/temp";
88 return false; // no public URL
90 return $this->thumbUrl
;
97 * Get a URL referring to this repository, with the private mwrepo protocol.
98 * The suffix, if supplied, is considered to be unencoded, and will be
99 * URL-encoded before being returned.
101 function getVirtualUrl( $suffix = false ) {
102 $path = 'mwrepo://' . $this->name
;
103 if ( $suffix !== false ) {
104 $path .= '/' . rawurlencode( $suffix );
110 * Get the local path corresponding to a virtual URL
112 function resolveVirtualUrl( $url ) {
113 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
114 throw new MWException( __METHOD__
.': unknown protoocl' );
117 $bits = explode( '/', substr( $url, 9 ), 3 );
118 if ( count( $bits ) != 3 ) {
119 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
121 list( $repo, $zone, $rel ) = $bits;
122 if ( $repo !== $this->name
) {
123 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
125 $base = $this->getZonePath( $zone );
127 throw new MWException( __METHOD__
.": invalid zone: $zone" );
129 return $base . '/' . rawurldecode( $rel );
133 * Store a batch of files
135 * @param array $triplets (src,zone,dest) triplets as per store()
136 * @param integer $flags Bitwise combination of the following flags:
137 * self::DELETE_SOURCE Delete the source file after upload
138 * self::OVERWRITE Overwrite an existing destination file instead of failing
139 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
140 * same contents as the source
142 function storeBatch( $triplets, $flags = 0 ) {
143 if ( !wfMkdirParents( $this->directory
) ) {
144 return $this->newFatal( 'upload_directory_missing', $this->directory
);
146 if ( !is_writable( $this->directory
) ) {
147 return $this->newFatal( 'upload_directory_read_only', $this->directory
);
149 $status = $this->newGood();
150 foreach ( $triplets as $i => $triplet ) {
151 list( $srcPath, $dstZone, $dstRel ) = $triplet;
153 $root = $this->getZonePath( $dstZone );
155 throw new MWException( "Invalid zone: $dstZone" );
157 if ( !$this->validateFilename( $dstRel ) ) {
158 throw new MWException( 'Validation error in $dstRel' );
160 $dstPath = "$root/$dstRel";
161 $dstDir = dirname( $dstPath );
163 if ( !is_dir( $dstDir ) ) {
164 if ( !wfMkdirParents( $dstDir ) ) {
165 return $this->newFatal( 'directorycreateerror', $dstDir );
167 if ( $dstZone == 'deleted' ) {
168 $this->initDeletedDir( $dstDir );
172 if ( self
::isVirtualUrl( $srcPath ) ) {
173 $srcPath = $triplets[$i][0] = $this->resolveVirtualUrl( $srcPath );
175 if ( !is_file( $srcPath ) ) {
176 // Make a list of files that don't exist for return to the caller
177 $status->fatal( 'filenotfound', $srcPath );
180 if ( !( $flags & self
::OVERWRITE
) && file_exists( $dstPath ) ) {
181 if ( $flags & self
::OVERWRITE_SAME
) {
182 $hashSource = sha1_file( $srcPath );
183 $hashDest = sha1_file( $dstPath );
184 if ( $hashSource != $hashDest ) {
185 $status->fatal( 'fileexistserror', $dstPath );
188 $status->fatal( 'fileexistserror', $dstPath );
193 $deleteDest = wfIsWindows() && ( $flags & self
::OVERWRITE
);
195 // Abort now on failure
196 if ( !$status->ok
) {
200 foreach ( $triplets as $triplet ) {
201 list( $srcPath, $dstZone, $dstRel ) = $triplet;
202 $root = $this->getZonePath( $dstZone );
203 $dstPath = "$root/$dstRel";
206 if ( $flags & self
::DELETE_SOURCE
) {
210 if ( !rename( $srcPath, $dstPath ) ) {
211 $status->error( 'filerenameerror', $srcPath, $dstPath );
215 if ( !copy( $srcPath, $dstPath ) ) {
216 $status->error( 'filecopyerror', $srcPath, $dstPath );
221 $this->chmod( $dstPath );
222 $status->successCount++
;
224 $status->failCount++
;
229 function append( $srcPath, $toAppendPath ){
230 $status = $this->newGood();
232 //resolve the virtual url:
233 if ( self
::isVirtualUrl( $srcPath ) ) {
234 $srcPath = $this->resolveVirtualUrl( $srcPath );
236 //make sure files are there:
237 if ( !is_file( $srcPath ) )
238 $status->fatal( 'append-src-filenotfound', $srcPath );
240 if ( !is_file( $toAppendPath ) )
241 $status->fatal( 'append-toappend-filenotfound', $toAppendPath );
244 if( file_put_contents( $srcPath, file_get_contents( $toAppendPath ), FILE_APPEND
) ){
245 $status->value
= $srcPath;
247 $status->fatal( 'fileappenderror', $toAppendPath, $srcPath);
250 //either way remove the append chunk as we have no use for it now:
251 unlink($toAppendPath);
256 * Checks existence of specified array of files.
258 * @param array $files URLs of files to check
259 * @param integer $flags Bitwise combination of the following flags:
260 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
261 * @return Either array of files and existence flags, or false
263 function fileExistsBatch( $files, $flags = 0 ) {
264 if ( !file_exists( $this->directory
) ||
!is_readable( $this->directory
) ) {
268 foreach ( $files as $key => $file ) {
269 if ( self
::isVirtualUrl( $file ) ) {
270 $file = $this->resolveVirtualUrl( $file );
272 if( $flags & self
::FILES_ONLY
) {
273 $result[$key] = is_file( $file );
275 $result[$key] = file_exists( $file );
283 * Take all available measures to prevent web accessibility of new deleted
284 * directories, in case the user has not configured offline storage
286 protected function initDeletedDir( $dir ) {
287 // Add a .htaccess file to the root of the deleted zone
288 $root = $this->getZonePath( 'deleted' );
289 if ( !file_exists( "$root/.htaccess" ) ) {
290 file_put_contents( "$root/.htaccess", "Deny from all\n" );
292 // Seed new directories with a blank index.html, to prevent crawling
293 file_put_contents( "$dir/index.html", '' );
297 * Pick a random name in the temp zone and store a file to it.
298 * @param string $originalName The base name of the file as specified
299 * by the user. The file extension will be maintained.
300 * @param string $srcPath The current location of the file.
301 * @return FileRepoStatus object with the URL in the value.
303 function storeTemp( $originalName, $srcPath ) {
304 $date = gmdate( "YmdHis" );
305 $hashPath = $this->getHashPath( $originalName );
306 $dstRel = "$hashPath$date!$originalName";
307 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
309 $result = $this->store( $srcPath, 'temp', $dstRel );
310 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
315 * Remove a temporary file or mark it for garbage collection
316 * @param string $virtualUrl The virtual URL returned by storeTemp
317 * @return boolean True on success, false on failure
319 function freeTemp( $virtualUrl ) {
320 $temp = "mwrepo://{$this->name}/temp";
321 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
322 wfDebug( __METHOD__
.": Invalid virtual URL\n" );
325 $path = $this->resolveVirtualUrl( $virtualUrl );
326 wfSuppressWarnings();
327 $success = unlink( $path );
333 * Publish a batch of files
334 * @param array $triplets (source,dest,archive) triplets as per publish()
335 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
336 * that the source files should be deleted if possible
338 function publishBatch( $triplets, $flags = 0 ) {
339 // Perform initial checks
340 if ( !wfMkdirParents( $this->directory
) ) {
341 return $this->newFatal( 'upload_directory_missing', $this->directory
);
343 if ( !is_writable( $this->directory
) ) {
344 return $this->newFatal( 'upload_directory_read_only', $this->directory
);
346 $status = $this->newGood( array() );
347 foreach ( $triplets as $i => $triplet ) {
348 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
350 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
351 $triplets[$i][0] = $srcPath = $this->resolveVirtualUrl( $srcPath );
353 if ( !$this->validateFilename( $dstRel ) ) {
354 throw new MWException( 'Validation error in $dstRel' );
356 if ( !$this->validateFilename( $archiveRel ) ) {
357 throw new MWException( 'Validation error in $archiveRel' );
359 $dstPath = "{$this->directory}/$dstRel";
360 $archivePath = "{$this->directory}/$archiveRel";
362 $dstDir = dirname( $dstPath );
363 $archiveDir = dirname( $archivePath );
364 // Abort immediately on directory creation errors since they're likely to be repetitive
365 if ( !is_dir( $dstDir ) && !wfMkdirParents( $dstDir ) ) {
366 return $this->newFatal( 'directorycreateerror', $dstDir );
368 if ( !is_dir( $archiveDir ) && !wfMkdirParents( $archiveDir ) ) {
369 return $this->newFatal( 'directorycreateerror', $archiveDir );
371 if ( !is_file( $srcPath ) ) {
372 // Make a list of files that don't exist for return to the caller
373 $status->fatal( 'filenotfound', $srcPath );
377 if ( !$status->ok
) {
381 foreach ( $triplets as $i => $triplet ) {
382 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
383 $dstPath = "{$this->directory}/$dstRel";
384 $archivePath = "{$this->directory}/$archiveRel";
386 // Archive destination file if it exists
387 if( is_file( $dstPath ) ) {
388 // Check if the archive file exists
389 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
390 // unlinks the destination file if it exists. DB-based synchronisation in
391 // publishBatch's caller should prevent races. In Windows there's no
392 // problem because the rename primitive fails if the destination exists.
393 if ( is_file( $archivePath ) ) {
396 wfSuppressWarnings();
397 $success = rename( $dstPath, $archivePath );
402 $status->error( 'filerenameerror',$dstPath, $archivePath );
403 $status->failCount++
;
406 wfDebug(__METHOD__
.": moved file $dstPath to $archivePath\n");
408 $status->value
[$i] = 'archived';
410 $status->value
[$i] = 'new';
414 wfSuppressWarnings();
415 if ( $flags & self
::DELETE_SOURCE
) {
416 if ( !rename( $srcPath, $dstPath ) ) {
417 $status->error( 'filerenameerror', $srcPath, $dstPath );
421 if ( !copy( $srcPath, $dstPath ) ) {
422 $status->error( 'filecopyerror', $srcPath, $dstPath );
429 $status->successCount++
;
430 wfDebug(__METHOD__
.": wrote tempfile $srcPath to $dstPath\n");
431 // Thread-safe override for umask
432 $this->chmod( $dstPath );
434 $status->failCount++
;
441 * Move a group of files to the deletion archive.
442 * If no valid deletion archive is configured, this may either delete the
443 * file or throw an exception, depending on the preference of the repository.
445 * @param array $sourceDestPairs Array of source/destination pairs. Each element
446 * is a two-element array containing the source file path relative to the
447 * public root in the first element, and the archive file path relative
448 * to the deleted zone root in the second element.
449 * @return FileRepoStatus
451 function deleteBatch( $sourceDestPairs ) {
452 $status = $this->newGood();
453 if ( !$this->deletedDir
) {
454 throw new MWException( __METHOD__
.': no valid deletion archive directory' );
458 * Validate filenames and create archive directories
460 foreach ( $sourceDestPairs as $pair ) {
461 list( $srcRel, $archiveRel ) = $pair;
462 if ( !$this->validateFilename( $srcRel ) ) {
463 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
465 if ( !$this->validateFilename( $archiveRel ) ) {
466 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
468 $archivePath = "{$this->deletedDir}/$archiveRel";
469 $archiveDir = dirname( $archivePath );
470 if ( !is_dir( $archiveDir ) ) {
471 if ( !wfMkdirParents( $archiveDir ) ) {
472 $status->fatal( 'directorycreateerror', $archiveDir );
475 $this->initDeletedDir( $archiveDir );
477 // Check if the archive directory is writable
478 // This doesn't appear to work on NTFS
479 if ( !is_writable( $archiveDir ) ) {
480 $status->fatal( 'filedelete-archive-read-only', $archiveDir );
483 if ( !$status->ok
) {
490 * We're now committed to returning an OK result, which will lead to
491 * the files being moved in the DB also.
493 foreach ( $sourceDestPairs as $pair ) {
494 list( $srcRel, $archiveRel ) = $pair;
495 $srcPath = "{$this->directory}/$srcRel";
496 $archivePath = "{$this->deletedDir}/$archiveRel";
498 if ( file_exists( $archivePath ) ) {
499 # A file with this content hash is already archived
500 if ( !@unlink
( $srcPath ) ) {
501 $status->error( 'filedeleteerror', $srcPath );
505 if ( !@rename
( $srcPath, $archivePath ) ) {
506 $status->error( 'filerenameerror', $srcPath, $archivePath );
509 $this->chmod( $archivePath );
513 $status->successCount++
;
515 $status->failCount++
;
522 * Get a relative path for a deletion archive key,
523 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
525 function getDeletedHashPath( $key ) {
527 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
528 $path .= $key[$i] . '/';
534 * Call a callback function for every file in the repository.
535 * Uses the filesystem even in child classes.
537 function enumFilesInFS( $callback ) {
538 $numDirs = 1 << ( $this->hashLevels
* 4 );
539 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
540 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
541 $path = $this->directory
;
542 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
543 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
545 if ( !file_exists( $path ) ||
!is_dir( $path ) ) {
548 $dir = opendir( $path );
549 while ( false !== ( $name = readdir( $dir ) ) ) {
550 call_user_func( $callback, $path . '/' . $name );
556 * Call a callback function for every file in the repository
557 * May use either the database or the filesystem
559 function enumFiles( $callback ) {
560 $this->enumFilesInFS( $callback );
564 * Get properties of a file with a given virtual URL
565 * The virtual URL must refer to this repo
567 function getFileProps( $virtualUrl ) {
568 $path = $this->resolveVirtualUrl( $virtualUrl );
569 return File
::getPropsFromPath( $path );
573 * Path disclosure protection functions
575 * Get a callback function to use for cleaning error message parameters
577 function getErrorCleanupFunction() {
578 switch ( $this->pathDisclosureProtection
) {
580 $callback = array( $this, 'simpleClean' );
583 $callback = parent
::getErrorCleanupFunction();
588 function simpleClean( $param ) {
589 if ( !isset( $this->simpleCleanPairs
) ) {
591 $this->simpleCleanPairs
= array(
592 $this->directory
=> 'public',
593 "{$this->directory}/temp" => 'temp',
595 dirname( __FILE__
) => '$IP/extensions/WebStore',
597 if ( $this->deletedDir
) {
598 $this->simpleCleanPairs
[$this->deletedDir
] = 'deleted';
601 return strtr( $param, $this->simpleCleanPairs
);
605 * Chmod a file, supressing the warnings.
606 * @param String $path The path to change
608 protected function chmod( $path ) {
609 wfSuppressWarnings();
610 chmod( $path, $this->fileMode
);