Made wfMkdirParents() faster and more robust
authorTim Starling <tstarling@users.mediawiki.org>
Tue, 4 Jul 2006 14:08:27 +0000 (14:08 +0000)
committerTim Starling <tstarling@users.mediawiki.org>
Tue, 4 Jul 2006 14:08:27 +0000 (14:08 +0000)
includes/GlobalFunctions.php

index 0abdda7..8b8d57a 100644 (file)
@@ -1535,18 +1535,46 @@ function wfTempDir() {
 /**
  * Make directory, and make all parent directories if they don't exist
  */
-function wfMkdirParents( $fullDir, $mode ) {
-       $parts = explode( '/', $fullDir );
-       $path = '';
-
-       foreach ( $parts as $dir ) {
-               $path .= $dir . '/';
-               if ( !is_dir( $path ) ) {
-                       if ( !mkdir( $path, $mode ) ) {
-                               return false;
-                       }
+function wfMkdirParents( $fullDir, $mode = 0777 ) {
+       if ( strval( $fullDir ) === '' ) {
+               return true;
+       }
+       
+       # Go back through the paths to find the first directory that exists
+       $currentDir = $fullDir;
+       $createList = array();
+       while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) { 
+               # Strip trailing slashes
+               $currentDir = rtrim( $currentDir, '/\\' );
+
+               # Add to create list
+               $createList[] = $currentDir;
+
+               # Find next delimiter searching from the end
+               $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
+               if ( $p === false ) {
+                       $currentDir = false;
+               } else {
+                       $currentDir = substr( $currentDir, 0, $p );
                }
        }
+       
+       if ( count( $createList ) == 0 ) {
+               # Directory specified already exists
+               return true;
+       } elseif ( $currentDir === false ) {
+               # Went all the way back to root and it apparently doesn't exist
+               return false;
+       }
+       
+       # Now go forward creating directories
+       $createList = array_reverse( $createList );
+       foreach ( $createList as $dir ) {
+               # use chmod to override the umask, as suggested by the PHP manual
+               if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
+                       return false;
+               } 
+       }
        return true;
 }