<?PHP

/******************************************************************************

dopewars - deal drugs to make lots and lots of money
Copyright (C) 2002 - 2003 drunkmenworkhere.org

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
http://www.gnu.org/licenses/gpl.txt

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

******************************************************************************/


/******************************************************************************

REQUIREMENTS:

  - PHP 4.2 or later
  - PostgreSQL 7.3


DATABASE:

  Dopewars uses 2 PostrgreSQL tables, you can use this SQL to create them in
  a database called 'drunkmen' (edit class db if you want to use a different 
  database name): 

    CREATE TABLE dopewars (
        id              serial,
        name            text,
        password        text,
        score           int,
        onthemove       boolean,
        player          text,
        date            datetime DEFAULT now ( )
    );

    CREATE UNIQUE INDEX dopewars_name ON dopewars (name);

    CREATE TABLE dopescores (
        id              serial,
        name            text,
        password        text,
        score           int,
        date            datetime DEFAULT now ( )
    );

  WARNING: porting Dopewars to MySQL is non-trivial since it uses row-level
  locking (select ... for update) which is not implemented in MySQL.

SCRIPT:

  The complete dopewars script is in this single file, the include file is 
  irrelevant for dopewars. The files referenced in this script located in 
  ../data are not required either.

  register_globals should be set to 'on' in your php.ini

  WARNING: the code is quite crufty!

******************************************************************************/



mt_srand ((float) microtime() * 1000000);


session_register("uid");
session_register("player");
session_register("language");

define("MAXLOAN"2000000);
define("MAXUSERS"20);



// ****************************************************************************
// CHECK FOR SEMAPHORE (created by database vacuum script in crontab)

$sem = @file("../data/185sem");
if (
$sem[0]) {
    echo 
"<html><head><link rel=\"stylesheet\" href=\"default.css\" type=\"text/css\">";
    echo 
"<title>dopewars</title></head>\n<body>";
    echo 
"<h2>dopewars</h2><p>is temporary offline<br />try again in a few minutes</p>\n";
    echo 
"<!--\n start time: " $sem[0] . "--></body></html>";
    exit;
}


// ****************************************************************************
// GENERIC POSTGRESQL WRAPPER

class db {
    var 
$db;
    
    function 
db() {
//        error_reporting(1); // no warnings
        
$this->db=pg_pconnect("dbname=drunkmen");  // database name is drunkmen
        
if (!$this->db) {
            echo 
"No database connection";
            exit;
        }
    }
    
