#!/usr/bin/perl -w
#
# gets product id's and forms request to worldpay
# wp_reg.pl?tick=game_id+game_id+...&curr=USD|GBP|EUR&test=nnn
#
# order is given ID (time+$$+md5(cookie) in hex)
# some data are logged

use strict;
use diagnostics;
use Fcntl qw(:DEFAULT :flock);
use CGI qw(:standard -oldstyle_urls);
use CGI::Carp;
use Digest::MD5 qw(md5_hex);

$CGI::POST_MAX = 1024*8;
$CGI::DISABLE_UPLOADS = 1;

use vars qw($game_id $currency $amount $cartId $descript %order %product
            $other @other_os $os_id $other_ban $regmode);

my $wp_url = "https://select.worldpay.com/wcc/purchase";
my $instId = "58349";
my $md5pass = "mymd5pass";
my $test_mode = param('test') || 0; # 100=success; 101=failure; 0=NO test
my $accId1 = $test_mode ? "16728589"   # test
                        : "16746800";  # live

my $cookname = 'ab_ut';

my $order_log = '/home/absolutist/www-data/worldpay/wp_preorder.log';
my $order_out = '/home/absolutist/www-data/worldpay/wp_outorder.log';
my $web_root  = '/home/absolutist/htdocs_bs';
my $game_conf = '/home/absolutist/www-data/worldpay/wp_game_conf.pl';

my %url = (
  w => "http://bshooter.com/",
  l => "http://linuxbag.com/",
  p => "http://pocketroom.com/palm/",
  c => "http://pocketroom.com/pocket/",
);

# other registrators
my %regs = (
  RN => { url => 'https://www.regnow.com/softsell/nph-softsell.cgi',
          prod => 'item',
          sconto => 'ss_coupon',
          userid => 'linkid',
        },
  RS => { url => 'http://www.regsoft.net/purchase.php3',
          prod => 'productid',
          sconto => 'pc',
#          userid => 'linkid',
        },
);

my %osname = (
  w => "Windows PC",
  p => "Palm OS",
  c => "Pocket PC",
  l => "Linux",
);

# game description template
my $desc_templ = "<_GAME_>: registration for the full version";

my $default_tick = "awgBUBL";

### end config -----------------------------------------------------------

# read product features
do $game_conf;

# read the parameters:
# check game ticker
if ($game_id = param('tick')) {
    unless (defined $product{$game_id}) {
        $game_id = $default_tick;
        warn("bad ticker in request: $ENV{QUERY_STRING}\n");
    }
} else {
    $game_id = $default_tick;
    warn("no ticker in request: $ENV{QUERY_STRING}\n");
}

# registration mode flag
$regmode = param('rm') || "-";

# set the right case, just in case
$game_id = lc(substr($game_id, 0, 3)) . uc(substr($game_id, 3, 5));
$os_id   = substr($game_id, 1, 1);

$currency = param('curr') || "USD";
my $time = time();
my $addr = remote_host();
my $proc = $$;

# get the cookie
my $cookie = cookie($cookname) || "-";

# assign the order id
my $order_id = sprintf("%lx-%lx-%s",
                       $time, $proc, substr( md5_hex($cookie),-3) );

unless ($amount = $product{$game_id}->{price}->{uc $currency}) {
    warn "no such currency: '$currency'\n";
}

open  LOG, ">>$order_log" or warn "can't append to $order_log: $!\n";
flock LOG, LOCK_EX;
print LOG $time, "\t", $addr, "\t", $game_id, "\t", $order_id, "\t",
          $currency, "\t", $amount, "\t", $amount, "\t", $cookie,
	  "\t", $regmode, "\n";
close LOG;

($descript = $desc_templ) =~ s/<_GAME_>/$product{$game_id}->{name}/g;

