renamed class brisco to Room, some free funcs moved to static class funcs, split...
[brisk.git] / web / brisk.phh
index 2394625..2fc0462 100644 (file)
@@ -2,7 +2,7 @@
 /*
  *  brisk - brisk.phh
  *
- *  Copyright (C) 2006 matteo.nastasi@milug.org
+ *  Copyright (C) 2006-2007 matteo.nastasi@milug.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
  *
  */
 
-define( FTOK_PATH, "/var/lib/brisk");
-define(TABLES_N, 8);
+define(FTOK_PATH, "/var/lib/brisk");
+define(LEGAL_PATH, "/tmp/legal_brisk");
+define(PROXY_PATH, "/var/lib/brisk_proxy");
+define(TABLES_N, 12);
 define(PLAYERS_N, 3);
 define(MAX_POINTS, 5);
-define(MAX_PLAYERS, (PLAYERS_N * TABLES_N));
+define(MAX_PLAYERS, (20 + (PLAYERS_N * TABLES_N)));
+define(SHM_DIMS, (50000 * MAX_PLAYERS));
+// define(COMM_N, 6);
 define(COMM_N, 12);
 define(COMM_GEN_N, 50);
 define(SESS_LEN, 13);
@@ -37,10 +41,12 @@ define(NICKSERV, "<i>SERVER</i>");
 define(BRISK_DEBUG, FALSE);
 // define(DEBUGGING, "local");
 
+$G_false = FALSE;
+
 $G_all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
-$G_brisk_version = "0.5.0";
+$G_brisk_version = "0.8.2";
 
