<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
  <head>
    <title>Command History -- a PHP exercise in arrays</title>
  </head>

  <body>
    <h1>Command History -- a PHP exercise in arrays</h1>

    <?php
      
/** Defines **/
      
define("RESULTS", "$DOCUMENT_ROOT/downloads" );
      
define("MAX_BARS", 10 );

      
/**    Function : getTmpPath
       **    Purpose:   figure out where tmp space is.
       **    Returns:   path to temporary filesystem space
       **/
      
function getTmpPath( ) {
        if( ! (
$tmp = getenv("TMPDIR")) ) {
          
$tmp = "/tmp";
//          echo "<BR>DEBUG: not set, so path is $tmp<BR>";
        
}
        return
$tmp;
      }

      
/**    Function : firstWord
       **    Purpose:   replaces the line by the first word in the line
       **    Returns:   n/a
       **/
      
function firstWord( &$val, $key ) {
        static
$sep = "([\t \n\r]+)";

        
$tok = strtok( trim($val), $sep );
        
$val = $tok;
      }

      
/**    Function : printArray
       **    Purpose:   print an array (for debugging)
       **    Args:      $a is the array
       **               $break is # of echo stmts before a <BR>
       **    Returns:   n/a
       **/
      
function printArray( $a, $break ) {
        
reset( $a );
        echo(
"<BR>" );
        
$cnt = 0;
        for(
$i = 0; $i < count($a); $i++ ) {
          echo
" : " . $a[$i];
          if(
$cnt == $break - 1 ) {
            echo(
"<BR>" );
            
$cnt = 0;
          }
          else {
            
$cnt++;
          }
        }
        echo(
"<BR>" );
      }

      
/**    Function : getWords
       **    Purpose:   the meat of this script..
       **    Returns:   path to history file to be analysed
       **/
      
function getWords( $f ) {
        
$lines = file( $f );  // read file into array 'lines'
        
array_walk( $lines, 'firstWord' );  // return array with only 1st words
        
reset( $lines );
        
$cmds = array( "" );
        
$cnt = 0;
        
/** get rid of comments (tcsh)  **/
        
while( list($key, $val) = each($lines) ) {
          if( !
ereg("^#", $val) ) {
            if(
$cnt > 0 ) {
              
array_push( $cmds, $val );
            }
            else {
              
$cmd[0] = $val;
            }
            
$cnt++;
          }
        }
        
sort( $cmds ); // sort to make tallying easier

        
$lastkey = "";
        
$lastcount = 0;
        
$totalunique = 0;
        
reset( $cmds );
        
$num = count( $cmds );
        
$totalcmds = $num;
        if(
$totalcmds < 2 ) {
          echo
"<BR>not enough history to bother with..";
          return;
        }
        
$stats = array( "" ); // array to hold statistics 'structure'
        
$cnt = 0;
        for(
$i = 0 ; $i < $num ; $i++ ) { // now create statistics
          
$element = next( $cmds );
          if(
strcmp($lastkey, $element) != 0 ) {
            if(
$i > 0 ) {
              
$percent = $lastcount/$totalcmds * 100;
              if(
$percent < 0.01 ) {
                
$percent = 0.01;
              }
              
$totalunique += 1;
              if(
$cnt > 0 ) {
                
array_push( $stats, $totalunique,
                 
$lastkey, $lastcount, $percent );
              }
              else {
                
$stats[0] = $totalunique;
                
array_push( $stats, $lastkey, $lastcount, $percent );
              }
              
$cnt++;
            }
            
$lastkey = $element;
            
$lastcount = 1;
          }
          else {
            
$lastcount += 1;
          }
        }
        echo
"<BR>There are " . $num . " commands in the history file.  ";
        echo
$totalunique . " commands are unique.\n";
//        printArray( $stats, 4 );
        
$num = count( $stats );

        
$numbers = array( "" );
        
reset( $stats );
        
$numbers[0] = $stats[2];
        for(
$i = 6 ; $i <= $num ; $i+=4 ) {
          
array_push( $numbers, $stats[$i] );
        }
        
reset( $numbers );
        
arsort( $numbers );
        
$num = count($numbers);

// image stuff
        
$im = imagecreate( 450, 250 );

        
$white =  ImageColorAllocate( $im, 255,255,255 );
        
$yellow = ImageColorAllocate( $im, 255,255,0 );
        
$orange = ImageColorAllocate( $im, 255,165,0 );
        
$brown =  ImageColorAllocate( $im, 165,42,42 );
        
$maroon = ImageColorAllocate( $im, 128,0,0 );
        
$red =    ImageColorAllocate( $im, 255,0,0 );
        
$magenta= ImageColorAllocate( $im, 255,0,255 );
        
$purple = ImageColorAllocate( $im, 128,0,128 );
        
$navy =   ImageColorAllocate( $im, 0,0,128 );
        
$blue =   ImageColorAllocate( $im, 0,0,255 );
        
$teal =   ImageColorAllocate( $im, 0,128,128 );
        
$aqua =   ImageColorAllocate( $im, 0,255,255 );
        
$green =  ImageColorAllocate( $im, 0,128,0 );
        
$lime =   ImageColorAllocate( $im, 0,255,0 );
        
$gray =   ImageColorAllocate( $im, 128,128,128 );
        
$black =  ImageColorAllocate( $im, 0,0,0 );

        
imagefill( $im, 0, 0, $gray );
        
imageLine( $im, 25, 25, 25, 225, $black );
        
imageLine( $im, 25, 225, 425, 225, $black );
        
$max = 1;
        
$nBars = ($num < MAX_BARS) ? $num : MAX_BARS;
        
$width = (400 / $nBars) - 10;
        
$height = 200;
        
$sx = 25;
        
$sy = 25;
        
$ex = 25 + $width;
        
$ey = 25 + $height;
        for(
$i = 0 ; $i < $nBars ; $i++, next($numbers) ) {
          
$key = key( $numbers );
          
//$str = $stats[$key*4+1] . " : " . $stats[$key*4+3] . " %";
          
$len = strlen( $stats[$key*4+1] );
          if(
$len > 12 ) {
            
$stats[$key*4+1] = substr( $stats[$key*4+1], $len-12 );
          }
          
$str = sprintf( "%12s : %4.2f %%",
           
$stats[$key*4+1], $stats[$key*4+3] );
          if(
$i == 0 ) { // then we have the maximal value -- scale with it
            
$max = $numbers[$key];
            
imagefilledrectangle( $im, $sx, $sy, $ex, $ey, $blue );
            
imagestringup( $im, 5, $ex-25, $ey-10, $str, $aqua );
          }
          else {
            
$sx += $width + 10;
            
$height = $height * ($stats[($key*4)+2] / $max);
            
$k = $key*4;
//echo "<BR> DBG:  fields  are " . $stats[$k] . " : " . $stats[$k+1] . " : " . $stats[$k+2] . " : " . $stats[$k+3] . " : " . $height;
            
$sy = 225 - $height;
            
$ex = $sx + $width;
            
$ey = $sy + $height;
            
imagefilledrectangle( $im, $sx, $sy, $ex, $ey, $blue );
            
imagestringup( $im, 5, $ex-25, $ey-10, $str, $aqua );
          }
        }
        
$p = tempnam( RESULTS, "pie" ) . ".gif"; // tmp dest filename
        
imagegif( $im, $p );
        
imagedestroy( $im );
        echo
"<img src=\"historyImage.php?$p\" ALT=\"History Image\"><BR>\n";
      }

      