%order = (
  instId   => $instId,
  accId1   => $accId1,
  cartId   => $order_id,
  amount   => $amount,
  currency => $currency,
  signatureFields => "amount:currency:cartId:MC_ticker",
  signature => md5_hex("$md5pass:$amount:$currency:$order_id:$game_id"),
  desc     => $descript,
  MC_osname   => $osname{$os_id},
  MC_ticker   => $game_id,
  MC_gamename => "$product{$game_id}->{name}",
  MC_utcook   => $cookie,
  MC_regmode  => $regmode,
  testMode => $test_mode,
);

## if there othe OS versions?
@other_os = ();
foreach (keys %osname) {
    next if $_ eq $os_id;
    {
    local $game_id = $game_id;
    substr($game_id, 1, 1) = $_;
    push @other_os, $_ if exists $product{$game_id}->{name};
    }
}

# we'll print it in the right column
if (my $n_oth = @other_os) {
    $other_ban = "<table border=0><tr><td>" .
          "<font size=-1 color='#ffffcc'><h4>Do not miss!</h4><p>Other versions of <b>$product{$game_id}->{name}</b> are available:</font></td></tr>";
    foreach my $os (@other_os) {
        my $other_url = self_url();
        $other_url =~ s/tick=(.)(.)/tick=$1$os/;
        $other_ban .= '<tr><td><a href="' . $other_url . '">'
	              . $osname{$os} . '</a></td></tr>';
    }
    $other_ban .= "</table>" . p;
} else { $other_ban = "" }

$amount = monify($amount);   # makre it look like money

print header(-type=>'text/html', -expires=>'-1y');

print start_html(-title => "BShooter.com - $descript",
                 -bgcolor => '#C5C4FE',
		 -leftmargin  => 10, -topmargin    => 10,
		 -marginwidth => 10, -marginheight => 10,
		 -meta => {-keywords=>'free games order full version online download shareware freeware demo java flash bubbles lines',
			   -description=>$descript},
                 -style  => {-src=>'/bubshooter.css'},
		 -script => {-language=>'JAVASCRIPT', -src=>'/bubshooter.js'},
#                 -onLoad => qq|preloadImages('/images/b_refresh_h.gif');|,
      );

print my_header();

print h2($descript),
      '<blockquote>',
      "<font size=+1>Thank you for choosing <b>$order{MC_gamename}</b> for <b>$order{MC_osname}</b>.", br,
      "You will be charged <b>$currency $amount</b> for the full game license.</font>";

print p, "Just click one of the buttons, depending on the way of payment
      you'd prefer, and you will be transferred to a secure server. We use
      best technology available to make the whole payment process secure
      and protect your privacy.", p,
      "Credit card orders are fulfilled in real time. Please fill the form
      carefully, as we will send you your registration information at the
      e-mail address you provide.", p,
      "Do not hit the button twice - this is likely to produce a duplicate order.", p,
      "Make sure your e-mail provider's filter is so configured that you can
      receive our mail. Please turn off any mail-filter that would require a
      manual confirmation and cause a delay in delivery of your code.", p,
     "<font size=-1>Please be patient while you are transferred to the secure
      server. The page will open in a new window.</font>", p;
#print start_form(-action => $wp_url, -method => 'POST',  -target=>'reg');
#
#foreach my $field (keys %order) {
#    print hidden(-name => $field, -default => $order{$field});
#}
#
#print table({-border=>0},
#        Tr({-valign=>'CENTER'},
#	   td(submit(-name => "Get Full Version",
#	      -value => "Get Full Version")),
#	   td("<font size=-1>Click this button if your card is one of these: "
#	      ."<b>Visa, Mastercard, Eurocard</b>. </font>")
#	),
#        Tr({-valign=>'CENTER'},
#	   td({-colspan=>2}, '<font size=-1 color="#cc0000">Attention! Please ',
#	   'use the button below if you have problems with this one.</font>')
#	)
#      ),
#      end_form;

# now choose rs or rn for second button (maybe both???)
foreach (keys %regs) {
    if (defined $product{$game_id}->{$_ . "_id"}) { $other = $_ }
}