-$root_wellarr = Array ( 'Benvenuto in brisk (Ver. '.$G_brisk_version.').',
+$root_wellarr = Array ( 'Benvenuto in brisk (Ver. '.$G_brisk_version.'), <b>NOVITA\'</b>: nuovo layout che permette pi&ugrave; tavoli, pi&ugrave; tavoli.',
                         'Se vuoi iscriverti alla <a target="_blank" href="http://www.milug.org/cgi-bin/mailman/listinfo/ml-briscola">Mailing List</a>, cliccala!' );
 $table_wellarr = Array ( 'Benvenuto al tavolo. Se almeno tre giocatori non sbloccano l\'uscita cliccando il lucchetto, chi esce non pu&ograve; risedersi a un qualunque tavolo per '.floor(BAN_TIME/60).' minuti.');
 
@@ -50,6 +56,9 @@ $G_room_help= '
 <b>Descrizione</b><br>
 Questa &egrave; un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
 <a target=\\"_blank\\" href=\\"http://it.wikipedia.org/wiki/Briscola#Gioco_a_5\\">Wikipedia</a>; in breve &egrave; la variante con l\'asta prima sulla carta e poi sui punti.<br><br>
+<b>Configurazione del browser.</b><br>
+Occorre abilitare i cookies.<br>
+<br>
 <b>Uso del sito</b><br>
 Potete sedervi a un tavolo o rimanere in piedi.<br>
 Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la partita.<br>
@@ -58,8 +67,9 @@ Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la parti
 All\'inizio vengono distribuite le carte e parte l\'asta; per partecipare all\'asta, quando sar&agrave; il vostro turno, potrete scegliere se andare avanti o passare cliccando sulle icone corrispondenti. Se si arriva ai punti, scrivete nella textbox il vostro rilancio e cliccate PUNTI.<br><br>
 Chi vince l\'asta dovr&agrave; decidere il seme della carta scelta e inizier&agrave; la mano.<br>
 Per giocare le carte dovrete trascinarle nel quadrato al centro del vostro schermo.<br><br>
-Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno quadrato al centro del vostro schermo.<br><br>
+Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno al quadrato al centro del vostro schermo.<br><br>
 Durante la partita, se vorrete ricaricare la pagina, usate l\'apposito bottone \\"reload\\" in basso a destra.<br>
+Dopo che &egrave; iniziata una partita per uscirne dovete chiedere agli altri giocatori di sbloccarla cliccando sul lucchetto. Se non si segue questa prassi, una volta usciti, non vi potrete sedere a nessun tavolo per '.floor(BAN_TIME/60).' minuti.
 <dl>
 <dt><b>Comandi della chat</b>
 <dd><b>/nick <i>&lt;nuovo_nickname&gt;</i></b> - cambio di nickname
@@ -97,13 +107,13 @@ class Card {
   function Card($value, $stat, $owner)
   {
     $this->value = $value;
-    $this->stat  = $stat;
+    $this->stat  = $stat; // Card stat
     $this->owner = $owner;
   }
 
   function assign($stat,$owner)
   {
-    $this->stat  = $stat;
+    $this->stat  = $stat; // Card stat
     $this->owner = $owner;
   }
 
@@ -114,14 +124,14 @@ class Card {
 
   function play($x,$y)
   {
-    $this->stat = 'table';
+    $this->stat = 'table'; // Card stat
     $this->x = $x;
     $this->y = $y;
   }
 
   function take($newown)
   {
-    $this->stat = 'take';
+    $this->stat = 'take'; // Card stat
     $this->owner = $newown;
   }
 }
@@ -156,27 +166,37 @@ class Table {
 
   function Table() 
   {
-    $this->player    =   array();
-    $this->player_n  =   0;
-    $this->card      =  &$this->bunch_create();
-    $this->asta_pla  =   array(); // TRUE: in auction, FALSE: out of the auction
-    $this->asta_pla_n=  -1;
-    $this->asta_card =  -1;
-    $this->asta_pnt  =  -1;
-    $this->mult      =   1;
-    $this->points    =   array( );
-    $this->points_n  =   0;
-    $this->total     =   array( 0, 0, 0, 0, 0);
-    $this->asta_win  =  -1;
-    $this->briscola  =  -1;
-    $this->friend    =  -1;
-    $this->turn      =   0;
-    $this->old_reason = "";
-    $this->old_asta_pnt = -1;
-    $this->old_pnt      = -1;
-    $this->old_win   =  -1;
-    $this->old_friend=  -1;
-
+  }
+  
+  function &create() 
+  {
+    GLOBAL $G_false;
+
+    if (($thiz = new Table()) == FALSE)
+      return ($G_false);
+
+    $thiz->player    =   array();
+    $thiz->player_n  =   0;
+    $thiz->card      =  &$thiz->bunch_create();
+    $thiz->asta_pla  =   array(); // TRUE: in auction, FALSE: out of the auction
+    $thiz->asta_pla_n=  -1;
+    $thiz->asta_card =  -1;
+    $thiz->asta_pnt  =  -1;
+    $thiz->mult      =   1;
+    $thiz->points    =   array( );
+    $thiz->points_n  =   0;
+    $thiz->total     =   array( 0, 0, 0, 0, 0);
+    $thiz->asta_win  =  -1;
+    $thiz->briscola  =  -1;
+    $thiz->friend    =  -1;
+    $thiz->turn      =   0;
+    $thiz->old_reason = "";
+    $thiz->old_asta_pnt = -1;
+    $thiz->old_pnt      = -1;
+    $thiz->old_win   =  -1;
+    $thiz->old_friend=  -1;
+
+    return ($thiz);
   }
 
   function &bunch_create()
@@ -184,10 +204,11 @@ class Table {
     $ret = array();
 
     for ($i = 0 ; $i < 40 ; $i++) {
-      $ret[$i] = new Card($i, 'bunch', 'no_owner');
+      $ret[$i] =& new Card($i, 'bunch', 'no_owner');
     }
 
-    return ($ret);
+    $oret = &$ret;
+    return ($oret);
   }
 
   function bunch_make()
@@ -201,7 +222,7 @@ class Table {
 
     for ($i = 39 ; $i >= 0 ; $i--) {
       $rn = rand(0, $i);
-
+      
       if ($rn == 0)
        log_main("RND ZERO", "");
       
@@ -211,7 +232,7 @@ class Table {
       $this->card[$id]->assign('hand', $owner);
 
       $rest[$rn] = $rest[$i];
-      $pubbpos[$rn2] = $pubbpos[$i];
+      // $pubbpos[$rn2] = $pubbpos[$i];
     }
   }
 
@@ -233,7 +254,7 @@ class Table {
 
   function game_init(&$userarr)
   {
-    log_rd2($sess,"GSTART 4");
+    log_rd2("XXX", "GSTART 4");
 
     $this->gstart = ($this->mazzo+1) % PLAYERS_N;
     $this->bunch_make();
@@ -281,17 +302,17 @@ class Table {
     return ($this->player_n - 1);
   }
   
-  function user_rem(&$bri, &$user)
+  function user_rem(&$room, &$user)
   {
     $tabpos = $user->table_pos;
     
     /* verifico la consistenza dei dati */
-    if ($bri->user[$this->player[$tabpos]] == $user) {
+    if ($room->user[$this->player[$tabpos]] == $user) {
       
       /* aggiorna l'array dei giocatori al tavolo. */
       for ($i = $tabpos ; $i < $this->player_n-1 ; $i++) {
        $this->player[$i] = $this->player[$i+1];
-       $user_cur = &$bri->user[$this->player[$i]];
+       $user_cur = &$room->user[$this->player[$i]];
        $user_cur->table_pos = $i;
       }
       $this->player_n--;
@@ -343,6 +364,7 @@ class Table {
 class User {
   var $name;       // name of the user
   var $sess;       // session of the user
+  var $ip;         // ip of the user
   var $lacc;       // last access (for the cleanup)
   var $laccwr;     // last access (for the cleanup)
   var $bantime;    // timeout to temporary ban
@@ -357,42 +379,134 @@ class User {
   var $exitislock; // Player can exit from the table ?
   var $table;      // id of the current table (if in table state)
   var $table_pos;  // idx on the table
+  var $the_end;    // Flag to change the end of the session
+
+  function User() {
+  }
+
+  function &create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
+    GLOBAL $G_false;
+
+    if (($thiz = new User()) == FALSE)
+      return ($G_false);
+
+    $thiz->name  = $name;
+    $thiz->sess  = $sess;
+    $thiz->ip    = $ip;
+    $thiz->lacc   = time();
+    $thiz->laccwr = time();
+    $thiz->bantime = 0;
+    $thiz->stat  = $stat;
+    $thiz->subst  = $subst;
+    $thiz->step  = 1;
+    $thiz->trans_step  = -1;
+    $thiz->comm  = array();
+    $thiz->asta_card = -2;
+    $thiz->asta_pnt  = -1;
+    $thiz->handpt = -1;
+    $thiz->exitislock = TRUE;
+    
+    $thiz->table = $table;
+    
+    return ($thiz);
+  }
+
+  function stat_set($stat) {
+    $this->stat = "$stat";
+    
+    /*
+    if (validate_sess($this->sess)) {
+      $fp = fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
+      fwrite($fp, sprintf("%s\n",$this->stat));
+      fclose($fp);
+    }
+    */
+  }
+
+  function step_set($step) {
+    $this->step = $step;
+    
+    do {
+      if (validate_sess($this->sess) == FALSE)
+       break;
+      if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
+       break;
+      fwrite($fp, pack("l",$this->step), 4);
+      fclose($fp);
+
+      return (TRUE);
+    } while (0);
 
-  function User($name, $sess, $stat = "", $subst = "", $table = -1) {
-    $this->name  = $name;
-    $this->sess  = $sess;
-    $this->lacc   = time();
-    $this->laccwr = time();
-    $this->bantime = 0;
-    $this->stat  = $stat;
-    $this->subst  = $subst;
-    $this->step  = 1;
-    $this->trans_step  = -1;
-    $this->comm  = array();
-    $this->asta_card = -2;
-    $this->asta_pnt  = -1;
-    $this->handpt = -1;
-    $this->exitislock = TRUE;
-
-    $this->table = $table;
+    return (FALSE);
   }
+
+  function step_inc() {
+    $this->step++;
+    
+    if (validate_sess($this->sess)) {
+      $fp = fopen(PROXY_PATH."/".$this->sess.".step", 'w');
+      fwrite($fp, pack("l",$this->step), 4);
+      fclose($fp);
+
+      return (TRUE);
+    }
+    
+    return (FALSE);
+  }
+}
+
+function step_get($sess) {
+  $fp = FALSE;
+  $ct = 0;
+  do {
+    if (validate_sess($sess) == FALSE)
+      break;
+  $ct = 1;
+    if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
+      break;
+  $ct = 2;
+    if (($s = fread($fp, 4)) == FALSE)
+      break;
+  $ct = 3;
+    if (strlen($s) != 4)
+      break;
+  $ct = 4;
+    $arr = unpack('l', $s);
+    fclose($fp);
+
+    // log_rd2($sess, "A0: ".$arr[0]."  A1: ".$arr[1]);
+    return ($arr[1]);
+  } while (0);
+
+  if ($fp != FALSE)
+    fclose($fp);
+
+  log_rd2($sess, "STEP_GET: return false ".$ct);
+  return (FALSE);
+}
+
+function step_unproxy($sess) {
+  log_rd2($sess, "UNPROXY: ".PROXY_PATH."/".$sess.".step");
+  @unlink(PROXY_PATH."/".$sess.".step");
 }
 
-class brisco {
+
+class Room {
   var $user;
   var $table;
   var $comm; // commands for many people
   var $step; // current step of the comm array
   var $garbage_timeout;
 
-  function brisco () {
+  function Room () {
     $this->user = array();
 
     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
-      $this->user[$i] = new User("", "");
+      $this->user[$i] =& User::create("", "");
     }
+
     for ($i = 0 ; $i < TABLES_N ; $i++) 
-      $this->table[$i] = new Table();
+      $this->table[$i] =& Table::create();
     $this->garbage_timeout = 0;
   }
 
@@ -414,7 +528,9 @@ class brisco {
          if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
            log_auth($user_cur->sess, "Autologout session.");
            
+           $tmp_sess = $user_cur->sess;
            $user_cur->sess = "";
+           step_unproxy($tmp_sess);
            $user_cur->name = "";
            $user_cur->the_end = FALSE;
            
@@ -433,7 +549,7 @@ class brisco {
            $this->room_wakeup(&$user_cur);
            $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
            $user_cur->comm[$user_cur->step % COMM_N] .=  show_notify("<br>Sei stato inattivo per ".(EXPIRE_TIME_SMAMMA/60.0)." minuti. <br><br>Quindi ritorni tra i <b>Giocatori in piedi</b>.", 0, "torna ai tavoli", 400, 100);
-           $user_cur->step++;
+           $user_cur->step_inc();
          }
        }
       }
@@ -441,6 +557,9 @@ class brisco {
       
       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
     }
+
+    // BAN_IP_CLEAN
+
   }
 
 
@@ -462,12 +581,12 @@ class brisco {
        log_main("PREIMPOST", "INLOOP name: ".$user_cur->name);
 
        if ($user_cur != $user) {
-         $user_cur->stat = "room";
+         $user_cur->stat_set("room");
          $user_cur->subst = "sitdown";
          $user_cur->laccwr = $curtime;
        }
        else if ($user->sess != "") {
-         $user_cur->stat = "room";
+         $user_cur->stat_set("room");
          $user_cur->subst = "standup";
          $user_cur->laccwr = $curtime;
          $user_cur->table = -1;
@@ -475,7 +594,7 @@ class brisco {
       }
     }
     else {
-      $user->stat = "room";
+      $user->stat_set("room");
       $user->subst = "standup";
       $user->laccwr = $curtime;
     }
@@ -501,7 +620,7 @@ class brisco {
        $ret .= table_content($this, $user_cur, $table_idx);
        $ret .= standup_content($this, $user_cur);
        
-       $act_content = table_act_content(FALSE, 0, $e, $user->table);
+       $act_content = table_act_content(FALSE, 0, $table_idx, $user->table);
        $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
        
        
@@ -521,7 +640,7 @@ class brisco {
       }
       log_wr($user_cur->sess, "ROOM_WAKEUP: ".$ret);
       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
-      $user_cur->step++;
+      $user_cur->step_inc();
     }
   }
   
@@ -556,7 +675,7 @@ class brisco {
        $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
       }
       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
-      $user_cur->step++;
+      $user_cur->step_inc();
     }
 
     log_main("table_update", "post");
@@ -595,7 +714,7 @@ class brisco {
        }
       }
       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
-      $user_cur->step++;
+      $user_cur->step_inc();
     }
   }
 
@@ -607,14 +726,16 @@ class brisco {
     
     $user_mesg = substr($mesg,6);
     
-    $dt = date("H:i ",time());
+    $timecur = time();
+    
+    $dt = date("H:i ", $timecur);
     if (strncmp($user_mesg, "/nick ", 6) == 0) {
       log_main($user->sess, "chatt_send BEGIN");
 
       if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
          $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
          $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Il nickname deve contenere almeno una lettera o una cifra.");', $dt.NICKSERV, xcape($name_new));
-         $user->step++;
+         $user->step_inc();
 
          return;
       }
@@ -631,7 +752,7 @@ class brisco {
        if ($user_cur->name == $name_new) {
          $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
          $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Nickname <b>%s</b> gi&agrave; in uso.");', $dt.NICKSERV, xcape($name_new));
-         $user->step++;
+         $user->step_inc();
          break;
        }
       }
@@ -664,7 +785,7 @@ class brisco {
            $table = &$this->table[$user->table];
            
            $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
-           $user_cur->comm[$user_cur->step % COMM_N] = sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
+           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
                xcape($this->user[$table->player[($user_cur->table_pos)%PLAYERS_N]]->name),
                xcape($this->user[$table->player[($user_cur->table_pos+1)%PLAYERS_N]]->name),
                xcape($this->user[$table->player[($user_cur->table_pos+2)%PLAYERS_N]]->name),
@@ -673,7 +794,7 @@ class brisco {
            if ($user_cur == $user)
              $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>";', 
                                                                   xcape($user->name,ENT_COMPAT,"UTF-8"));
-           $user_cur->step++;
+           $user_cur->step_inc();
          }
        }
       }
@@ -692,21 +813,24 @@ class brisco {
        $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
        $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s","%s");',
                                                             $dt.xcape($user->name), xcape($user_mesg));
-       $user_cur->step++;
+       $user_cur->step_inc();
       }
+      log_legal($timecur, $user->sess, $user->name, 
+               ($user->stat == 'room' ? 'room' : 'table '.$user->table),$user_mesg);
     }
   }
 
   function &get_user($sess, &$idx)
   {
-    GLOBAL $PHP_SELF;
-    
-    if (strlen($sess) == SESS_LEN) {
+    GLOBAL $PHP_SELF, $G_false;
+
+    if (validate_sess($sess)) {
       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
        if (strcmp($sess, $this->user[$i]->sess) == 0) {
          // find it
          $idx = $i;
-         return ($this->user[$i]);
+         $ret = &$this->user[$i];
+         return ($ret);
        }
       }
       log_main($sess, sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
@@ -716,11 +840,12 @@ class brisco {
     else {
       log_main($sess, sprintf("get_user: Wrong strlen [%s]",$sess));
     }
-    return (FALSE);
+
+    return ($G_false);
   }
 
   /*
-   * function &add_user(&$bri, &$sess, &$idx, $name)
+   * function &add_user(&$room, &$sess, &$idx, $name, $ip)
    *
    * RETURN VALUE:
    *   if ($idx != -1 && ret == FALSE)  =>  duplicated nick
@@ -728,14 +853,16 @@ class brisco {
    *   if ($idx == -1 && ret == FALSE)  =>  no space left
    *   if (ret == TRUE)                 =>  SUCCESS
    */
-  function &add_user(&$sess, &$idx, $name)
+  function &add_user(&$sess, &$idx, $name, $ip)
   {
+    GLOBAL $G_false;
+
     $idx = -1;
     $idfree = -1;
     
     if (($name_new = validate_name($name)) == FALSE) {
       $idx = -2;
-      return (FALSE);
+      return ($G_false);
     }
 
     log_auth("XXX", sprintf("ARRIVA: [%s]", $sess));
@@ -763,6 +890,7 @@ class brisco {
 
     if ($idx != -1 && $i == MAX_PLAYERS) {
       /* SUCCESS */
+      $curtime = time();
       if ($sess == "") {
        $this->user[$idx]->sess = uniqid("");
        $sess = $this->user[$idx]->sess;
@@ -772,16 +900,19 @@ class brisco {
        $this->user[$idx]->sess = $sess;
       }
       $this->user[$idx]->name = $name_new;
-      $this->user[$idx]->stat = "room";
+      $this->user[$idx]->stat_set("room");
+      // MOP $this->user[$idx]->step_set(0);
       $this->user[$idx]->subst = "standup";
-      $this->user[$idx]->laccwr = time();
-      
+      $this->user[$idx]->lacc =   $curtime;
+      $this->user[$idx]->laccwr = $curtime;
+      $this->user[$idx]->bantime = 0;
+      $this->user[$idx]->ip = $ip;
       log_main("XXX", sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
       
       return ($this->user[$idx]);
     }
 
-    return (FALSE);
+    return ($G_false);
   }
   
   function standup_update(&$user)
@@ -800,13 +931,123 @@ class brisco {
        
        log_main("FROM STANDUP", "NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
        
-       $user_cur->step++;
+       $user_cur->step_inc();
       }
     }
   }
 
+  // Static functions
+  function &init_data()
+  {
+    $room =& new Room();
+    
+    return $room;
+  }
+  
 
-} // end class brisco
+  function &load_data() 
+  {
+    GLOBAL $G_false, $sess;
+    
+    if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
+      echo "FTOK FAILED";
+      exit;
+    }
+    
+    if ($shm = shm_attach($tok, SHM_DIMS)) {
+      $room = @shm_get_var($shm, $tok);
+      
+      log_only($sess, "bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
+      if (isset($room)) 
+       log_only($sess, "bri count ".count($room));
+      
+      if ($room == FALSE) {
+       log_only($sess, "INIT MAIN DATA");
+       
+       $room =& Room::init_data();
+       if (shm_put_var($shm, $tok, $room) == FALSE) {
+         log_only($sess, "PUT_VAR FALLITA ".strlen(serialize($room)));
+         log_only($sess, serialize($room));
+       }
+      }
+      
+      shm_detach($shm);
+      
+      $ret = &$room;
+      return ($ret);
+    }
+    
+    return ($G_false);
+  }
+  
+
+  function save_data(&$room) 
+  {
+    GLOBAL $sess;
+    
+    $ret =   FALSE;
+    $shm =   FALSE;
+    $isacq = FALSE;
+    
+    // var_dump($room);
+    
+    if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
+      return (FALSE);
+    
+    do {
+      $isacq = TRUE;
+      
+      if (($shm = shm_attach($tok, SHM_DIMS)) == FALSE)
+       break;
+      
+      // log_only($sess, "PUT_VAR DI ".strlen(serialize($room)));
+      if (shm_put_var($shm, $tok, $room) == FALSE) {
+       log_only($sess, "PUT_VAR FALLITA ".strlen(serialize($room)));
+       log_only($sess, serialize($room));
+       break;
+      }
+      // log_main("XXX", "QUI CI ARRIVA [".$room->user[0]->name."]");
+      $ret = TRUE;
+    } while (0);
+    
+    if ($shm)
+      shm_detach($shm);
+    
+    return ($ret);
+  }
+
+  function lock_data()
+  {
+    GLOBAL $sess; 
+    
+    //  echo "LOCK: ".FTOK_PATH."/main";
+    //  exit;
+    if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
+      echo "FTOK FAILED";
+      exit;
+    }
+    // echo "FTOK ".$tok."<br>";
+    if (($res = sem_get($tok)) == FALSE) {
+      echo "SEM_GET FAILED";
+      exit;
+    }
+    if (sem_acquire($res)) {   
+      log_only($sess, "LOCK");
+      return ($res);
+    }
+    else
+      return (FALSE);
+  }
+  
+  function unlock_data($res)
+  {
+    GLOBAL $sess; 
+    
+    log_only($sess, "UNLOCK");
+
+    return (sem_release($res));
+  }
+} // end class Room
 
 function make_seed()
 {
@@ -814,85 +1055,128 @@ function make_seed()
   return (float) $sec + ((float) $usec * 100000);
 }
 
+function log_only2($sess, $log) {
+  if (BRISK_DEBUG != TRUE)
+    return;
+  
+
+  if (($fp = @fopen("/tmp/brisk_only2.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
+}
+
+function log_only($sess, $log) {
+  if (BRISK_DEBUG != TRUE)
+    return;
+  
+
+  if (($fp = @fopen("/tmp/brisk_only.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
+}
+
 function log_main($sess, $log) {
   if (BRISK_DEBUG != TRUE)
     return;
 
-  $fp = fopen("/tmp/brisk_main.log", 'a');
-  fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
-  fclose($fp);
+  if (($fp = @fopen("/tmp/brisk_main.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
 }
 
 function log_rd($sess, $log) {
   if (BRISK_DEBUG != TRUE)
     return;
 
-  $fp = fopen("/tmp/brisk_rd.log", 'a');
-  fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
-  fclose($fp);
+  if (($fp = @fopen("/tmp/brisk_rd.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
 }
 
 function log_rd2($sess, $log) {
   if (BRISK_DEBUG != TRUE)
     return;
 
-  $fp = fopen("/tmp/brisk_rd2.log", 'a');
-  fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
-  fclose($fp);
+  if (($fp = @fopen("/tmp/brisk_rd2.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
 }
 
 function log_send($sess, $log) {
   if (BRISK_DEBUG != TRUE)
     return;
 
-  $fp = fopen("/tmp/brisk_send.log", 'a');
-  fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
-  fclose($fp);
+  if (($fp = @fopen("/tmp/brisk_send.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
 }
 
 function log_auth($sess, $log) {
   if (BRISK_DEBUG != TRUE)
     return;
 
-  $fp = fopen("/tmp/brisk_auth.log", 'a');
-  fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
-  fclose($fp);
+  if (($fp = @fopen("/tmp/brisk_auth.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
+    fclose($fp);
+  }
+}
+
+function log_lock($sess, $log) {
+  if (BRISK_DEBUG != TRUE)
+    return;
+
+  if (($fp = @fopen("/tmp/brisk_lock.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
+    fclose($fp);
+  }
 }
 
 function log_wr($sess, $log) {
   if (BRISK_DEBUG != TRUE)
     return;
 
-  $fp = fopen("/tmp/brisk_wr.log", 'a');
-  fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
-  fclose($fp);
+  if (($fp = @fopen("/tmp/brisk_wr.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
 }
 
 function log_load($sess, $log) {
   if (BRISK_DEBUG != TRUE)
     return;
 
-  $fp = fopen("/tmp/brisk_load.log", 'a');
-  fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
-  fclose($fp);
+  if (($fp = @fopen("/tmp/brisk_load.log", 'a')) != FALSE) {
+    fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
+    fclose($fp);
+  }
 }
 
-function init_data()
+function log_legal($timecur, $sess, $name, $where, $mesg) 
 {
-  $brisco = new brisco();
+  GLOBAL $_SERVER;
 
-  return $brisco;
+  if (($fp = @fopen(LEGAL_PATH, 'a')) != FALSE) {
+    /* Unix time | session | nickname | IP | where was | mesg */
+    fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $timecur, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
+    fclose($fp);
+  }
 }
 
-function lock_data()
+
+
+
+function lock_banlist()
 {
-       //  echo "LOCK: ".FTOK_PATH."/main";
-       //  exit;
-  if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
+  if (($tok = ftok(FTOK_PATH."/main", "L")) == -1) {
     echo "FTOK FAILED";
     exit;
   }
-  // echo "FTOK ".$tok."<br>";
   if (($res = sem_get($tok)) == FALSE) {
     echo "SEM_GET FAILED";
     exit;
@@ -900,68 +1184,14 @@ function lock_data()
   if (sem_acquire($res)) 
     return ($res);
   else
-    return (false);
+    return (FALSE);
 }
 
-function unlock_data($res)
+function unlock_banlist($res)
 {
   return (sem_release($res));
 }
 
-
-function &load_data() 
-{
-  if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
-    echo "FTOK FAILED";
-    exit;
-  }
-
-  if ($shm = shm_attach($tok,100000 * TABLES_N)) {
-    if(($bri = @shm_get_var($shm, $tok)) == false) {
-      log_main("XXX", "INIT MAIN DATA");
-
-      $bri = init_data();
-      shm_put_var($shm, $tok, $bri);
-    }
-    
-    shm_detach($shm);
-
-    return ($bri);
-  }
-
-  return (NULL);
-}
-
-
-function save_data(&$bri) 
-{
-  $ret =   FALSE;
-  $shm =   FALSE;
-  $isacq = FALSE;
-
-  // var_dump($bri);
-
-  if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
-    return (FALSE);
-
-  do {
-    $isacq = TRUE;
-    
-    if (($shm = shm_attach($tok,100000 * TABLES_N)) == FALSE)
-      break;
-    
-    if (shm_put_var($shm, $tok, $bri) == FALSE)
-      break;
-    // log_main("XXX", "QUI CI ARRIVA [".$bri->user[0]->name."]");
-    $ret = TRUE;
-  } while (0);
-  
-  if ($shm)
-    shm_detach($shm);
-     
-  return ($ret);
-}
-
 function table_act_content($isstanding, $sitted, $table, $cur_table)
 {
   $ret = "";
@@ -980,30 +1210,30 @@ function table_act_content($isstanding, $sitted, $table, $cur_table)
   return ($ret);
 }
 
-function table_content($bri, $user, $table_idx)
+function table_content($room, $user, $table_idx)
 {
   $content = "";
-
+  $ret = "";
   // TODO
   //
   //   Si possono usare i dati nella classe table
   //
 
   $sess = $user->sess;
-  $table = &$bri->table[$table_idx];
+  $table = &$room->table[$table_idx];
 
   if ($user->stat != 'room')
     return;
 
   for ($i = 0 ; $i < $table->player_n ; $i++) {
-    $user_cur = &$bri->user[$table->player[$i]];
+    $user_cur = &$room->user[$table->player[$i]];
 
     if ($user_cur == $user) 
        { $hilion = "<b>"; $hilioff = "</b>"; }
       else
        { $hilion = ""; $hilioff = ""; }
 
-    log_main($bri->user[$e]->name, sprintf("IN TABLE [%d]", $table_idx));
+    log_main($user_cur->name, sprintf("IN TABLE [%d]", $table_idx));
     
     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
   }
@@ -1017,7 +1247,7 @@ function table_content($bri, $user, $table_idx)
   return ($ret);
 }
 
-function standup_content(&$bri, $user)
+function standup_content(&$room, $user)
 {
   $ret = "";
   $content = "";
@@ -1026,7 +1256,7 @@ function standup_content(&$bri, $user)
     return;
 
   for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
-    if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
+    if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
       continue;
     $ct++;
   }
@@ -1034,20 +1264,20 @@ function standup_content(&$bri, $user)
   $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
 
   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
-    if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
+    if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
       continue;
 
 
-    if ($bri->user[$e]->subst == "standup") {
+    if ($room->user[$e]->subst == "standup") {
       if (($ct % 4) == 0) {
        $content .= '<tr>';
       }
-      if ($bri->user[$e] == $user) 
+      if ($room->user[$e] == $user) 
        { $hilion = "<b>"; $hilioff = "</b>"; }
       else
        { $hilion = ""; $hilioff = ""; }
 
-      $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($bri->user[$e]->name), $hilioff);
+      $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($room->user[$e]->name), $hilioff);
       if (($ct % 4) == 3) {
        $content .= '</tr>';
       }
@@ -1070,7 +1300,7 @@ function show_notify($text, $tout, $butt, $w, $h)
   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
 }
 
-function briscola_show($bri, $table, $user)
+function briscola_show($room, $table, $user)
 {
   $ptnadd = "";
   $ret = "";
@@ -1083,7 +1313,7 @@ function briscola_show($bri, $table, $user)
     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
   else 
     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
-                   xcape($bri->user[$table->player[$table->asta_win]]->name), $ptnadd);
+                   xcape($room->user[$table->player[$table->asta_win]]->name), $ptnadd);
 
   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
                  $table->asta_win);
@@ -1126,16 +1356,17 @@ function multoval($mult)
     return (sprintf("%d-plo", $mult));
 }
 
-function show_table_info(&$bri, &$table, $table_pos)
+function show_table_info(&$room, &$table, $table_pos)
 {
-  $user = &$bri->user[$table->player[$table_pos]];
+  $ret = "";
+  $user = &$room->user[$table->player[$table_pos]];
 
   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
   $noty = sprintf('<table class=\"points\"><tr><th></th>');
   
   // Names.
   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
-    $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($bri->user[$table->player[$i]]->name));
+    $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($room->user[$table->player[$i]]->name));
   $noty .= sprintf("</tr>");
 
   // Points.
@@ -1166,8 +1397,8 @@ function show_table_info(&$bri, &$table, $table_pos)
 
     if ($win != $fri) {
       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
-                      xcape($bri->user[$win]->name),
-                      xcape($bri->user[$fri]->name));
+                      xcape($room->user[$win]->name),
+                      xcape($room->user[$fri]->name));
       if ($table->old_pnt == 120) {
        $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
       }
@@ -1180,7 +1411,7 @@ function show_table_info(&$bri, &$table, $table_pos)
     }
     else {
       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
-                      xcape($bri->user[$win]->name));
+                      xcape($room->user[$win]->name));
       if ($table->old_pnt == 120) {
        $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
       }
@@ -1195,7 +1426,7 @@ function show_table_info(&$bri, &$table, $table_pos)
   if ($table->mazzo == $table_pos) 
     $noty .= "Fai <b>tu</b> il mazzo,";
   else {
-    $unam = xcape($bri->user[$table->player[$table->mazzo]]->name);
+    $unam = xcape($room->user[$table->player[$table->mazzo]]->name);
     $noty .= "Il mazzo a <b>$unam</b>,";
   }
 
@@ -1214,7 +1445,7 @@ function show_table_info(&$bri, &$table, $table_pos)
     $noty .= " tocca a <b>te</b> giocare.";
   }
   else {
-    $unam = xcape($bri->user[$table->player[$curplayer]]->name);
+    $unam = xcape($room->user[$table->player[$curplayer]]->name);
     $noty .= " tocca a <b>$unam</b> giocare.";
   }
 
@@ -1231,6 +1462,7 @@ function show_table_info(&$bri, &$table, $table_pos)
 function root_wellcome($user)
 {
   GLOBAL $root_wellarr;
+  $ret = "";
 
   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $root_wellarr[$i]));
@@ -1241,6 +1473,7 @@ function root_wellcome($user)
 function table_wellcome($user)
 {
   GLOBAL $table_wellarr;
+  $ret = "";
 
   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $table_wellarr[$i]));
@@ -1248,21 +1481,21 @@ function table_wellcome($user)
   return ($ret);
 }
 
-function show_room(&$bri, &$user)
+function show_room(&$room, &$user)
 {
-  $ret .= sprintf('gst.st = %d;',  $user->step);
+  $ret = sprintf('gst.st = %d;',  $user->step);
   $ret .= sprintf('stat = "%s";',  $user->stat);
 
   $ret .= root_wellcome($user);
   $ret .= sprintf('subst = "%s";', $user->subst);
   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
   for ($i = 0 ; $i < TABLES_N ; $i++) {
-    $ret .= table_content($bri, $user, $i);
+    $ret .= table_content($room, $user, $i);
     $act_content = table_act_content(($user->subst == 'standup'), 
-                                    $bri->table[$i]->player_n, $i, $user->table);
+                                    $room->table[$i]->player_n, $i, $user->table);
     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
   }
-  $ret .= standup_content($bri, $user);
+  $ret .= standup_content($room, $user);
   
   return ($ret);
 }
@@ -1279,14 +1512,14 @@ Examples                    of $is_transition, $is_again:
   from table: asta cmd e tutti passano:  TRUE, TRUE
   from table: fine partita:              TRUE, TRUE
  */
-function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
+function show_table(&$room, &$user, $sendstep, $is_transition, $is_again)
 {
   $table_idx = $user->table;
-  $table = &$bri->table[$table_idx];
+  $table = &$room->table[$table_idx];
   $table_pos = $user->table_pos;
 
   $ret = "table_init();";
-  $ret .= $table->exitlock_show(&$bri->user, $table_pos);
+  $ret .= $table->exitlock_show(&$room->user, $table_pos);
   if (!$is_again) {
     /* GENERAL STATUS */
     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
@@ -1297,15 +1530,15 @@ function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
     /* USERS INFO */
     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
-                   xcape($bri->user[$table->player[($table_pos)%PLAYERS_N]]->name),
-                   xcape($bri->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
-                   xcape($bri->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
-                   (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
-                   (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
+                   xcape($room->user[$table->player[($table_pos)%PLAYERS_N]]->name),
+                   xcape($room->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
+                   xcape($room->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
+                   (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
+                   (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
   }
   /* NOTIFY FOR THE CARD MAKER */
   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
-    $ret .= show_table_info(&$bri, &$table, $table_pos);
+    $ret .= show_table_info(&$room, &$table, $table_pos);
   }
   if (!$is_again) 
     $ret .= table_wellcome($user);
@@ -1329,7 +1562,7 @@ function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
              break;
          }
        }
-       log_rd($sess, "O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
+       log_rd($user->sess, "O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
        
        $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
                         $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
@@ -1393,7 +1626,7 @@ function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
     /* show users auction status */
     $showst = "";
     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
-      $user_cur = &$bri->user[$table->player[$i]];
+      $user_cur = &$room->user[$table->player[$i]];
       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
                         ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
     }
@@ -1439,7 +1672,7 @@ function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
       $ret .= "remark_off();";
     
     /* WHO CALL AND WATH */
-    $ret .= briscola_show($bri, $table, $user);
+    $ret .= briscola_show($room, $table, $user);
     
   }
   return ($ret);
@@ -1485,7 +1718,7 @@ function calculate_winner(&$table)
 
   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
     $table->card[$ontid[$i]]->owner = $cur_win;
-    $table->card[$ontid[$i]]->stat =  "take";
+    $table->card[$ontid[$i]]->stat =  "take"; // Card stat
   }
   return ($cur_win);
 }