#!/usr/bin/perl -w
# stock.cgi: show stock data
# usage: stock.cgi
# note: call as ../stock.php to allow for smooth page loads
# 20061125 erikt@xs4all.nl

BEGIN { open(STDERR, ">>/WWW/t/tjongkim/tmp/errorlog"); }

use lib "/WWW/t/tjongkim/private/molbeurs/www/cgi-bin";
use shout;
use elib;

# resource specifications 
$baseDir = "/WWW/t/tjongkim/private/molbeurs";
$longDate = `date`;
chomp($longDate);
$recentMax = 50; # maximum length of default recent trade list
$bigAmount = 90;

# standard lines for output
print "Content-type: text/html\n\n";

# host check
$host = $ENV{"REMOTE_ADDR"};
if (not defined $host) { $host = "0.0.0.0"; }
if (open(INFILE,"$baseDir/blocked.host")) {
   while (<INFILE>) {
      $line = $_;
      chomp($line);
      $line =~ s/\s+//;
      if ($host eq $line) {
         print <<THEEND;
<p>
Je computer heeft geen toegang tot de interne pagina's van de Molbeurs.
<p>
Als je vindt dat dit onterecht is, vraag dan
aan erikt(at)xs4all.nl om te worden toegelaten.
THEEND
         exit(0);
      }
   }
   close(INFILE);
}

# variables (incomplete)
my (%bestBuyProp,%bestBuyPrice,%bestSellProp,%bestSellPrice);

# read arguments
$line = <STDIN>;
if (not defined $line) {
   if (defined $ENV{"QUERY_STRING"}) { $line = $ENV{"QUERY_STRING"}; }
   else { $line = ""; } 
}
if ($line eq "" and defined $ARGV[0]) { $line = shift(@ARGV); }
chomp($line);
@args = split(/\&+/,$line);
%args = ();
for ($i=0;$i<=$#args;$i++) {
   if (defined $args[$i]) {
      ($field,$value) = split(/=+/,$args[$i]);
      if (defined $field and defined $value) {
         $args{$field} = $value;
         $args{$field} =~ s/\++$//; # remove trailing spaces
         $args{$field} =~ s/^\++$//; # remove initial spaces
      }
   }
}

if (not defined $args{"STOCK"} or $args{"STOCK"} eq "") {
   print "<p>\nFout: aandeel niet gedefinieerd.\n";
   exit(0);
}
$stock = lc($args{"STOCK"});
$otherStock = $stock;
$otherStock =~ s/mol$/kandidaat/;
$otherColor = $colorC;
if ($stock eq $otherStock) { 
   $otherStock =~ s/kandidaat$/mol/; 
   $otherColor = $colorM;
}
$file = "$baseDir/stocks/".lc($stock);
if (not -f $file) {
   print "<p>\nFout: onbekend aandeel: $stock\n";
   exit(0);
}
if ($stock =~ /mol$/) { $color = $colorM; } else { $color = $colorC; }

# ip logging
&ipLogger();

# check for candidates that dropped out
%left = ();
if (open(INFILE,"$baseDir/LEFT")) {
   while (<INFILE>) {
      $line = $_;
      chomp($line);
      $line =~ s/^\s+//;
      $line =~ s/\s+.*//;
      $line = lc($line);
      $left{"$line+mol"} = 1;
      $left{"$line+kandidaat"} = 1;
   }
   close(INFILE);
}

# read previous prices
$dayPrice = 0;
$weekPrice = 0;
if (open(INFILE,"$baseDir/logs/prices/today")) {
   while (<INFILE>) {
      $line = $_;
      chomp($line);
      ($s,$p,) = split(/\s+/,$line);
      if ($s eq $stock and defined $p) {
         $dayPrice = $p;
         last;
      }
   }
   close(INFILE);
}
if (open(INFILE,"$baseDir/logs/prices/thisweek")) {
   while (<INFILE>) {
      $line = $_;
      chomp($line);
      ($s,$p) = split(/\s+/,$line);
      if ($s eq $stock and defined $p) {
         $weekPrice = $p;
         last;
      }
   }
   close(INFILE);
}