if (defined $other) {  ## quick fix - rewrite it
#print "To use other method (checks, fax, phone and mail order are accepted;
#      additional fee will be charged for those methods),
#      please click the button below.", p;

print start_form(-action => $regs{$other}->{url},
                 -method => 'GET', -target=>'reg'),
      # print product id
      hidden(-name => "$regs{$other}->{prod}",
             -default => $product{$game_id}->{$other."_id"}),
      # print discount will be here
      (defined($regs{$other}->{sconto}) && $product{$game_id}->{$other."_sc"})
        ? hidden(-name => "$regs{$other}->{sconto}",
                 -default => $product{$game_id}->{$other."_sc"}) : "",
      # print cookie if registrar allows it
      (defined($regs{$other}->{userid}) && $cookie =~ /\d/)
        ? hidden(-name => "$regs{$other}->{userid}",
                 -default => $cookie) : "";
print table({-border=>0},
        Tr({-valign=>'CENTER'},
	   td(submit(-name => "Get Full Version",
	      -value => "Get Full Version")),
	   td("<font size=-1>Click this button if your card is "
	      ."<b>American Express, Discover, Master Money or other</b>, or "
	      ."if you want to pay off-line by <b>Check, Fax, Phone, Post Order</b>.</font>"),
	)
      ),
#      p, "<font size=-1>Please be patient while you are transferred to the secure
#          server. The page will open in a new window.</font>",
      div({-align=>'right'},
          q|<a href="javascript:void(0)" onclick="javascript:window.open('http://absolutist.com/register/quick_instr.html', 'instructions', 'width=550,height=350, scrollbars=yes')">How it works?</a>|
      ),
      end_form, p, hr, p;
}  ## end fix!

print qq|
<font size=-1>
You can also get new
<a href="https://www.regnow.com/softsell/nph-softsell.cgi?item=5012-2&Get+Full+Version=Get+Full+Version">Bubble Shooter Deluxe</a>,
 <a href="http://absolutist.com/cgi-bin/wp_reg.pl?tick=awgBUPE">Bubble Shooter: Premium Edition</a>,
 <a href="https://www.plimus.com/jsp/buynow.jsp?contractId=2179106">Bubble Shooter Christmas Edition</a>,
 <a href="https://absolutist.com/cgi-bin/wp_reg.pl?tick=awgBGPK">Bubble Golden Pack</a><br /><br />
</font>

<font size=-1>Refunds will be given at the discretion of the Company Management. Please read the
	 <a href="javascript:void(0)" onClick="window.open('http://absolutist.com/LICENSE.TXT', '_lcns', 'location=no,statusbar=yes,status=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,resizable=yes,width=600,height=400')">license
	 agreement</a>. Please make sure the
	 <a href="$product{$game_id}->{dload2}">trial version</a> works properly
         on your computer</font>|;

print '</blockquote>', my_footer(), end_html;

exit;

sub monify {
    my $str = $_[0] or return "0.00";
    return sprintf("%4.2f", $str);
}

