Programming
[Linux/Shell/Bash] Count pattern matches/instances in string
by Chuck Kozler on Jan.20, 2010, under Computers, Linux/Unix, Networks/Servers, Programming, Web Dev
This handy little Bash scripting function will count the number of instances it finds in a string by the given delimeter. As of right now, its pretty basic…I didnt go too far into expanding it and working it (like going through and escaping all character escapes) and only escape for | and \.
function countPatterns { string_in="$1" delim="$2" if [ $delim == "/" ] || [ $delim == "|" ]; then delim="\\$delim"; fi retval=`echo $string_in | perl -ne 'while(/'${delim}'/g){++$count}; print "$count\n"'` return $retval }
Remember, this isnt really completed but you get the idea. The use is something like:
countPatterns "this|is|a|string|" "|" instances="$?" #would output 4 echo $instances
[PHP]Empty an array
by Chuck Kozler on Dec.20, 2009, under Computers, Home, Programming, Web Dev
This simple function will empty an array for you. I had to use this for some stuff I was writing for parsing the results of a MySQL query.
I am surprised that there isnt a built in PHP function for this. If there is, let me know…please!
<?php function emptyArray( $array ) { $size = sizeof( $array ); for( $i = 0; $i < $size; $i++ ) { array_pop( $array ); } } ?>
I would use this so that I could use the same array over and over again in a class and have it be dumped every execution of the function it was being utilized in.
Sphere: Related Content[Ubuntu\Mono\Gnome] GtkMountISO Application Release
by Chuck Kozler on Sep.27, 2009, under Computers, Home, Linux/Unix, Programming, Ubuntu, Windows
So, I guess this is my actual first application release in about 4 years since I stopped writing cheats/hacks for Counter-Strike and Counter-Strike source. You can see the video of this in action below and underneath, a link to download it from. You can find all the information you need in the readme. Please, make sure you read the readme, it will save us all a lot of time. For whatever reason, I am going to post the flow chart I made for the bash installer script. Maybe *someone* can find it useful in the future.
Sphere: Related Content[Ubuntu/Gnome] Gtk ISO Mount Program
by Chuck Kozler on Sep.24, 2009, under Computers, Home, Linux/Unix, Programming, Ubuntu
This is a program I wrote to mount ISO’s under Linux. I wrote it in C# utilizing the Mono libraries. I must say, I love C# so much more now. The video is below and the unedited/uncleaned code is below the video. Hope you enjoy!
using System; using Gtk; using System.Diagnostics; using System.Text.RegularExpressions; public partial class MainWindow: Gtk.Window { string Users_Home = Environment.GetEnvironmentVariable( "HOME" ); public int runCommand( string command, string args, bool wait ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start() ) { if( wait == true ) { proc.WaitForExit( ); return proc.ExitCode; } else { return proc.ExitCode; } } return -1; } public void runCommand( string command, string args, bool wait, int milliseconds ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start() ) { if( wait == true ) if( milliseconds > 0 ) proc.WaitForExit( milliseconds ); else proc.WaitForExit( ); else proc.Close( ); } } public string getOutput( string command, string args, bool wait ) { Process proc = new Process( ); proc.StartInfo.FileName = command; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if( proc.Start( ) ) { if( wait == true ) { proc.WaitForExit( ); string output = proc.StandardOutput.ReadToEnd( ).TrimEnd( ); string error = proc.StandardError.ReadToEnd( ).TrimEnd( ); if( output.Equals( "" ) || output.Equals( " " ) ) { return error; } else return output; } else { string output = proc.StandardOutput.ReadToEnd( ).TrimEnd( ); string error = proc.StandardError.ReadToEnd( ).TrimEnd( ); if( output.Equals( "" ) || output.Equals( " " ) ) { return error; } else return output; } } else return "Could not start process. Check process file name."; } public string getCommand( string command_name ) { return getOutput( "which", command_name, false ); } public void UpdateMountList( ) { runCommand( "sh", "-c \"mount -l | grep -i \"" + Users_Home + "/.GtkMountISO\" | cut -d ' ' -f3 > " + Users_Home + "/.GtkMountISO/mounts.current\"", true ); int ln_count = 0; string cur_line = ""; System.IO.StreamReader file = new System.IO.StreamReader( Users_Home + "/.GtkMountISO/mounts.current" ); while( ( cur_line = file.ReadLine( ) ) != null ) { CurrentMounts.AppendText( cur_line ); ln_count++; } file.Close( ); CurrentMounts.RemoveText( ln_count ); } public MainWindow (): base (Gtk.WindowType.Toplevel) { Build (); if( !( System.IO.Directory.Exists( Users_Home + "/.GtkMountISO" ) ) ) { //If hidden GtkMountISO folder does not exist, create dir string mkdir = getCommand( "mkdir" ); Console.WriteLine( "GtkMountISO folder does not exist. Creating." ); int retval = runCommand( mkdir, Users_Home + "/.GtkMountISO", true ); if( retval == 0 ) { Console.WriteLine( "Created directory for GtkMountISO" ); } } else { UpdateMountList( ); } } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { int rm_retval = runCommand( "rm", Users_Home + "/.GtkMountISO/mounts.current", true ); Console.WriteLine( "Del retval = " + rm_retval ); Application.Quit (); a.RetVal = true; } protected virtual void OnMountISOClicked (object sender, System.EventArgs e) { string zenity = getCommand( "zenity" ); string xterm = getCommand( "xterm" ); string echo = getCommand( "echo" ); string sleep = getCommand( "sleep" ); try { /* * 1.) Get Filename */ //Get Full file name string ISO_Name = SelectISOButton.Filename.ToString( ); Regex r = new Regex( @"\s+" ); string ISO_Name_Regex = r.Replace( ISO_Name, @"\\ " ); //Split it based on slashes string[] ISO_Name_Parts = ISO_Name.Split( '/' ); //Get length to subtract one and get single file name int Parts_num = ISO_Name_Parts.Length; string ISO_Parsed_Name = ISO_Name_Parts[ Parts_num - 1 ]; //Split string again based on "." to get standalone file name with no extension string[] ISO_Strip_Extension = ISO_Parsed_Name.Split( '.' ); int ISO_Parsed_Num = ISO_Strip_Extension.Length; string ISO_Cleaned_Name = ISO_Strip_Extension[ ISO_Parsed_Num - 2 ]; string iso_extension = ISO_Strip_Extension[ ISO_Parsed_Num - 1 ]; Console.WriteLine( "Extension = " + iso_extension ); if( iso_extension.Equals( "iso" ) || iso_extension.Equals( "ISO" ) ) { Console.WriteLine( "Cleaned Name = " + ISO_Cleaned_Name ); /* * 2.) Make folder name @ /_USERS_HOME_DIR_/_FILE_NAME_ */ string Users_Home = Environment.GetEnvironmentVariable( "HOME" ); Console.WriteLine( Users_Home ); string mkdir = getCommand( "mkdir" ); string make_dir_cmd = mkdir + " " + Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name; Console.WriteLine( make_dir_cmd ); int make_dir = runCommand( mkdir, Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name, true ); string mount_point = Users_Home + "/.GtkMountISO/" + ISO_Cleaned_Name; int zenity_retval = -1; if( make_dir != 0 ) { zenity_retval = runCommand( zenity, "--question --text=\"Folder exists. Would you like to mount anyway?\"", true ); Console.WriteLine( "Zenity reval = " + zenity_retval ); } if( ( make_dir == 0 ) || ( make_dir != 0 && zenity_retval == 0 ) ) { Console.WriteLine( "Folder created" ); /* * 3.) Execute "mount -t iso9660 _FULL_FILE_NAME_ /_USERS_HOME_DIR_/_FILE_NAME_ -o loop */ string gksudo = getCommand( "gksudo" ); string mount = getCommand( "mount" ); Console.WriteLine( "ISO_Name = " + ISO_Name ); Console.WriteLine( "Mount_Point = " + mount_point ); //Need to some how account for white space without corrupting the commands sent to the system... int retval = runCommand( gksudo, "\"" + mount + " -t iso9660 " + ISO_Name_Regex + " " + mount_point + " -o loop\"", true ); Console.WriteLine( " Mount Retval = " + retval ); if( retval == 0 || retval == 1 ) { //Success if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Success! && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--info --title=\"Success\" --text=\"Success!\n\n You can find the ISO mounted at " + mount_point + "\"", true, 0 ); string nautilus = getCommand( "nautilus" ); if( nautilus.Equals( "" ) ) return; else runCommand( nautilus, "\"" + mount_point + "\"", false, 0 ); } else if( retval == 7 ) { //Mount Failure if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Failed to mount. Is the file an actual ISO? && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Failed to mount. Is the file an actual ISO?\"", true, 0 ); } else if( retval == 32 ) { //Mount Failure if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " Failed to mount. Is there already something mounted there? && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Failed to mount. Is there already something mounted there?\"", true, 0 ); } /* * 4.) Add to flat file database of mounted folders */ UpdateMountList( ); } } else { if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " File is not an ISO image && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"You must select an ISO image file\"", true, 0 ); } } catch( NullReferenceException nullexception ) { string error = nullexception.ToString( ); if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " You must select a file first && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--error --title=\"error\" --text=\"Error Thrown: \n\n" + error + "\n\nYou must select a file first\"", true, 0 ); Console.WriteLine( error ); } } protected virtual void OnUnMountISOClicked (object sender, System.EventArgs e) { Console.WriteLine( "Unmounting " + CurrentMounts.ActiveText ); string zenity = getCommand( "zenity" ); string xterm = getCommand( "xterm" ); string echo = getCommand( "echo" ); string sleep = getCommand( "sleep" ); string gksudo = getCommand( "gksudo" ); string umount = getCommand( "umount" ); string iso_to_unmount = CurrentMounts.ActiveText; int umount_retval = runCommand( gksudo, "\"" + umount + " -f " + iso_to_unmount + "\"", true ); Console.WriteLine( "Umount retval = " + umount_retval ); if( umount_retval == 0 ) { if( zenity.Equals( "" ) ) { runCommand( xterm, "-e \"" + echo + " File successfully unmounted && " + sleep + " 5\"", true, 0 ); } else runCommand( zenity, "--info --title=\"error\" --text=\"File successfully unmounted!\"", true, 0 ); } UpdateMountList( ); } }
[PHP]Sort Files by Modification Date
by Chuck Kozler on Aug.20, 2009, under Home, Programming
Hi everyone,
I have needed this for some time now to organize photos by the most recent added into a folder for a clients website. Ill just give the code and give you an example (explained example) as to how I used it.
First, the client has a folder with all the images and I wanted to display the most recent added picture as the display picture for the album as well as have them sorted by most recent added into the folder. So, we have a folder with all the images, in this case there were about 27 images in the folder.
First of all, with this code, you will need to have already traversed the folder and stored all the files in an array. Whether you use array_push or just store it in a C style fashion, either way works. You still need to have them stored in an array. Then, you will need a second array to store the output to it. Remember, this is following my example so I will include almost all the code that it took for me to accomplish this Lets have a look:
// Image files array $image_files = array( ); // Array to store the images that were sorted $image_sorted = array( ); // Read the extension of the file name passed function readExtension( $file ) { $extension = substr( $file, strrpos( $file, '.' ) + 1 ); return $extension; } // This may already exist but I was in a coding frenzy. Obviously, this checks if it is an image or not function isImage( $file ) { $extension = readExtension( $file ); $valid_images = array( "gif", "jpg", "jpeg", "png", "gif" ); for( $i = 0; $i < sizeof( $valid_images ); $i++ ) { if( $extension == $valid_images[ $i ] ) { return true; } } } // Traverse the directory and get all the images in that folder function getImagesInFolder( $dir ) { if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumbs.db" ) { if( !( is_dir( $dir . $file ) ) ) { $file_fp = $dir . $file; if( isImage( $file_fp ) ) array_push( $GLOBALS['image_files'], $file_fp ); } } } closedir( $handle ); } } //The brunt of the post. Explained below in more detail function sortByModDate( $array_in, &$array_out ) { for( $i = 0; $i < sizeof( $array_in ); $i++ ) { $time_stamp = date("G:i:s-d-m-y", filemtime( $array_in[ $i ] ) ); $array_out[ $array_in[ $i ] ] = $time_stamp; } arsort( $array_out, SORT_STRING ); $array_out = array_keys( $array_out ); if( $array_out[ 0 ] == "0" ) array_shift( $array_out ); unset( $array_in ); } // Get the sorted file by index number. This seems a bit redundant so you can modify as you see fit. function getSortedImageByIdx( $index_num ) { sortByModDate( $GLOBALS['image_files'], $GLOBALS['image_sorted'] ); return $GLOBALS[ '{image_sorted[ $index_num ]}' ]; }
Lets dissect code behind the basis of this post:
// $array_in = Array of all the files you want to sort // $array_out = Array to store the sorted files function sortByModDate( $array_in, &$array_out ) {
// Loop through all the inputted files array for( $i = 0; $i < sizeof( $array_in ); $i++ ) {
// Receive the time stamp $time_stamp = date("G:i:s-d-m-y", filemtime( $array_in[ $i ] ) );
// Store the time stamp in the $array_out array using the file name as a key // // NOTE: This had to be done this way since you can not have duplicate keys. // If you have a file edited at the EXACT same time as another file, that file // will therefore be dropped from the sorting $array_out[ $array_in[ $i ] ] = $time_stamp; }
// Sort and reverse the array based on the string. This allows for you to reference the // most recent file by accessing index array 0 arsort( $array_out, SORT_STRING );
// Break the keys from the above sorted array which allows us to access the sorted files // in a numerical sense (see example use below) $array_out = array_keys( $array_out );
// Couldnt really figure out why an extra iteration was being done but sometimes it will // create a zero index with a zero in it. This shifts the array and removes that zero if( $array_out[ 0 ] == "0" ) array_shift( $array_out );
// Free-up some resources unset( $array_in ); }
And here is an example use:
echo "Most recent file: " . getSortedImageByIdx( 0 ) . "<br>";
Also, this was originally in a class and I made some edits here during the post so some stuff may not be directly copy and paste. Adjust accordingly.
Sphere: Related Content[PHP]Directory Listing v1.1 Beta
by Chuck Kozler on Aug.07, 2009, under Home, Programming
Hi everyone,
This is the second version of the PHP Directory Listing that is posted directly beneath this one. This one is a little better and coded a lot better in my opinion. Though heavy code changes will come in the final versions to make sure everything is cleaned and secure, this one is definitely better than the last.
Some changes are:
1.) Removed the download rar/tar/zip functionality for now until I can figure out the best/cleanest way to implement it
2.) BIG: The directory listing is now completely recursive. What does this mean? This means that instead of having to copy an index.php file to every single directory that you want a directory list in, you just have to copy the first one and it will scan through all directories and store them in memory. You can see a screenshot below for more details.
3.) Images are now used more dynamically based on the file type. Supported file types are most movie and audio formats as well as archives and images.
I think that covers most of the changes.
The recursive directories function just implements programming recursion and calls the directory traversal function over and over again until its done reaching directories.
dir_list.class.php – The heart of the directory listing. You can see an example of how to use this on an index.php below
<?php class cDirList { public $path; public $debug; function debugPrint( $text ) { echo "// " . $text . "<br>"; } //All directories recursively from current working directory, full path location public $directories = array( ); //Directories in current working directory, full path location public $pwd_directories = array( ); //Files full path location public $files = array( ); public $file_types = array( "archive" => array( "7z", "zip", "rar", "tar", "gzip" ), "audio" => array( "mp3", "ogg", "wma", "flac", "aif", "ra" ), "video" => array( "avi", "wmv", "mpg", "mpeg", "asf", "mkv", "flv", "mov" ), "doc" => array( "doc", "docx", "log", "msg", "ods", "m3u" ), "code" => array( "cpp", "c", "sh", "py", "php" ), "image" => array( "jpg", "png", "jpeg", "gif" ), "program" => array( "exe" ) ); function getArraySize( $array ) { return sizeof( $array ); } function getFinalIndex( $array ) { return sizeof( $array ) - 1; } function getDirAtIndex( $dir_array, $idx ) { return $dir_array[ $idx ]; } function getDirIndex( $dir_array, $dir_name ) { return array_search( $dir_name, $dir_array ); } function printArray( $array ) { print_r( $array ); } function crawlDirectories( $dir ) { if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumb.db" ) { if( is_dir( $dir . $file ) ) { //Store directories in array $dir_fp = $dir . $file; array_push( $this->directories, $dir_fp ); //Recursion, duh! So simple.... $this->crawlDirectories( $dir . $file . "/" ); } } } closedir( $handle ); } } function getFoldersInCwd( $dir ) { $dir = $this->correctPath( $dir ); if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumb.db" ) { if( is_dir( $dir . $file ) ) { //Store directories in array $dir_fp = $dir . $file; array_push( $this->pwd_directories, $dir_fp ); } } } closedir( $handle ); } } function getFilesInFolder( $dir ) { $dir = $this->correctPath( $dir ); if( $handle = opendir( $dir ) ) { while( false !== ( $file = readdir( $handle ) ) ) { if( $file != "." && $file != ".." && $file != "Thumbs.db" ) { if( !( is_dir( $dir . $file ) ) ) { $file_fp = $dir . $file; //$this->files[$index_num] = $file_fp; array_push( $this->files, $file_fp ); } } } closedir( $handle ); } } function getSingleName( $full_path ) { $full_path_explode = explode( "/", $full_path ); $full_path_final_idx = $this->getFinalIndex( $full_path_explode ); return $full_path_explode[ $full_path_final_idx ]; } function correctPath( $path ) { $path_explode = explode( "/", $path ); $path_final_idx = $this->getFinalIndex( $path_explode ); if( $path_explode[ $path_final_idx ] == null ) return $path; else { $path .= "/"; return $path; } } function getRelativePath( $path ) { $path = str_replace( $_SERVER['DOCUMENT_ROOT'], "", $path ); return $path; } function getFileType( $file ) { $type = substr( $file, strrpos( $file, '.' ) + 1 ); return $type; } function handleFileType( $file ) { $file = strtolower( $file ); $got_type = 0; $in_file_type = ""; foreach( $this->file_types as $type => $key ) { foreach( $key as $ext ) { //$this->debugPrint( "Extensions: " . $ext ); if( $this->getFileType( $file ) == $ext ) { $in_file_type = $type; $got_type = 1; } } if( $got_type > 0 ) break; } if( $in_file_type == "archive" ) return "<img src='images/archives.png'/>"; else if( $in_file_type == "image" ) return "<img src='images/images.png'/>"; else if( $in_file_type == "video" ) return "<img src='images/videos.png'/>"; else if( $in_file_type == "doc" ) return "<img src='images/docs.png'/>"; else if( $in_file_type == "code" ) return "<img src='images/code.png'/>"; else if( $in_file_type == "program" ) return "<img src='images/programs.png'/>"; else if( $in_file_type == "audio" ) return "<img src='images/audio.png'/>"; else if( $got_type == 0 && $in_file_type == "" ) return "<img src='images/unknown.gif' height='16px' width='16px'/>"; } function getScriptRootDir( ) { $script_name = explode( "/", $_SERVER['SCRIPT_NAME'] ); $filename = $script_name[ sizeof( $script_name )-1 ]; return str_replace( $filename, "", $_SERVER['SCRIPT_FILENAME'] ); } function __construct( ) { $this->path = $this->getScriptRootDir(); $this->crawlDirectories( $this->path ); sort( $this->directories ); sort( $this->pwd_directories ); } }; ?>
Index.php
<?php require_once( 'dir_list.php' ); $dirlist = new cDirList( ); $dir = $dirlist->getScriptRootDir(); $dirlist->getFoldersInCwd( $dir ); echo "<font size='9' face='Verdana'>" . $dirlist->getRelativePath( $dir ) . "</font><br>\n" . "<font size='1' face='Sans MS'>" . $dirlist->path . "</font><br>\n<br>\n"; if( $dirlist->getArraySize( $dirlist->directories ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->pwd_directories ); $i++ ) { echo "<img src='images/folders.png'/>" . "<font size='2'> " . "<a href='do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "'>" . $dirlist->getSingleName( $dirlist->pwd_directories[$i] ) . "</a><br>\n" . "</font>"; echo "      " . "<font size='1'>" . "http://" . $_SERVER['SERVER_NAME'] . "/do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "<br>\n" . "</font>"; } } else { echo "<img src='images/nothing.gif' />" . "<font size='2'>  " . "No folders found" . "</font>" . "<br>\n"; } $dirlist->getFilesInFolder( $dir ); if( $dirlist->getArraySize( $dirlist->files ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->files ); $i++ ) { echo $dirlist->handleFileType( $dirlist->getSingleName( $dirlist->files[ $i ] ) ) . "<font size='2'><a href='" . $dirlist->getRelativePath( $dir ) . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "'>" . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "</a></font><br>\n"; } } else { echo "<img src='images/nothing.gif' />" . " <font size='2'>" . "No files found" . "</font>" . "<br>\n"; } ?>
do_list.php – List the files and/or folders in the current directory
<?php require( 'dir_list.php' ); $dirlist = new cDirList( ); //Get directory name based on GET index name $index_number = $_GET['id']; $dir = $dirlist->getDirAtIndex( $dirlist->directories, $index_number ); $dirlist->getFoldersInCwd( $dir ); echo "<font size='9' face='Verdana'>" . $dirlist->getRelativePath( $dir ) . "</font><br>\n" . "<font size='1' face='Sans MS'>" . $dirlist->path . "</font><br>\n<br>\n"; function checkId( $id ) { if( $id < 0 || $id > $GLOBALS['dirlist']->getArraySize( $GLOBALS['dirlist']->directories ) ) return; } checkId( $index_number ); if( $dirlist->getArraySize( $dirlist->pwd_directories ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->pwd_directories ); $i++ ) { echo "<img src='images/folders.png'/>" . "<font size='2'> " . "<a href='do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "'>" . $dirlist->getSingleName( $dirlist->pwd_directories[$i] ) . "</a><br>\n" . "</font>"; echo "      " . "<font size='1'>" . "http://" . $_SERVER['SERVER_NAME'] . "/do_list.php?id=" . $dirlist->getDirIndex( $dirlist->directories, $dirlist->pwd_directories[$i] ) . "<br>\n" . "</font>"; } echo "<br>\n"; } else { echo "<img src='images/nothing.gif' />" . " <font size='2'>" . "No folders found" . "</font>" . "<br>\n<br>\n"; } $dirlist->getFilesInFolder( $dir ); if( $dirlist->getArraySize( $dirlist->files ) > 0 ) { for( $i = 0; $i < $dirlist->getArraySize( $dirlist->files ); $i++ ) { echo $dirlist->handleFileType( $dirlist->getSingleName( $dirlist->files[ $i ] ) ) . "<font size='2'><a href='" . $dirlist->getRelativePath( $dir ) . "/" . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "'>" . $dirlist->getSingleName( $dirlist->files[ $i ] ) . "</a></font><br>\n"; } } else { echo "<img src='images/nothing.gif' />" . " <font size='2'>" . "No files found" . "</font>" . "<br>\n"; } ?>
You can see some screenshots below of it in use.
1st screenshot shows the directory listing from the first index page. As you can see the numbers skip increments rather than being 1 at a time, this is because it has hit folders that have folders inside of them and then increments the ID number based on the directories found. The second screenshot shows the difference of images between different types of files. The third screenshot shows folders inside of a folder and how they are incremented accordingly (see screenshot 1 as well). The fourth screenshot shows you another directory listing and also shows how the script can go very deep through files and traverse all directories from a root directory.
- Dir_List_new
[PHP]Directory Listing v1 BETA
by Chuck Kozler on Jul.10, 2009, under Home, Programming
Hi everyone,
I hated the Apache and Lighttpd directory listings, so, I have made this. This was brought about because my roomates would always want to download some stuff from me, whether it was documents for projects, some song I was listening to, or a movie. With Apache and Lighttpd you are unable to download a whole directory but can download individual files. This seemed a little backwards to me since someone could easily traverse the directories themselves and download each file. Rather, this script will allow them click a button in a directory that will tar/rar the entire directory and then produce a download link for them.
This is currently in heavy beta, pretty much alpha, as the code below is going through heavy rewrites. Currently right now it:
1.) Caches all the files in the current directory
2.) Stores them in an array for indexing
3.) Sends a GET request with the ID (in the array) of the file
4.) When the user is at the do_download.php file, they are prompted with a download button to download the entire directory, or if they so choose, download an individual file
5.) If the user clicks the download button the script rar’s the entire directory and then produces a download link *Read Note*
6.) Once the rar/zip is complete, they are prompted with a download link
This currently has minimal security by only checking the ID and make sure it isnt out of bounds (too high or too low). I have provided the class of the directory listing as well as an example for an index.php page. The do_download.php is where the listing of the current directory is done as well providing the user a button to download the entire directory:
This is so alpha/beta that I am considering it more of a POC (proof-of-concept) for now until I have time to make it better and dynamic.
directory-list.class.php
<?php class dirlist { private $directory_path; private $folder_names = array( ); private $file_names = array( ); private $folder_full_paths = array( ); private $file_full_paths = array( ); private $dir_handle; function setDirHandle( $path ) { $this->dir_handle = opendir( $path ) or die( "Could not open directory." ); } function array_get_real_size( $array_in ) { $size = 0; if( sizeof( $array_in ) == 0 ) return 0; foreach( $array_in as $a ) { $size += sizeof( $a ); } return $size; } function print_array( $array_in ) { //All this does is echos pre tags and executes print_r. If I leave this here, my website breaks my code. } function getDirList( ) { $path = $this->directory_path; $this->setDirHandle( $path ); $dir_count = 0; $file_count = 0; while( false != ( $file = readdir( $this->dir_handle ) ) ) { if( $file == "." || $file == ".." ) continue; if( is_dir( $path . $file ) ) { $this->folder_names[ $dir_count ] = $file; $this->folder_full_paths[ $file ] = $path . $file; $dir_count++; } else { $this->file_names[ $file_count ] = $file; $this->file_full_paths[ $file ] = $path . $file; $file_count++; } } //$this->print_array( $this->file_full_paths ); //$this->print_array( $this->folder_full_paths ); return true; } function getFolderFp( $folder_name ) { return $this->folder_full_paths[ $folder_name ]; } function getFolderName( $index_number ) { return $this->folder_names[ $index_number ]; } function getTotalFolders( ) { return $this->array_get_real_size( $this->folder_full_paths ); } function getFileFp( $file_name ) { return $this->file_full_paths[ $file_name ]; } function getFileName( $index_number ) { return $this->file_names[ $index_number ]; } function getTotalFiles( ) { return $this->array_get_real_size( $this->file_full_paths ); } function getSortedFolderFp( $index_number ) { $sorted_folders = $this->folder_full_paths; sort( $sorted_folders, SORT_STRING ); return $sorted_folders[ $index_number ]; } function getSortedFolderName( $index_number ) { $sorted_folders = $this->folder_names; sort( $sorted_folders, SORT_STRING ); return $sorted_folders[ $index_number ]; } function getCurDir( ) { $tmp = $this->directory_path; $tmp_explode = explode( "/", $tmp ); $res = $tmp_explode[ sizeof( $tmp_explode ) - 2 ] . "/"; return $res; } function getCorrectedPath( ) { return $this->directory_path; } function correctPath( $path ) { $tmp = $path; $tmp_explode = explode( "/", $tmp ); $tmp_size = sizeof( $tmp_explode ); if( $tmp_explode[ $tmp_size - 1 ] == null ) { $this->directory_path = $path; return; } else { $this->directory_path = $path . "/"; return; } } function generateDownloadLink( $export_dir, $file_name ) { // make http://10.14.52.30/$dir->getcurdir()/$foldername $host = $_SERVER['SERVER_NAME']; $script_filename = basename( $_SERVER['SCRIPT_FILENAME'] ); $cur_path = preg_replace( '/'.$script_filename.'/','', $_SERVER['SCRIPT_NAME'] ); $link = "http://" . $host . $cur_path . $export_dir . $file_name; return $link; } function generateAHrefLink( ) { $host = $_SERVER['SERVER_NAME']; $script_filename = basename( $_SERVER['SCRIPT_FILENAME'] ); $cur_path = preg_replace( '/'.$script_filename.'/','', $_SERVER['SCRIPT_NAME'] ); $link = "http://" . $host . $cur_path; return $link; } function getPwd( ) { } function __construct( $path ) { $this->correctPath( $path ); } }; ?>
Index.php
<?php require_once( 'directory_list.class.php' ); $dir = new dirlist( "/var/www/music" ); $dir->getDirList( ); echo "<p align='left'>\n"; echo "<font size='+9' face='Verdana'>\n"; echo $dir->getCurDir() . "<br>\n"; echo "</font>\n"; echo "<font size='1' face='Sans MS'>\n"; echo $dir->getCorrectedPath( ) . "<br>\n"; echo "</font>\n"; echo "</p>\n"; echo "<font size='2'>\n"; for( $i = 0; $i < $dir->getTotalFolders( ); $i++ ) { $link = $dir->generateAHrefLink() . "do_download.php?id=" . $i; echo "   " . "<img src='http://10.14.52.30/images/folder.png'>" . "<a href='$link'>".$dir->getSortedFolderName($i)."</a><br>"; echo $link . "<br><br>"; } echo "</font>\n"; ?>
This needs heavy rewriting:
do_download.php
<?php $export_dir = "export/"; $export_dir_tmp = $export_dir; require_once( 'directory_list.class.php' ); function checkValidFileId( $id, $max_value, $min ) { // Out of bounds. Negative attempt or over max attempt if( ( $id < $min ) || ( $id > $max_value ) ) return false; else return true; } function getPwd( $in_path ) { $pwd = preg_replace( '/'.basename( $_SERVER['SCRIPT_FILENAME'] ).'/', '', $in_path ); return $pwd; } $dir = new dirlist( "/var/www/music" ); $dir->getDirList( ); $id = $_GET['id']; $pwd = getPwd( $_SERVER[ 'SCRIPT_FILENAME' ] ); $export_dir = $pwd . $export_dir; echo "<p align='left'>\n"; echo "<font size='+9' face='Verdana'>\n"; echo $dir->getCurDir() . $dir->getSortedFolderName( $id ) . "<br>\n"; echo "</font>\n"; echo "<font size='1' face='Sans MS'>\n"; echo $dir->getCorrectedPath( ) . $dir->getSortedFolderName( $id ) . "<br>\n"; echo "</font>\n"; echo "</p>\n"; echo "<font size='3' face='Times'>"; echo "You have requested the directory: <br>     " . $dir->getSortedFolderName( $id ) . "<br>\n"; echo "<br>Click below to download<br>"; //- Create filename $filename = preg_replace( '/\s/', '_', $dir->getSortedFolderName( $id ) ); echo "</font>"; echo "<form action='" . basename( $_SERVER['SCRIPT_FILENAME'] ) . "?id=$id' method='post'>"; echo "<select name='format'>"; echo "<option value='zip'>Zip Archive</option>"; echo "<option value='rar'>Rar Archive</option>"; echo "<option value='tar'>Tar Archive</option>"; echo "<option value='gzip'>GZip Archive</option>"; echo "<input type='submit' name='Download' value='Download'>"; echo "</form>"; $inner_dir = new dirlist( $dir->getCorrectedPath( ) . $dir->getSortedFolderName( $id ) ); $inner_dir->getDirList( ); echo "Inner Path: " . $inner_dir->getCorrectedPath() . "<br>"; echo "Files: " . $inner_dir->getTotalFiles() . "<br>"; echo "<font face='Times' size='2'>"; for( $i = 0; $i < $inner_dir->getTotalFiles(); $i++ ) { echo "<a href='../../music/".$inner_dir->getCurDir() . $inner_dir->getFileName( $i )."'>".$inner_dir->getFileName($i)."</a><br>"; } for( $i = 0; $i < $inner_dir->getTotalFolders(); $i++ ) { echo "<a href='../../music/".$inner_dir->getCurDir() . $inner_dir->getFolderName( $i )."'>".$inner_dir->getFolderName($i)."</a><br>"; } echo "</font>"; if( $_POST['Download'] ) { switch( $_POST['format'] ) { case "zip": if( checkValidFileId( $id, $dir->getTotalFolders(), 0 ) ) { $export_filename = $filename . ".zip"; $export_fullpath = "\"".$export_dir . $export_filename."\""; $export_files_in = "\"".$dir->getSortedFolderFp( $id )."\""; $zip_executable = exec( 'which zip' ); $command = $zip_executable . " -r " . $export_fullpath . " " . $export_files_in; system( "echo Please wait while your file is processed" ); echo "<br>"; echo "<br>"; $export_fullpath = preg_replace( '/"/', '', $export_fullpath ); if( file_exists( $export_fullpath ) ) { //echo $dir->getHostPath() . "<br>"; echo "Your processing is complete: <a href='" . $dir->generateDownloadLink( $export_dir_tmp, $export_filename ). "'>$export_filename</a>"; exit; } if( is_writable( $export_dir ) ) { system( $command ) or die( "What" ); $export_fullpath = preg_replace( '/"/', '', $export_fullpath ); if( file_exists( $export_fullpath ) ) { echo "<br><br>"; echo "Your processing is complete: <a href='" . $dir->generateDownloadLink( $export_dir_tmp, $export_filename ). "'>$export_filename</a>"; exit; } } } else echo "You have tried to download an invalid file. Please try again." . "<br><br>"; break; case "rar": echo "We are rarring it" . "<br>"; break; case "tar": echo "We are tarring it" . "<br>"; break; case "gzip": echo "We are gzipping it" . "<br>"; break; default: break; } } //echo "Export dir: " . $export_dir . "<br>"; ?>
Some updates that will come:
A total of only three files needed: 1 for the class, 1 for the index, and 1 for the download. The next directory list class will traverse all of the directories from the current working path, recursively, allowing for a much wider dynamic behind this entire concept. So far, for me, doing this and keeping it organized is proving a little tricky.
Screenshots:
[Mono/Linux] C# Shell Commands
by Chuck Kozler on Mar.24, 2009, under Computers, Home, Linux/Unix, Programming, Windows
These are some functions I have wrote recently for more or less debugging purposes. I use these functions to execute shell commands via C#. I am in no way a professional programmer so my code may seem sloppy, redundant, or plain useless to some. Thank you, but, please keep those comments to yourself.
What the function does is pretty much explained in the function definitions.
public string logfile = "debug.log"; public void writelog( string logfile, string message ) { string datetime = System.DateTime.Now.ToString(); if( !File.Exists( logfile ) ) runshellcmd( "touch " + logfile ); StreamWriter file = new StreamWriter( logfile, true ); file.WriteLine( "[ " + datetime + " ]:\n" + message + "\n" ); file.Close( ); } public int runshellcmd( string cmd ) { string[] parts = cmd.Split( ' ' ); string cmd_name = parts[ 0 ]; string arguments = ""; if( parts.Length > 1 ) for( int i = 1; i < parts.Length; i++ ) arguments += " " + parts[ i ]; Process proc = new Process( ); proc.StartInfo.FileName = cmd_name; proc.StartInfo.Arguments = arguments; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; try { if( proc.Start( ) ) { proc.WaitForExit( ); return proc.ExitCode; } else return proc.ExitCode; } catch( System.ComponentModel.Win32Exception w32e ) { writelog( logfile, w32e.Message.ToString( ) ); return proc.ExitCode; } } public string getoutput( string cmd ) { string[] parts = cmd.Split( ' ' ); string cmd_name = parts[ 0 ]; string arguments = ""; if( parts.Length > 1 ){ for( int i = 1; i < parts.Length; i++ ){ arguments += " " + parts[ i ]; } } Process proc = new Process( ); proc.StartInfo.FileName = cmd_name; proc.StartInfo.Arguments = arguments; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; try { if( proc.Start( ) ) { proc.WaitForExit( ); string output = proc.StandardOutput.ReadToEnd().TrimEnd(); string error = proc.StandardError.ReadToEnd().TrimEnd(); if( output.Equals( "" ) || output.Equals( " " ) ) return error; else return output; } } catch( System.ComponentModel.Win32Exception w32e ) { string ret = "Error Thrown: " + w32e.ToString( ); return ret; } return "Broke"; } public bool pipeoutput( string ofile, string cmd ) { StreamWriter file = new StreamWriter( ofile ); try { file.WriteLine( getoutput( cmd ) ); file.Close( ); return true; } catch( System.IO.FileNotFoundException notfound ) { writelog( logfile, notfound.Message.ToString( ) ); return false; } } public string getexitcode( string cmd ) { return runshellcmd( cmd ).ToString(); } public string pwd( ) { string ret = getoutput( "pwd" ); return ret; } public bool killbypid( int pid ) { if( runshellcmd( "kill -9 " + pid ) == 0 ) return true; else return false; } public bool killbyname( string procname ) { //This should actually be "killall -9 + procname", I placed mono in the front because I was killing my own process. Remove to kill other processes by name if( runshellcmd( "killall -9 mono " + procname ) == 0 ) return true; else return false; } public string mygrep( string cmd_to_pipe, string text_to_search ) { string output = ""; //Check if the file exists if( File.Exists( "grep_tmp" ) ) runshellcmd( "rm grep_tmp" ); //Pipe output to a temp file if( pipeoutput( "grep_tmp", cmd_to_pipe) ) { //Set the out variable to the output of the command output = getoutput( "grep -i " + text_to_search + " grep_tmp" ); //Delete the file if( runshellcmd( "rm grep_tmp" ) == 0 ) { //Return the results return output; } } return ""; }
These are some example uses. Stuff I used when debugging.
//Delete the logfile to just make sure I was viewing the most current stuff runshellcmd( "rm " + logfile ); //get workingdir by running the pwd command and returning the output (see pwd() function) string workingdir = pwd( ); //Get processID int procid = System.Diagnostics.Process.GetCurrentProcess().Id; //Get processname string procname = System.Diagnostics.Process.GetCurrentProcess().ProcessName; writelog( logfile, "Working Dir: " + workingdir ); writelog( logfile, "Process ID: " + procid ); writelog( logfile, "Process Name: " + procname ); //We want to search for "process" after we pipe the output from debug.log string tmp = mygrep( "cat debug.log", "process" ); writelog( logfile, "Grep Results:\n" + tmp ); textview1.Buffer.Text = getoutput( "cat debug.log" ); //Kill our process by PID killbypid( procid ); //Kill by our process name killbyname( procname );
[PHP]Deny by Host/Hostname
by Chuck Kozler on Mar.16, 2009, under Computers, Networks/Servers, Programming
Well, it seems my Wordpress blog here is getting slammed with Russian spambots lately. My hoster has not gotten back to me yet if they can block a host for me (Henrik!
), so, I decided to write this up.
The comments in the code explain it pretty well
<?php //Get remote host $_get_addr = $_SERVER['REMOTE_ADDR']; //Get the host from the address $_get_host = gethostbyaddr( $_get_addr ); //Ban list array. The text before => is a key name and //after the => is the host you want to ban. This allows //for aliasing your problematic hostnames $_config_hostbanlist = array( russia1 => "nn-88-237.nm-s.ru" ); /* Ban by full hostname. The list is populated by the hostbanlist array. Simply it just compares their host with an entry in the hostbanlist array */ function isHostBanned( $host, $_ban_list ) { //Iterate each entry in the banned list array foreach( $_ban_list as $entry ) { //If we get a match, return true (the host is banned) if( strtolower( $host ) == strtolower( $entry ) ) return true; } return false; } /* This will ban by IP. This list is populated dynamically by the hostbanlist variable. It then resolves IP's for each hostname in the list and then checks it. */ function isIPBanned( $_remote_addr, $_ban_list ) { foreach( $_ban_list as $entry ) { $entry_ip = gethostbyname( strtolower( $entry ) ); if( $_remote_addr == $entry_ip ) return true; } return false; } function doAlert( $alert ) { echo "<script language='JavaScript'>window.alert( \"$alert\" )</script>"; } /* We will be checking for true/false of isIPBanned first since the IP banned list is populated by the $_config_hostbanlist array and isIPBanned resolves the hostname to an IP. Then, if that fails, it also then checks the hostname and compares to the list again via hostname. Flow: isIPBanned? -> loop hostbanlist -> resolve IP for given loop iteration -> check IP resolved to REMOTE_ADDR -> Match? => Banned -> No Match? => Not in that list, assume they are either not in the list or their IP could not be resolved. Go to isHostBanned function to ensure they are not in the list isHostBanned -> loop hostbanlist -> check if their host is equal to an entry in the array -> Match? => Banned -> No match? => Not banned */ if( isIPBanned( $_get_addr, $_config_hostbanlist ) || isHostBanned( $_get_host, $_config_hostbanlist ) ) { doAlert( "You are banned" ); echo "<br><br><br><p align='center'>Your host [$_get_host] and/or IP [$_get_addr] has been banned. <br> Please contact <a href='mailto:webmaster@ckozler.net'>webmaster@ckozler.net</a> if you feel you have reached this page in error</p>" . "<br>"; exit; } ?>
When you use this, all you need to do is copy and paste this into a file and then in each file you want to ban the host from, you do:
require('hostblock.php');
Of course, the example above assumes you name the file hostblock.php
Sphere: Related Content[Linux/Mono]C#: Execute Shell Commands (function)
by Chuck Kozler on Feb.14, 2009, under Computers, Linux/Unix, Programming, Ubuntu, Windows
Hi everyone,
This is a short function I wrote to execute a shell command in C#. This needs to be used with Mono on Linux but should run natively on Windows.
protected virtual bool RunCommand( string szCmd, string szArgs, int wait ) { if( szCmd == null ) return false; System.Diagnostics.Process myproc = new System.Diagnostics.Process( ); myproc.EnableRaisingEvents = false; myproc.StartInfo.FileName = szCmd; myproc.StartInfo.Arguments = szArgs; if( myproc.Start( ) ) { //Using WaitForExit( ) allows for the host program //to wait for the command its executing before it continues if( wait == 1 ) myproc.WaitForExit( ); else myproc.Close( ); return true; } else return false; }
If you’re viewing this page then this is pretty self explanatory.
Called as such:
if( RunCommand( "/usr/bin/zenity", "--warning", 0 ) ) Console.WriteLine( "Command ran" );