# intro
$fancyStock = &fancyStock($stock,1);
$fancyOther = &fancyStock($otherStock,1);
print <<THEEND;
<html>
<head>
<title>Molbeurs: $fancyStock</title>
<link rel="alternate" type="application/rss+xml" title="RSS Molbeurs" href="http://ifarm.nl/molbeurs/rss.xml">
<meta name="robots" content="noindex, nofollow">
</head>
<body bgcolor="#cccccc">
<div align="center">
<table><tr><td valign="top" align="right" width="180">
THEEND

# show current users
&ipShow();

print <<THEEND;
<td valign="top">
<table width="778" bgcolor="white" cellpadding="5" cellspacing="5">
<tr><td>
THEEND

&menu();

print <<THEEND;
<table cellspacing="0">
<tr>
<td valign="top" width="55%">
<table cellspacing="10" align="left">
THEEND

%prices = ();
%amounts = ();
&readPrices();

&checkTrades();

if ($prices{$stock} == $dayPrice) { $dayPrice = "geen verandering"; }
elsif ($prices{$stock} > $dayPrice) {
   if ($dayPrice == 0) { $dayPrice = 0.01; }
   $dayPrice = sprintf "+%0.2f (<font style=\"color:green;\">+%0.1f%%</font>)",
      $prices{$stock}-$dayPrice,100*($prices{$stock}-$dayPrice)/$dayPrice;
} else {
   $dayPrice = sprintf "%0.2f (<font style=\"color:red;\">%0.1f%%</font>)",
      $prices{$stock}-$dayPrice,100*($prices{$stock}-$dayPrice)/$dayPrice;
}
if ($prices{$stock} == $weekPrice) { $weekPrice = "geen verandering"; }
elsif ($prices{$stock} > $weekPrice) {
   if ($weekPrice == 0) { $weekPrice = 0.01; }
   $weekPrice = sprintf "+%0.2f (<font style=\"color:green;\">+%0.1f%%</font>)",
      $prices{$stock}-$weekPrice,100*($prices{$stock}-$weekPrice)/$weekPrice;
} else {
   $weekPrice = sprintf "%0.2f (<font style=\"color:red;\">%0.1f%%</font>)",
      $prices{$stock}-$weekPrice,100*($prices{$stock}-$weekPrice)/$weekPrice;
}


print "</table>\n<td valign=\"top\">\n";

$dukaten = ($p == 1) ? "dukaat" : "dukaten";
print <<THEEND;
<p>
<a href="/molbeurs/graphs.html#price"><img src="/molbeurs/images/$stock.jpg" width="352" height="144" alt="$stock" border="0"></a>
<a href="/molbeurs/graphs.html#volume"><img src="/molbeurs/images/${stock}-t.jpg" width="352" height="144" alt="$stock" border="0"></a>
<p>
<h1>$fancyStock</h1>
<p>
Huidige waarde: $prices{$stock} $dukaten
<br>Vandaag: $dayPrice
<br>Deze week: $weekPrice
<br>Aandelen in het spel: $amounts{$stock}
<br>Zie ook aandeel: <a href="/molbeurs/stock.php?STOCK=$otherStock" style="color:$otherColor;">$fancyOther</a> ($amounts{$otherStock})
THEEND

# offer trade actions
&buyAndSell();

print <<THEEND;
<p>
<hr>
<address>
Generated at $longDate. erikt(at)xs4all.nl
</address>
</table>
</table>
<td valign="top">
THEEND

&showShoutText(10);

print <<THEEND;
</table>
</div>
</body>
</html>
THEEND

exit(0);