/**    Function : create a tmp pathname
       **    Returns:   pathname
       **/
      
function buildPath( $string ) {
        
$t = time( );  // use # of seconds to randomize dir name
        
$p = getTmpPath() . "/" . $t;
        if(
mkdir($p, 0700)) {
          
$p = $p . "/" . $string;
        }
        else {
          
$p = "";
        }
        return
$p;
      }

      
/** MAIN starts **/
      
if( file_exists($userfile) ) {
        
$f = buildPath( $userfile_name );  // generate tmp pathname
        
if( strlen($f) > 0 ) {
          if(
rename($userfile, $f) ) {  // rename the file to tmp name
            
$ar = "";
            
/** fork the 'file' command to provide funky info **/
            
$cmd = EscapeShellCmd( "/usr/bin/file -b $f" );
            
exec( $cmd, $ar, $ret );
            if(
$ret == 0 ) {
              if( !
eregi("ASCII text", $ar[0]) ) {
                
printf("Sorry, your input file <FONT COLOR=\"red\"><I>%s</I></FONT>
                 does not seem to be a history file, but reports file type:
                 <I>%s</I>"
, $userfile_name, $ar[0] );
              }
              else {
                
getWords( $f );
              }
            }
          }
          
// clean up tmp files
          
if( unlink($f) ) {
            
rmdir( dirname($f) );
          }
          else {
            echo
"<BR>DEBUG: could not unlink " . $f . "<BR>";
          }
        }
      }
    
?>

    <hr>
    <address>
    <a href="mailto&#058;Denice&#046;Deatrich&#064;epfl.ch">Denice Deatrich</a>
    </address>
<!-- Created: Thu Dec  2 22:37:03 MET 1999 -->
<!-- hhmts start -->
Last modified: Thu Dec  2 23:01:25 MET 1999
<!-- hhmts end -->
  </body>
</html>