<?php
// Dogs in the Vineyard online dice roller
// Copyright (c) 2008-2009 Lapo Luchini <lapo@lapo.it>, Marco Orlandi <noemon78@gmail.com>
// 
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
// 
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// Requirements: PHP 5 with PDO SQLite extension
// Flags can be found here: http://www.famfamfam.com/lab/icons/flags/famfamfam_flag_icons.zip

$baseURL 'http://dadi.lapo.it/';

header('Content-Type: text/html;charset=CP1252');
header('Content-Style-Type: text/css');
header('Content-Script-Type: text/javascript');
header("Cache-Control: max-age=60"); // cacheable for 1 minute
?>
<html>
<head>
  <title>Dadi online per il PbF CnV</title>
  <style type="text/css">
    body    { font-family: sans-serif; }
    td.flag { width: 16px; }
    td.time { font-size: 50%; color: gray; text-align: right; white-space: nowrap; }
    td.dice { color: blue; text-align: right; white-space: nowrap; }
    td.dice:hover { background: cyan; }
    td.user { font-size: 80%; font-style: italic; white-space: nowrap; }
    tr.links td { padding: 0px; font-family: monospace; white-space: nowrap; }
    /*input   { width: 100%; }*/
    span.label { width: 100px; }
  </style>
</head>
<body>
<form method="POST" action="?">
  <p><span class="label">Descrizione&nbsp;</span><input type="text" size="80" id="throw" name="throw"/></p>
  <p><span class="label">Dado&nbsp;</span><input type="text" size="50" name="dices" <?if (isset($_POST['dices'])) echo 'value="' $_POST['dices'] . '"'; else echo 'value="1d6"';?> /></p>
  <p><input type="submit" name="send" value="Lancia" id="btnLancia"></p>
</form>
<script type="text/javascript">
document.getElementById('throw').focus();
function show(node, time, dice) {
    if (node.links === 1)
    return;
    var tr = document.createElement('tr');
    tr.className = 'links';
    var td = document.createElement('td');
    td.colSpan = 2;
    tr.appendChild(td);
    td = document.createElement('td');
    td.colSpan = 3;
    td.innerHTML = '<table><tr><td>HTML:</td><td>&lt;a href="<?=$baseURL?>' + time + '">' + dice + '&lt;/a></td></tr>' +
    '<tr><td>BBCode:</td><td>[url=<?=$baseURL?>' + time + ']' + dice + '[/url]</td></tr></table>';
    tr.appendChild(td);
    var parent = node.parentNode;
    parent.parentNode.insertBefore(tr, parent.nextSibling);
    node.links = 1;
}
</script>
<?
$db 
= new PDO('sqlite:dadi.sqldb');
$db->exec('
  CREATE TABLE IF NOT EXISTS throw (
    time INTEGER PRIMARY KEY,
    text TEXT,
    value TEXT,
    ip TEXT
  );
'
);

if (isset(
$_POST['throw'])) {
    
// calcola valore
    
$val '';
    
$totDices 0;
    
$partssplit('[+, ]+'$_POST['dices']);
    foreach (
$parts as $dice) {
        if (
ereg ("^([1-9][0-9]*)d([1-9][0-9]*|F)$"$dice$regs)) {
            
$numDices=$regs[1];
            
$diceType=$regs[2];
            for ( 
$i 1$i <= $numDices$i++) {
                if (++
$totDices 20) {
                    echo 
"Si possono tirare un massimo di 20 dadi contemporaneamente.";
                    
$val '';
                    break;
                }
                if (
$diceType == 'F')
                    
$currValmt_rand(-11);
                else if (
$diceType 100) {
                    echo 
"Si possono tirare dadi con un massimo di 100 facce.";
                    
$val '';
                    break;
                } else
                    
$currValmt_rand(1$diceType);
                
$val .= "$currVal/$diceType ";
            }
        } else {
            echo 
"Formato Dado non valido: " $dice;
            
$val='';
            break;
        }
    }
    
    if (
$val) {
        
// inserisce in DB
        
$q $db->prepare('INSERT INTO throw (time, text, value, ip) VALUES (?, ?, ?, ?);');
        
$q->execute(array(time(), "$_POST[throw] ($_POST[dices])"trim($val), $_SERVER['REMOTE_ADDR']));
    }
}

function 
printDice($value, &$full, &$num) {
    
$i 0;
    foreach (
explode(' '$value) as $throw) {
    
$parts explode('/'$throw);
    
$vals["$parts[0].$i"] = $parts;
    ++
$i;
    }
    
ksort($vals);
    
$full '';
    
$num '';
    foreach (
$vals as $parts) {
        
$full .= "<span title='1d$parts[1]'>$parts[0]</span> ";
    
$num .= "$parts[0] ";
    }
    
$full trim($full);
    
$num trim($num);
}

$user1 = array('screaming''rowling''red''green''magenta''mad''crazy',
    
'pillaging''drunken''flapping''flickering''phase''massive',
    
'mutant''radioactive''transgenic''solid''liquid''venom',
    
'big''small''tiny''huge''strange');
$user2 = array('monkey''lion''otter''tiger''puma''zebra''turtle',
    
'platypus''griffyn''leviathan''leontophone''boa''aspid''sheep',
    
'snake''dragonfly''unicorn''squid''cobra''spider''mantis');

$q $db->prepare('SELECT * FROM throw WHERE time <= ? ORDER BY time DESC LIMIT 100;');
$q->execute(array(isset($_GET['time']) ? (int)$_GET['time'] : 0x7FFFFFFF));
$q->setFetchMode(PDO::FETCH_ASSOC);
echo 
"<table name='history'>\n";
while (
$row $q->fetch()) {
    
$flag '';
    
$cc strtolower(geoip_country_code_by_name($row['ip']));
    if (
$cc) {
    
$cn htmlspecialchars(geoip_country_name_by_name($row['ip']));
    
$flag '<img src="flags/' $cc '.png" alt="Flag of: ' $cn '" title="' $cn '"/>';
    }
    
$crc crc32($row['ip']);
    
$user $user1[$crc count($user1)] . ' ';
    
$user .= $user2[($crc 65537) % count($user2)];
    
//$val = ereg_replace('([1-9][0-9]*)/([1-9][0-9]*)', '<span title="1d\2">\1</span>', $row['value']);
    
printDice($row['value'], $full$num);
?>
  <tr>
    <td class="time"><a href="<?=$baseURL $row['time']?>"><?=strftime('%Y-%m-%d<br/>%H:%M:%S'$row['time'])?></a></td>
    <td class="flag"><?=$flag?></td>
    <td class="user"><?=$user?></td>
    <td class="dice" onclick="show(this, <?=$row['time']?>, '<?=$num?>')"><?=$full?></td>
    <td><?=htmlspecialchars($row['text'])?></td>
  </tr>
<?
}
echo 
"</table>\n";
?>
<div id="footer">Copyright &copy; 2008-<?=date('Y')?> <a href="mailto:lapo@lapo.it">Lapo Luchini</a> e <a href="mailto:noemon78@gmail.com">Marco Orlandi</a><br/>
<a href="dadi.phps">sorgenti</a> rilasciati come opensource sotto la <a href="http://it.wikipedia.org/wiki/Licenza_ISC">licenza ISC</a>.</div>
</body>
</html>