sub buyAndSell {
   my $s = $stock;

   $s =~ s/\+/ /g;

   if (not defined $left{$stock}) {
      print <<THEEND;
<p>
<div style="background-color:$color; color:white;">
<h2>Kopen</h2>
<p>
<form method="post" action="/molbeurs/cgi-bin/trade.cgi">
<input type="hidden" name="STOCK" value="$s">
<input type="hidden" name="ACTION" value="buy">
<table>
<tr>
<td style="color:white;" align="right"> Naam
<td align="left"><input type="text" size="20" name="NICKNAME">
<tr>
<td style="color:white;" align="right"> Aandeel
<td style="color:white;" align="left"> $fancyStock
<tr>
<td style="color:white;" align="right"> Aantal
<td align="left"><input type="text" size="20" name="NUMBER">
<tr>
<td style="color:white;" align="right"> Wachtwoord
<td align="left"><input type="password" size="20" name="PASSWORD">
<tr>
<td align="right"> &nbsp;
<td align="left"><input type="submit" value=" Verstuur ">
</table>
</form>
</div>
<p>
<small>
<iframe src="http://free.timeanddate.com/clock/i1zjhiln/n16/fn15/fs12/tct/pct/ahr/th1" frameborder="0" width="74" height="17" allowTransparency="true"></iframe>
</small>
THEEND
   }

   if (not defined $left{$stock} or $stock =~ /kandidaat/i) {
      print <<THEEND;
<p>
<div style="background-color:$color; color:white;">
<h2>Verkopen</h2>
<p>
<form method="post" action="/molbeurs/cgi-bin/trade.cgi">
<input type="hidden" name="STOCK" value="$s">
<input type="hidden" name="ACTION" value="sell">
<table>
<tr>
<td style="color:white;" align="right"> Naam
<td align="left"><input type="text" size="20" name="NICKNAME">
<tr>
<td style="color:white;" align="right"> Aandeel
<td style="color:white;" align="left"> $fancyStock
<tr>
<td style="color:white;" align="right"> Aantal
<td align="left"><input type="text" size="20" name="NUMBER">
<tr>
<td style="color:white;" align="right"> Wachtwoord
<td align="left"><input type="password" size="20" name="PASSWORD">
<tr>
<td align="right"> &nbsp;
<td align="left"><input type="submit" value=" Verstuur ">
</table>
</form>
</div>
THEEND
   }
}

sub fancyName {
   my ($line) = shift(@_);
   my ($upper);

   if ($line =~ /^([a-z])/) {
      $upper = $1;
      $upper =~ tr/a-z/A-Z/;
      $line =~ s/^./$upper/;
   }
   return($line);
}

sub menu {
   print <<THEEND;
<img src="/molbeurs/images/molbeurs.jpg" width="760" height="80" alt="molbeurs">
<div align="center">
<form action="/molbeurs/cgi-bin/user.cgi">
<a href="/molbeurs/">Home</a> |
<a href="/molbeurs/faq.html">Uitleg</a> |
<a href="/molbeurs/graphs.html">Grafieken</a> |
<a href="/molbeurs/register.html">Registreren</a> |
Naam: <input type="text" size="16" name="NICKNAME">
<input type="submit" value=" Zoek ">
| <a href="http://www.wieisdemol.com/molbeurs/">Forum</a>
| <a href="/demol/category/molbeurs/">Blog</a>
| <a href="/molbeurs/submit.html">Idee&euml;nbus</a>
| <a href="/molbeurs/contact.html">Contact</a>
</form>
</div>
THEEND
}

