penguin/utils

my env utils

php/regRename.php

raw ยท 5941 bytes

<?php

error_reporting ( E_ALL^E_NOTICE ) ;

//----------- Usage -----------

if ( !$argv[1] ) 
	die ( "Usage: php {$argv[0]} [options] [-d directory] [-p patterns] [-s \"first match\" \"second\" ...] [...args]\n
  -d <paths>	Directories to look over
  -p <patterns>	Define RegEx patterns
  -r		Rename file recursively
  -s <str ...>	Strings that will replace the matches

  Optional:
	*-e <patterns>	Exclude defined pattern
	*-l <File>	Output log file
	-t		Test without modifying anything

*Not available yet.

" ) ;

//------- End Usage -----------




//Define globals
$test = false;
$recursive = false;
$searchDirs = array();
$patterns = array();
$replaceStrs = array();

//------- Main Functions --------
function getDirName ( $dir ) {
	return is_dir ( $dir ) ? $dir : dirname ( $dir ) ;
}

function getFileList ( $dir ) {
	$fileList = array();
	$iterator = new DirectoryIterator ( getDirName ( $dir )  ) ;
	foreach ( $iterator as $fileinfo ) {
		if ( $fileinfo->isFile() ) {
				$fileList[] = $dir."/".$fileinfo->getFilename();
		}
	}
	return $fileList;
}

function getDirList ( $dir ) {
	$dirList = array();
	$iterator = new DirectoryIterator ( getDirName ( $dir )  ) ;
	foreach ( $iterator as $fileinfo ) {
			if ( $fileinfo->isDir() ) {
					$dirList[] = $fileinfo->getFilename();
			}
	}
	//Chop dir "." and ".."
	array_shift ( $dirList ) ;
	array_shift ( $dirList ) ;
	return $dirList;
}

function getWholeDirList ( $dir ) {
	$wholeDirList = array();
	//getWholeDirList will stop untill getDirList return an empty array.
	foreach ( getDirList ( $dir ) as $file ) {
			//Store found path
			$wholeDirList[] = "$dir/$file";
			//Method getWholeDirList will self-iterate if sub-directories exist.
			$wholeDirList = array_merge ( $wholeDirList, getWholeDirList ( "$dir/$file" )  ) ;
	}
	return $wholeDirList;
}

function getWholeFileList ( $dir ) {
	//Get the first level list.
	$wholeFileList = getFileList( $dir );
	//getWholeDirList and search its files.
	foreach ( getWholeDirList ( $dir ) as $dir ) {
		$wholeFileList = array_merge ( $wholeFileList, getFileList ( $dir )  ) ;
	}
	return $wholeFileList;
}

function validateOptions (  ) {
	global $searchDirs, $patterns, $replaceStrs;
	
	try {
		if(count($searchDirs) == 0)
		throw new Exception("Search directory is missing");
		else if(count($patterns) == 0)
		throw new Exception("Search pattern is missing");
		else if(count($replaceStrs) == 0)
		throw new Exception("Replacement string is missing");
		else if(count($replaceStrs) != count($patterns))
		throw new Exception("Replacement string and pattern count not match");
	} catch(Exception $e) {
		var_dump( $GLOBALS );
		die("Error: $e.\n");
	}
}

function setOptions( $item, $value = NULL ) {
	global $test, $recursive, $searchDirs, $patterns, $replaceStrs;
	switch($item) {
		case "-d":
			if($value)
			$searchDirs[] = $value;
		break;
		case "-p":
			if($value)
			$patterns[] = $value;
		break;
		case "-r":
			$recursive = true;
		break;
		case "-s":
			if($value)
			$replaceStrs[] = $value;
		break;
		case "-t":
			$test = true;
		break;
		default:
			//Do nothing
	}
}

//parseOptions utilitiese by tgckpg
function parseOptions ( $argStream, $handler ) {
	//Chop first useless argument -- argv[0]
	array_shift ( $argStream ) ;
	//Initiate ArrayObject for iterator
	$arrayobject = new ArrayObject ( $argStream ) ;
	//Initiate iterator for iteration
	$iterator = $arrayobject->getIterator();

	//If options is set first
	if( $iterator->valid() && preg_match ( '/^-\w$/', $iterator->current() ) ) {
		//iterate through whole argument stream
		for (	; $iterator->valid(); $iterator->next() ) {
			//Check if reached next option
			if( preg_match ( '/^-\w$/', $opts = $iterator->current() ) ) {
				//Get current options
				$currOpt = $opts;
				//echo "$currOpt\n";
				//Test if next stream is an option
				for ( $iterator->next(); $iterator->valid(); $iterator->next() ) {
					if ( preg_match ( '/^-\w$/', $opts = $iterator->current() ) ) {
						//echo "$currOpt $opts\n";
						$handler($currOpt);
						$currOpt = $opts;
					} else break;
					//var_dump($iterator->valid());
				}
			}//End if
			//echo "$currOpt $opts\n";
			$handler($currOpt, $opts);
			//A temporary fix for infinite loop
			if(!$iterator->valid())
				break;
		}// End for
	//If option is not set first.
	} else {
		//Try other approach.
	}// End if
}


//------- End Main Functions --------


parseOptions ( $argv, 'setOptions' ) ;
validateOptions();


//------- Begin Operations -------
foreach ( $searchDirs as $dir ) {
	echo "Directory: $dir\nBuilding file list ...\n";
	if ( $recursive ) {
		$fileList = getWholeFileList($dir);
	}	else {
		$fileList = getFileList($dir);
	}
	echo "Searching ...\n";
	foreach ( $fileList as $file ) {
		//
		// Get the file name
		// RegExplained:
		// Example: /foo/bar/foobar.bar
		//   $matches[0][0] is the whole string "/foo/bar/foobar.bar"
		//
		//   ^(.+?)
		//   This gets the file path "/foo/bar/" for $matches[1][0]
		//
		//   ([^\/\\\\]+)$
		//   This gets the file name "foobar.bar" for $matches[2][0]
		//
		preg_match_all('/^(.+?)([^\/\\\\]+)$/', $file, $matches );
		$newName = $matches[2][0];
		foreach ( $patterns as $key => $pattern ) {
			//Rename over the patterns
			$newName = preg_replace( $pattern, $replaceStrs[$key], $newName );
		}
		if( $matches[2][0] != $newName ) {
			if( $test ) {
				echo "File \"{$matches[2][0]}\" will renamed to \"$newName\"\n";
			} else {
				rename ( $file, "{$matches[1][0]}$newName" );
			}
			if ( $logfile ) {
				
			}
		}/* else {
			echo "File \"{$matches[0][0]}\" will not be renamed\n";
		}
		//*/
	}
	echo "\n";
}
if ( $test ) echo "*** Test enabled ***\n\n";



//------- End Operations -------*/
?>