sub my_header {
return <<'_END_HEADER_';
<table width="778" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr valign="top">
    <td width="23" align="left" background="/images/mid2_in.gif"><img src="/images/mid1_in.gif" width="23" height="17"></td>
    <td background="/images/fon_top.gif"><img src="/images/spacer.gif" width="720" height="1"></td>
    <td width="35" align="right" background="/images/fon_right.gif"><img src="/images/corn1.gif" width="35" height="17"></td>
  </tr>
  <tr>
    <td width="23" align="left" background="/images/mid2_in.gif">&nbsp;</td>
    <td bgcolor="#B3B3FB"><SCRIPT LANGUAGE=JavaScript1.1>
<!--
var MM_contentVersion = 5;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	    for (var i = 0; i < words.length; ++i)
	    {
		if (isNaN(parseInt(words[i])))
		continue;
		var MM_PluginVersion = words[i];
	    }
	var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0
   && (navigator.appVersion.indexOf("Win") != -1)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
	document.write('</SCR' + 'IPT\> \n');
}
if ( MM_FlashCanPlay ) {
		document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
	document.write('  codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" ');
	document.write(' ID="flash" WIDTH="700" HEIGHT="107" ALIGN="">');
	document.write(' <PARAM NAME=movie VALUE="/images/flash_in.swf"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#C5C4FE>  ');
	document.write(' <EMBED src="/images/flash_in.swf" quality=high bgcolor=#C5C4FE  ');
	document.write(' swLiveConnect=FALSE WIDTH="700" HEIGHT="107" NAME="flash" ALIGN=""');
	document.write(' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">');
	document.write(' </EMBED>');
	document.write(' </OBJECT>');
} else{
	document.write('<IMG SRC="/images/flash_in.jpg" WIDTH="700" HEIGHT="107" usemap="#flash" BORDER=0>');
}
//-->
</SCRIPT><NOSCRIPT><IMG SRC="/images/flash.jpg" WIDTH="350" HEIGHT="525" usemap="#flash" BORDER=0></NOSCRIPT>
</td>
    <td width="35" align="right" background="/images/fon_right.gif">&nbsp;</td>
  </tr>
  <tr valign="bottom">
    <td width="23" align="left" background="/images/mid2_in.gif"><img src="/images/mid3_in.gif" width="23" height="13"></td>
    <td background="/images/fon_bot.gif"><img src="/images/spacer.gif" width="720" height="1"></td>
    <td width="35" align="right" background="/images/fon_right.gif"><img src="/images/corn2.gif" width="35" height="13"></td>
  </tr>
</table>
<img src="/images/spacer.gif" width="10" height="10">
<table width="778" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr valign="top">
    <td width="23" align="left" background="/images/mid2_in.gif"><img src="/images/mid1_in.gif" width="23" height="17"></td>
    <td background="/images/fon_top.gif"><img src="/images/spacer.gif" width="720" height="1"></td>
    <td width="35" align="right" background="/images/fon_right.gif"><img src="/images/corn1.gif" width="35" height="17"></td>
  </tr>
  <tr>
    <td width="23" align="left" background="/images/mid2_in.gif">&nbsp;</td>
    <td valign="top" bgcolor="#B3B3FB">
_END_HEADER_
}

sub my_footer {
return <<_END_FOOTER_;
    </td>
    <td width="35" align="right" background="/images/fon_right.gif">&nbsp;</td>
  </tr>
  <tr valign="bottom">
    <td width="23" align="left" background="/images/mid2_in.gif"><img src="/images/mid3_in.gif" width="23" height="13"></td>
    <td background="/images/fon_bot.gif"><img src="/images/spacer.gif" width="720" height="1"></td>
    <td width="35" align="right" background="/images/fon_right.gif"><img src="/images/corn2.gif" width="35" height="13"></td>
  </tr>
</table>
<div align="center" class="txt2"><font color="#FFFFFF"><a href="/download.html">Download</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="/cgi-bin/wp_reg_bs.pl?tick=awgBUBL">Full version</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="/screenshot.html">Screenshots</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="/cgi-bin/tournament.pl">Tournament</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="/news.html">News</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="/support.html">Support</a></font><br>
  <br />
  <font class="txt2">
    Bshooter.com is the best place for all fans of Bubbles games.
    You can download a classic Bubble Shooter Deluxe game for free and try it.<br />
    Now the new sequel of bubbles game is available.
    Download a free trial version of Bubble Shooter: Premium Edition game.<br />
    Enjoy a free bubbles screensaver, 3 game themes and 8 bubbles skins.
    Play Bubble Shooter for free online.<br />
    Have endless bubble bursting fun 24/7 at Bshooter.com.
    &copy; BShooter.com 2003-2009
  </font>
</div>

<MAP NAME="flash">
  <area shape="rect" coords="49,55,155,96" href="/">
  <area shape="rect" coords="163,54,287,97" href="/download.html">
  <area shape="rect" coords="294,52,437,95" href="/screenshot.html">
  <area shape="rect" coords="445,50,588,92" href="/cgi-bin/tournament.pl">
  <area shape="rect" coords="595,50,700,92" href="/support.html">
</MAP>
_END_FOOTER_
}