sub checkTrades {
   my (@buy,@sell,@buyPrice,@sellPrice,%othersBuy,%othersSell,@trades,
       $best,$dir,$file,$line,$n,$s,$c,$p,$action,$i,$now);

   %othersBuy = ();
   %othersSell = ();
   @trades = &readTrades();
   $stock = lc($stock);
   for ($i=0;$i<=$#trades;$i++) {
      # $file $d $action $n $s $c $p -
      ($file,$d,$action,$n,$s,$c,$p,$best) = split(/\s+/,$trades[$i]);
      $s = lc($s);
      if ($s eq $stock) {
         if ($action =~ /buy/i) {
            push(@buy,$trades[$i]);
            push(@buyPrice,$p);
         } else {
            push(@sell,$trades[$i]);
            push(@sellPrice,$p);
         }
      }
      if ($action =~ /buy/) {
         $othersBuy{$s} = (defined $othersBuy{$s}) ? $othersBuy{$s}+$c : $c;
      } else {
         $othersSell{$s} = (defined $othersSell{$s}) ? $othersSell{$s}+$c : $c;
      }
   }
   $sorted = 0;
   @sorted = ();
   for ($i=0;$i<=$#sellPrice;$i++) { $sorted[$i] = $i; }
   while (not $sorted) {
      $sorted = 1;
      for ($i=0;$i<$#sellPrice;$i++) {
         if ($sellPrice[$sorted[$i]] > $sellPrice[$sorted[$i+1]]) {
            ($sorted[$i],$sorted[$i+1]) = ($sorted[$i+1],$sorted[$i]);
            $sorted = 0;
         }
      }
   }
#  if ($#sell >= 0) {
#     print "<tr><td><small>$fancyStock is te koop voor:\n";
#  } else {
#     print "<tr><td><small>Er is op dit moment niemand die $fancyStock wil verkopen.\n";
#  }
#  for ($i=0;$i<=$#sorted;$i++) {
#     # $file 2006.12.26.15:59:56 buy varkentje alex+mol 1 11 $best
#     ($_,$d,$action,$n,$_,$c,$p,$best) = split(/\s+/,$sell[$sorted[$i]]);
#     $d = &summarizeDate($d);
#     $best = ($best eq "-") ? "" : " <font style=\"color:green;\">*</font>";
#     $dukaten = ($p == 1) ? "dukaat" : "dukaten";
#     printf "<br> %d $dukaten (%dx van %s op %s)%s\n",$p,$c,&fancyUser($n,0),$d,$best;
#  }
#  print "</small>\n";
   $sorted = 0;
   @sorted = ();
   for ($i=0;$i<=$#buyPrice;$i++) { $sorted[$i] = $i; }
   while (not $sorted) {
      $sorted = 1;
      for ($i=0;$i<$#buyPrice;$i++) {
         if ($buyPrice[$sorted[$i]] < $buyPrice[$sorted[$i+1]]) {
            ($sorted[$i],$sorted[$i+1]) = ($sorted[$i+1],$sorted[$i]);
            $sorted = 0;
         }
      }
   }
#  if ($#buy >= 0) {
#     print "<tr><td><small>$fancyStock wordt gezocht voor:\n";
#  } else {
#     print "<tr><td><small>Er is op dit moment niemand die $fancyStock wil kopen.\n";
#  }
#  for ($i=0;$i<=$#sorted;$i++) {
#     ($_,$d,$action,$n,$_,$c,$p,$best) = split(/\s+/,$buy[$sorted[$i]]);
#     $d = &summarizeDate($d);
#     $best = ($best eq "-") ? "" : " <font style=\"color:green;\">*</font>";
#     $dukaten = ($p == 1) ? "dukaat" : "dukaten";
#     printf "<br> %d $dukaten (%dx door %s op %s)%s\n",$p,$c,&fancyUser($n,0),$d,$best; 
#  }
#  print "</small>\n";
#  if ($#sell < 0 and $#buy < 0) {
#     if (defined $left{$stock}) {
#        print "<tr><td><small>De handel in dit aandeel is stopgezet.</small>\n";
#     } else {
#        print "<tr><td><small>Er is nu niemand die in dit aandeel wil handelen.</small>\n";
#     }
#  }
   # collect and print stock collectors
   &collectors();
   # collect and print recent trades
   &recentTrades($stock);
}

sub otherStockSort {
   my ($s1,$s2,$p1,$p2) = @_;

   if ($p1 != $p2) { return($p1 <=> $p2); }
   else { return($s1 cmp $s2); }
}

sub fancyStock {
   my ($s,$noHTML) = @_;
   my ($color,@s,$stock);

   if (not defined $noHTML) { $noHTML = 0; }
   $stock = $s;
   $stock =~ /^(.)(.*)\+(.)(.*)$/;
   @s = ($1,$2,$3,$4);
   $s[0] =~ tr/a-z/A-Z/;
   $s[2] =~ tr/a-z/A-Z/;
   if ($stock =~ /mol$/) { $color = $colorM; }
   else { $color = $colorC; }
   $stock = "$s[0]$s[1] $s[2]$s[3]";
   if (not $noHTML) { $stock = "<a href=\"/molbeurs/stock.php?STOCK=$s\" style=\"color:$color;\">$stock</a>"; }
   return($stock);
}

sub fancyUser {
   my ($user,$html) = @_;
   my ($fancyUser);

   $fancyUser = $user;
   $fancyUser =~ s/\+/ /g;
   $user = lc($user);
   if (defined $html and $html >= 0) {
      $fancyUser = "<a href=\"/molbeurs/user.php?NICKNAME=$user\">$fancyUser</a>";
   }
   return($fancyUser);
}

#sub sortMarket {
#   my ($a,$b,$c,$d) = @_;
#
#   if ($a != $b) { return($b <=> $a); }
#   else { return($c cmp $d); }
#}

sub readPrices {
   my ($s,$p,$a);

   %prices = ();
   %amounts = ();
   $file = "$baseDir/prices";
   if (not open(INFILE,$file)) { print "Fout: prijzenbestand onleesbaar\n"; }
   else {
      %prices = ();
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         ($s,$p,$_,$a) = split(/\s+/,$line);
         $prices{$s} = $p;
         $amounts{$s} = $a;
      }
      close(INFILE);
   }  
}

sub summarizeDate {
   my ($date) = shift(@_);

   if ($date =~ /^.....(..).(..).(..):(..):..$/) {
      $date = "$2-$1 $3:$4";
   }
   return($date);
}

sub readTrades {
   my (@files,$dir,$file,$line,$n,$s,$a,$p,$action,@out,$i);
   my $count = 0;
   my $nicknameSpace;

   @out = ();
   %bestBuyProp = ();
   %bestBuyPrice = ();
   %bestSellProp = ();
   %bestSellPrice = ();
   if (not open(INFILE,"grep . /dev/null $baseDir/trades/* 2>/dev/null |")) {
      print "Fout: kan transactiebestanden niet lezen\n";
   } else {
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         $line =~ s/^([^:]*:[^:]*:[^:]*)://;
         $file = $1;
         $file =~ s/.*\///;
         ($d,$action,$n,$s,$a,$p) = split(/\s+/,$line);
         push(@out,"$file $d $action $n $s $a $p -");
         if ($action =~ /buy/i and
             (not defined $bestBuyPrice{$s} or $p > $bestBuyPrice{$s})) {
            $bestBuyPrice{$s} = $p;
            $bestBuyProp{$s} = $#out;
         }
         if ($action =~ /sell/i and
             (not defined $bestSellPrice{$s} or $p < $bestSellPrice{$s})) {
            $bestSellPrice{$s} = $p;
            $bestSellProp{$s} = $#out;
         }
      }
      close(INFILE);
   }
   foreach $i (keys %bestBuyProp) { $out[$bestBuyProp{$i}] =~ s/.$/\+/; }
   foreach $i (keys %bestSellProp) { $out[$bestSellProp{$i}] =~ s/.$/\+/; }
   return(@out);
}