    function 
qry($qry,$num=0)
    {
        if (!isset(
$this->db)) return FALSE;
        
        
$rel pg_query($this->db$qry);
        if (!
$rel) {
            return array();
        }
        
        
$nr pg_numrows($rel);
        if (
$num==0$num=$nr;
        else if (
$num>$nr$num=$nr;
        
        
$res = array();
        
        for(
$i 0$i $num$i++)
            
$res[] = pg_fetch_array($rel$iPGSQL_ASSOC);

        return 
$res;
    }
}

$db = new db();


// ****************************************************************************
// HIGH SCORE LIST

if ($action == "hiscore") {
    echo 
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
    echo 
"<html><head><title>dopewars</title><link rel=\"stylesheet\" href=\"default.css\" type=\"text/css\"></head><body><h3>dopewars - high scores</h3>";
    
    echo 
"<p><b>active dealers</b></p>";
    
$qry "select name, score from dopewars order by score desc";
    
$results $db->qry($qry);
    while (list(
$key$val) = each ($results)) {
            echo 
$key+1;
            echo 
" - " htmlentities($val["name"]) . " (\$" $val["score"] . ")<br>";
    }
    
    echo 
"<p><b>legendary dead dealers - all time high scores</b></p><p>(top 50)</p>";
    
$qry "select name, score from dopescores order by score desc limit 50";
    
$results $db->qry($qry);
    while (list(
$key$val) = each ($results)) {
            echo 
$key+1;
            echo 
" - " htmlentities($val["name"]) . " (\$" $val["score"] . ")<br>";
    }
    
    echo 
"<p><a href=\"$PHP_SELF\">back</a></p>";
    echo 
"</body></html>";
    exit;
}


// ****************************************************************************
// LOGIN SCREEN 

if (!$player || $logout) {
    
    
$uid "";
    
$player "";

    switch (
$action) {
        case 
"login":
            
$name trim(str_replace(","" "substr($name,0,20)));
            
$password trim(substr($password,0,15));
            if (
addslashes($name) != $name || (strstr($name"  ") && $new)) {
                
$error "Invalid characters in username.";
            } else if (
addslashes($password) != $password) {
                
$error "Invalid characters in password.";
            } else if (
$name != "" && $password != "") {
                
$language=$lang;
                
$lname strtolower($name);
                
$qry "select * from dopewars where lower(name) = '$lname';";
                
$result $db->qry($qry);
                if (
$new) {
                    if (
$result != array()) {
                        
$error "There already exists a user named \"$name\".";
                    } else {
                        
check_max();
                        
$player["name"] = $name;
                        
$player["cash"] = 5000;
                        
$player["debt"] = 4761;
                        
$player["bank"] = 0;
                        
$player["guns"] = 0;
                        
$player["bitches"] = 2;
                        
$player["space"] = 20 $player["bitches"] * 10;
                        
$player["held"] = 0;
                        
$player["life"] = 100;
                        
$player["guns"] = array();
                        
$player["drugs"] = array();
                        
$player["drugprices"] = array();
                        
$player["prices"] = array();
                        
$player["destination"] = 1;
                        
$player["snitches"] = array();
                        
$player["currentsnitches"] = array();
                        
$player["snitchreport"] = array();
                        
$player["fighthistory"] = array();


                        
$pl addslashes(serialize($player));
                        
$qry "insert into dopewars (name, password, score, player) values ('$name', '$password', 0, '$pl');";
                        
$result $db->qry($qry);

                        
$uid $name;
                    }                                            
                } else {
                    if (
$result == array()) {
                        
$error "No such user";
                    } else if (
$result[0]["password"] != $password) {
                        
$error "Invalid password";
                    } else {
                        
check_max();
                        
$uid addslashes($result[0]["name"]);
                    }
                    
                }                    
            }
            if (!
$uid) {
                echo 
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
                echo 
"<html><head><title>dopewars</title><link rel=\"stylesheet\" href=\"default.css\" type=\"text/css\"></head><body><h3>dopewars - login</h3>";
                echo 
"<div style=\"height:20px;margin-top:30px;\">";
                if (
$error) {
                    echo 
"<p>$error</p>";
                }
                echo 
"</div>";
                echo 
"<form action=\"$PHP_SELF\" method=\"POST\">";
                echo 
"<p>name: ";
                echo 
"<input name=\"name\" type=\"text\" value=\"\" class=\"button\" size=\"10\" maxlength=\"20\"></p>";
                echo 
"<p>password: ";
                echo 
"<input name=\"password\" type=\"password\" value=\"\" class=\"button\" size=\"10\" maxlength=\"15\"></p>";
                echo 
"<p>language: ";
                echo 
"<select name=\"lang\" class=\"button\"><option value=\"EN\">English</option>";
                if (
strtolower($HTTP_ACCEPT_LANGUAGE) == "nl") {
                    echo 
"<option value=\"NL\" selected>Nederlands</option>";
                } else {
                    echo 
"<option value=\"NL\">Nederlands</option>";
                }
                echo 
"</select></p>";
                if (
$new) {
                    echo 
"<p><input name=\"new\" type=\"checkbox\" checked> <label for=\"new\">create new account</label></p>";
                } else {
                    echo 
"<p><input name=\"new\" type=\"checkbox\"> <label for=\"new\">create new account</label></p>";
                }
                echo 
"<input name=\"action\" type=\"hidden\" value=\"login\">";
                echo 
"<input type=\"submit\" value=\"login\" class=\"button\"> ";
                echo 
"</form>";    
                echo 
"</body></html>";
                exit;
            }
            break;

        default:

            
// genereric script to check for drunkmenworkhere editions
            // comment out next two lines, they're only useful on drunkmenworkhere.org
            
@include("editions.php");
            @
checkEdition();

            echo 
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
            echo 
"<html><head><title>dopewars</title><link rel=\"stylesheet\" href=\"default.css\" type=\"text/css\"></head><body>";
            echo 
"<h2>dopewars</h2>";
            echo 
"<p>(deal drugs to make lots and lots of money)</p>";
            echo 
"<p><a href=\"$PHP_SELF?action=login\">login</a> | ";
            if (
strtolower($HTTP_ACCEPT_LANGUAGE) == "nl") {
                echo 
"<a href=\"185NL.html\" target=\"_blank\">instructions</a> | ";
            } else {
                echo 
"<a href=\"185EN.html\" target=\"_blank\">instructions</a> | ";
            }
            echo 
"<a href=\"$PHP_SELF?action=hiscore\">high scores</a> | ";
            echo 
"<a href=\"185info.html\">info</a></p>";
            echo 
"</body></html>";
            exit;
    }
}


// ****************************************************************************
// SOME FUNCTIONS

function check_max(){
    global 
$db;

    
$qry "select count(*) from dopewars where extract(epoch from now()-date)<60;";
    
$result $db->qry($qry);
    if (
$result[0]["count"] > MAXUSERS) {
        echo 
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
        echo 
"<html><title>dopewars</title><head><link rel=\"stylesheet\" href=\"default.css\" type=\"text/css\"></head><body><h2>dopewars - login</h2>";
            echo 
"<p>Too many users connected.<br>Please try to login again in a minute.</p><p><a href=\"$PHP_SELF?action=login\">back</a></p></body></html>";
        exit;
    }
}

function 
save_exit(){
    global 
$db$player$uid$onthemove$updatedate;


    
// calculate total
    
$player["cash"] = round($player["cash"]);
    
$player["bank"] = round($player["bank"]);
    
$player["debt"] = round($player["debt"]);

    
$player["total"] = $player["cash"] + $player["bank"] - $player["debt"];
    
reset ($player["drugs"]);
    while (list(
$drug$val) = each($player["drugs"])) {
        
$player["total"] += $player["drugprices"][$drug] * $val;
    }

    
// update database

    
$pl addslashes(serialize($player));
    
$qry "update dopewars set player='$pl', onthemove=$onthemove";
    
$qry .= ", score=" round($player["total"]);
    if (
$updatedate) {
        
$qry .= ", date=now()";
    }    
    
$qry .= " where name='$uid';\ncommit;";
    
$db->qry($qry);

    exit;
}

function 
save_player($uid$player$stopmoving=0) {
    global 
$db;

    
    
// calculate total
    
    
$player["total"] = $player["cash"] + $player["bank"] - $player["debt"];
    
reset ($player["drugs"]);
    while (list(
$drug$val) = each($player["drugs"])) {
        
$player["total"] += $player["drugprices"][$drug] * $val;
    }
    
    
// update database
    
    
$pl addslashes(serialize($player));
    
$qry "update dopewars set player='$pl'"
    if (
$stopmoving) {
        
$qry .= ", onthemove=FALSE";
    }
    
$qry .= ", score=" round($player["total"]);
    
$qry .= " where name='$uid';";
    
$db->qry($qry);
}

function 
banner($i$j) {
    
// this function is work in conjuction with click clock (http://drunkmenworkhere.org/187.php)
    // comment out, works on drunkmenworkhere.org only
    
global $language;

    if (
$i $j) {
        
$k $j;
        
$j $i;
        
$i $k;
    }

    
$foo 0;
    for (
$n=0$n<=$i$n++) {
        
$foo += $n;
    }
    
    
$foo $i*$foo + ($j $i) - 1;
    if (
$language == "NL") {
        
$foo += 28;
    }
    
$banners = @file("../data/dopewars_banners.txt");
    if (
$banners[$foo]!="\n" && $banners[$foo]!="") {
        
$b explode("\t"$banners[$foo]);
        echo 
"<p><a href=\"http://" trim($b[1]) . "\" target=\"_blank\"><img src=\"http://" trim($b[0]) . "\" border=\"0\" alt=\"play click clock to get your free banner here\"></a>";
    }
}

function 
check_life() {
    global 
$db$player$uid$str,$pass$PHP_SELF;
    
    if (
$player["life"] > 0) {
        if (
$player["life"] > 100) {
            
$player["life"] = 100;
        }
        return;
    } else {
        
report_snitches();
        
$qry "insert into dopescores (name, password, score) values ('" $player["name"] . "', '$pass', '" $player["total"] . "');";
        
$db->qry($qry);
        
$player "";
        
$qry "delete from dopewars where name = '$uid';\ncommit;";
        
$db->qry($qry);
        echo 
"<br>"$str["dead"];
        echo 
"<p><a href=\"$PHP_SELF?logout=1\">new game</a>";
        echo 
"</body></html>";
        exit;    
    }
}

function 
dealer_list() {
    global 
$db;

    
$qry "select id, name from dopewars order by name;";
    
$result $db->qry($qry);
    echo 
"<select name=\"dealer\" class=\"button\">";
    echo 
"<option></option>";
    while (list (
$key$val) = each($result)) {
        echo 
"<option value=\"{$val['id']}\">" htmlentities($val["name"]) . "</option>";
    }
    echo 
"</select>";
}

function 
report_snitches() {
        global 
$db$uid$player$str;

    
$player["fightreport"]["player"] = $uid;
    
$foo array_unique($player["currentsnitches"]);
    
$foo implode (", "$foo);
    if (
$foo) {
        
printf("<br>" $str["snitched"], $foo);
    }

    
$qry implode("','"array_unique($player["currentsnitches"]));
    
$qry "select * from dopewars where name in ('$qry') for update;";
    
$results $db->qry($qry);
    while (list (
$key$result) = each($results)) {    
        
$subject unserialize(stripslashes($result["player"]));
        
$subject["snitchreport"][] = $player["fightreport"];
        
save_player($result["name"], $subject);
    }
    
$player["currentsnitches"] = array();
    
$player["fightreport"] = array();
}

function 
lose_bitch($player) {
    global 
$drugs$guns;

    
// subtract proportional amount of drugs
    
reset ($player["drugs"]);
    while (list(
$key$val) = each($player["drugs"])) {
        
$num round($val/($player["bitches"] + 2));
        
$player["drugs"][$key] -= $num;
        
$player["space"] += $num;
    }

    
// remove guns
    
if (round(array_sum($player["guns"])/($player["bitches"] + 2))) {
        
reset ($player["guns"]);
        while (list(
$key$val) = each($player["guns"])) {
            if (
$val) {
                
$player["guns"][$key] -= 1;
                break;
            }
        }
    }

    
$player["bitches"]--;
    
$player["space"] -=10;

    return 
$player;
}

function 
printmenu($enabled 1) {
    global 
$places$str$currency$player$special$language$PHP_SELF;


    
// status table
    
    
echo "
    <div style=\"float:right; height:300px; width:200px; text-align:right;\"><table width=\"200\">"
;
    
    echo 
"<tr><th colspan=2>" $str["status"] . "</th></tr>";
    
    echo 
"<tr><td>" $str["name"] . ": " htmlentities($player["name"]) . "</td></tr>\n";
    echo 
"<tr><td>" $str["cash"] . ": $currency " $player["cash"] . "</td></tr>\n";
    echo 
"<tr><td>" $str["bank"] . ": $currency " $player["bank"] . "</td></tr>\n";
    echo 
"<tr><td>" $str["debt"] . ": $currency " $player["debt"] . "</td></tr>\n";
    echo 
"<tr><td>" $str["bitches"] . ": " $player["bitches"] . "</td></tr>\n";
    echo 
"<tr><td>" $str["life"] . ": " $player["life"] . "%</td></tr>\n";
    echo 
"<tr><td>" $str["space"] . ": " $player["space"] . "</td></tr>\n";
    echo 
"<tr><td>" $str["guns"] . ": " array_sum($player["guns"]) . "</td></tr>\n";
    
    
    echo 
"</table></div>";
    
    
    
// location menu table
    
    
echo "
    <div style=\"float:left; height:300px; width:200px; text-align:left; \"><table width=\"200\">"
;
    echo 
"<tr><th colspan=2>" $str["goto"] . "</th></tr>";
    while (list(
$key$val) = each($places)) {
        if (
$player["location"] == $key) {
            echo 
"<tr><td><b>&raquo; $val &laquo;</b></td></tr>\n";
        } else {
            if (
$enabled ) {
                echo 
"<tr><td><a href=\"$PHP_SELF?l=$key\" title=\"" $special[$key] . "\">$val</a></td></tr>\n";
            } else {
                echo 
"<tr><td>$val</td></tr>\n";
            }
        }
    }
    if (
$enabled) {
        echo 
"<tr><td><br><br><a href=\"$PHP_SELF?action=hiscore\" target=\"_blank\">high scores</a></td></tr>\n";
        echo 
"<tr><td><a href=\"185$language.html\" target=\"_blank\">" $str["instruct"] . "</a></td></tr>\n";
        echo 
"<tr><td><a href=\"$PHP_SELF?action=od&s=0\">" $str["od"] . "</a></td></tr>\n";
        echo 
"<tr><td><a href=\"$PHP_SELF?logout=1\">" $str["logout"] . "</a></td></tr>\n";
    } else {
        echo 
"<tr><td><br><br>high scores</td></tr>\n";
        echo 
"<tr><td>" $str["instruct"] . "</td></tr>\n";
        echo 
"<tr><td>" $str["od"] . "</td></tr>\n";
        echo 
"<tr><td>" $str["logout"] . "</td></tr>\n";
    }
    echo 
"</table></div>";
}

function 
print_header($reload 0) {
    global 
$PHP_SELF;

    echo 
"<html><head><title>dopewars</title><link rel=\"stylesheet\" href=\"default.css\" type=\"text/css\">";

    if (
$reload) {
        echo  
"<meta http-equiv=\"refresh\" content=\"3; URL=$PHP_SELF?reload=1\">";
    }

    echo 
"</head><body>\n";
}

// ****************************************************************************
// LANGUAGE STUFF

if ($language == "NL") {

    
$places = array(
        
"Spangen",
        
"Tussendijken",
        
"Dijkzigt/Cool",
        
"Oude Westen",
        
"Centraal Station",
        
"Tarwewijk",
        
"Hillesluis",
        
"Zuidplein");

    
$special = array(
        
=> "de woekeraar op de Mathenesserdijk",
        
=> "de hero&iuml;nehoeren op de Keileweg",
        
=> "de polikliniek",
        
=> "het GWK",
        
=> "de wapenhandelaar in de Millinxbuurt");

    
$drugs = array(
        array(
"name" => "LSD",        "min" => 1000,    "max"=> 4400,     "minmsg" => ""maxmsg=>"LSD is bezig aan een come-back in het party-circuit!"),
        array(
"name" => "coca&iuml;ne",    "min" => 15000,    "max"=> 29000,    "minmsg" => "Bolletjesslikkers hebben Rotterdam Airport ontdekt: coca&iuml;ne in overvloed.",    "maxmsg" => "In de haven is een lading Columbiaanse coke onderschept."),
        array(
"name" => "hero&iuml;ne",    "min" => 5500,    "max"=> 13000,    "minmsg" => "In de Pauluskerk wordt gratis methadon verstrekt, de hero&iuml;ne markt is ingestort.",    "maxmsg" => "Hero&iuml;ne-junks komen hier massaal naar toe, er is een tekort aan smack."),
        array(
"name" => "hash",        "min" => 480,    "max"=> 1280,    "minmsg" => "Een Marokkaans schip heeft grote hoeveelheden hash afgeleverd.",    "maxmsg" => "Een container maroc is door de douane vernietigd."),
        array(
"name" => "wiet",        "min" => 315,    "max"=> 890,    "minmsg" => "",    "maxmsg" => "Een hennepkwekerij is opgerold, de wietprijzen zijn omhooggeschoten!"),
        array(
"name" => "speed",    "min" => 90,    "max"=> 250,    "minmsg" => "",    "maxmsg" => ""),
        array(
"name" => "XTC",        "min" => 2800,    "max"=> 3700,    "minmsg" => "Een nieuw XTC laboratorium dumpt pillen voor weinig.""maxmsg" => "De politie heeft een XTC laboratorium ontmanteld."),
        array(
"name" => "valium",    "min" => 11,    "max"=> 60,    "minmsg" => "Rivaliserende dealers hebben een apotheek beroofd en verkopen goedkoop valium!",    "maxmsg" => ""),
        array(
"name" => "paddo's",    "min" => 630,    "max"=> 1300,    "minmsg" => "",    "maxmsg" => "In een proefproces zijn paddo's verboden, de prijzen schieten omhoog."),
        array(
"name" => "peyote",    "min" => 220,    "max"=> 700,    "minmsg" => "",    "maxmsg" => ""),
        array(
"name" => "PCP",        "min" => 1000,    "max"=> 2500,    "minmsg" => "",    "maxmsg" => ""));

    
$bitchactions = array (
        array(
"name" => "geile neukseks",    "price" => 20),
        array(
"name" => "spion",        "price" => 6500),
        array(
"name" => "verklikker",           "price" => 10000),
        array(
"name" => "drugskoerier",        "price" => 35000));

    
$fight = array("blijven staan""over geven""vluchten""schieten");    
        

    
$maxmsgs = array("%s is in de mode!""Een lading %s is onderschept, er is schaarste.""Verslaafden betalen belachelijke prijzen voor %s.");
    
$minmsgs = array("De markt wordt overspoeld met %s");

    
$str["nospace"]    = "Je hebt geen ruimte voor %s drugs.";
    
$str["nodrug"]    = "Je hebt helemaal niet  %s eenheden %s.";

    
$str["morespace"]    = "Je kunt nu 10 extra units meenemen.";

    
$str["doctor"]    = "Je zelf laten opereren kost &euro; %s.";
    
$str["recovered"]    = "Je bent kerngezond.";
    
$str["disease"]    = "Je hebt een SOA opgelopen.";
    
$str["mugged"]    = "Je zakken zijn gerold: je geld is weg!";
    
$str["ooh"]    = "'Ooh, was het ook goed voor jou?'";
    
$str["operate"]    = "opereren";

    
$str["nogunspace"]    = "Je kunt niet meer wapens dragen.";
    
$str["noguncash"]    = "Dit wapen is te duur.";
    
$str["nomoney"]    = "Je hebt daar geen geld voor.";
    
$str["sell"]    = "verkoop";
    
$str["buy"]    = "koop";
    
$str["available"]    = "markt:";
    
$str["carried"]        = "in bezit:";
    
$str["to"]    = "naar";
    
$str["at"]    = "bij";