# get successful recent trades from logfile
sub recentTrades {
   my ($stock) = @_;
   my ($line,@trades,%lastLines,$buyer,$d,$s,$t,$c,$f,$a,$n);

   @trades = ();
   if (open(INFILE,"$baseDir/logs/logfile")) {
      %lastLines = ();
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         # 2007.01.07.15:13:56.43360.wh-www10.xs4all.nl <- 2007.01.07.15:10:26.20068.wh-www18.xs4all.nl (1)
         # 2007.01.07.15:15:01 liesbeth+mol total: 4 489.5 122 150
         ($d,$s,$t,$c,$_,$_,$n) = split(/\s+/,$line);
         if (defined $t and $s eq $stock and $t =~ /^(buy|sell)$/) {
#            foreach $f (keys %lastLines) {
#               $buyer = "";
#               if (open(INFILE2,"$baseDir/done/$f")) {
#                  $buyer = <INFILE2>;
#                  close(INFILE2);
#                  chomp($buyer);
#                  ($_,$_,$buyer) = split(/\s+/,$buyer);
#               } elsif  (open(INFILE2,"$baseDir/trades/$f")) {
#                  $buyer = <INFILE2>;
#                  close(INFILE2);
#                  chomp($buyer);
#                  ($_,$_,$buyer) = split(/\s+/,$buyer);
#               } elsif (open(INFILE2,"$baseDir/deleted/$f")) {
#                  $buyer = <INFILE2>;
#                  close(INFILE2);
#                  chomp($buyer);
#                  ($_,$_,$buyer) = split(/\s+/,$buyer);
#               }
#               # remove guessed buyer
#               if ($line =~ /[a-z]$/i) { $line =~ s/\s+\S+\s*$//; } 
#               push(@trades,"$line $lastLines{$f} $buyer");
#            }
             push(@trades,$line);
         }
         #if (defined $s and $s eq "<-") { 
         #   $c =~ s/\D//g;
         #   $lastLines{$d} = $lastLines{$d} ? $lastLines{$d}+$c : $c; 
         #} else { %lastLines = (); }
      }
      close(INFILE);
   }
   if ($#trades >= 0) {
      $recent = (defined $args{"MAX"} and $args{"MAX"} eq "1") ? "" : " recent";
      print "<tr><td><small>$fancyStock is$recent verhandeld voor:\n";
      for ($i=$#trades;($i>=0 and ($i>=$#trades-$recentMax or 
         (defined $args{"MAX"} and $args{"MAX"} eq "1")));$i--) {
         # line format: 2007.01.02.15:55:00 alex+mol total: 2 130 20 75 2 lo
         #        2008: ($d,$s,$t,$c,$_,$_,$n) = split(/\s+/,$line);
         ($d,$_,$s,$a,$_,$_,$p,$buyer) = split(/\s+/,$trades[$i]);
         $d = &summarizeDate($d);
         if ($a <= 0) { next; }
         $dukaten = ($p == 1) ? "dukaat" : "dukaten";
         if (not defined $buyer or $buyer eq "" or $s !~ /^(buy|sell)$/) { $buyer = ""; }
         elsif ($s eq "buy") { $buyer = ", koper: " . &fancyUser($buyer,0); }
         else { $buyer = ", verkoper: " . &fancyUser($buyer,0); }
         # next condition avoids $c==0 but might cause less than 10 being shown
         $p = sprintf "%0.2f",$p;
         if ($a >= $bigAmount) { $a = "<strong>${a}x</strong>"; }
         else { $a .= "x"; }
         print "<br>$p $dukaten ($a op $d$buyer)\n";
      }
      if ($#trades > $recentMax and 
          (not defined $args{"MAX"} or $args{"MAX"} ne "1")) { 
         print "<br>(<a href=\"/molbeurs/stock.php?STOCK=$stock\&MAX=1\">alles</a>)\n"; }
      print "</small>\n";
   }
}

sub collectors {
   my ($file) = "$baseDir/collectors/$stock";
   my ($line,$nickname,$number,$i,%counts);

   if (open(INFILE,$file)) {
      # read the collectors
      %counts = ();
      while (<INFILE>) {
         $line = $_;
         chomp($line);
         ($number,$nickname) = split(/\s+/,$line);
         $counts{$nickname} = $number;
      }
      close(INFILE);
      # print the collectors in descending order
      $last = "";
      print "<tr><td><small>$fancyStock wordt verzameld door:<br>\n";
      foreach $i (sort { $counts{$b} <=> $counts{$a} } keys %counts) {
         if ($last ne "") { print ",\n"; }
         printf "%s (%d)",&fancyUser($i,0),$counts{$i};
         $last = $i;
      }
      print "\n";
      close(INFILE);
      print "</small>\n";
   }
}

# ip logger
#sub ipLogger {
#   open(OUTFILE,">>$baseDir/logs/ips/now") or return();
#   if (@_) { printf OUTFILE "%d %s %s\n",time(),$ENV{"REMOTE_ADDR"},$_[0]; }
#   else { printf OUTFILE  "%d %s\n",time(),$ENV{"REMOTE_ADDR"}; }
#   close(OUTFILE);
#   return();
#}

