Log refactoring, the_end field added, check to avoid multiple table_wakeup.
[brisk.git] / web / Obj / brisk.phh
1 <?php
2 /*
3  *  brisk - brisk.phh
4  *
5  *  Copyright (C) 2006-2007 matteo.nastasi@milug.org
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details. You should have received a
16  * copy of the GNU General Public License along with this program; if
17  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
18  * Suite 330, Boston, MA 02111-1307, USA.
19  *
20  */
21
22 define(FTOK_PATH, "/var/lib/brisk");
23 define(LEGAL_PATH, "/tmp/legal_brisk");
24 define(PROXY_PATH, "/var/lib/brisk_proxy");
25 define(TABLES_N, 12);
26 define(PLAYERS_N, 3);
27 define(MAX_POINTS, 5);
28 define(MAX_PLAYERS, (20 + (PLAYERS_N * TABLES_N)));
29 define(SHM_DIMS, (50000 * MAX_PLAYERS));
30 // define(COMM_N, 6);
31 define(COMM_N, 12);
32 define(COMM_GEN_N, 50);
33 define(SESS_LEN, 13);
34 define(STREAM_TIMEOUT, 20);
35 define(EXPIRE_TIME_RD, 180);
36 define(EXPIRE_TIME_SMAMMA, 360); 
37 // BAN_TIME da allineare anche in commons.js
38 define(BAN_TIME, 900); 
39 define(GARBAGE_TIMEOUT, 10);
40 define(NICKSERV, "<i>SERVER</i>");
41
42 define(DBG_ONL2, 0x0001);
43 define(DBG_ONLY, 0x0002);
44 define(DBG_MAIN, 0x0004);
45 define(DBG_READ, 0x0008);
46 define(DBG_REA2, 0x0010);
47 define(DBG_SEND, 0x0020);
48 define(DBG_LOCK, 0x0040);
49 define(DBG_WRIT, 0x0080);
50 define(DBG_LOAD, 0x0100);
51 define(DBG_AUTH, 0x0200);
52
53 define(BRISK_DEBUG, 0);
54 // define(DEBUGGING, "local");
55
56 $G_false = FALSE;
57
58 $G_all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
59 $G_brisk_version = "spawn-0.0.3";
60
61 $root_wellarr = Array ( 'Benvenuto in brisk (Ver. '.$G_brisk_version.'), <b>NOVITA\'</b>: nuovo layout che permette pi&ugrave; tavoli, pi&ugrave; tavoli.',
62                         'Se vuoi iscriverti alla <a target="_blank" href="http://www.milug.org/cgi-bin/mailman/listinfo/ml-briscola">Mailing List</a>, cliccala!' );
63 $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.');
64
65
66 $G_room_help= '
67 <div style=\\"text-align: left; padding: 8px;\\">
68 <b>Descrizione</b><br>
69 Questa &egrave; un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
70 <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>
71 <b>Configurazione del browser.</b><br>
72 Occorre abilitare i cookies.<br>
73 <br>
74 <b>Uso del sito</b><br>
75 Potete sedervi a un tavolo o rimanere in piedi.<br>
76 Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la partita.<br>
77 <br>
78 <b>Partita</b><br>
79 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>
80 Chi vince l\'asta dovr&agrave; decidere il seme della carta scelta e inizier&agrave; la mano.<br>
81 Per giocare le carte dovrete trascinarle nel quadrato al centro del vostro schermo.<br><br>
82 Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno al quadrato al centro del vostro schermo.<br><br>
83 Durante la partita, se vorrete ricaricare la pagina, usate l\'apposito bottone \\"reload\\" in basso a destra.<br>
84 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.
85 <dl>
86 <dt><b>Comandi della chat</b>
87 <dd><b>/nick <i>&lt;nuovo_nickname&gt;</i></b> - cambio di nickname
88 <dd>.. to be continue ..
89 </dl>
90 </div>
91 ';
92
93 $G_room_about= '<br>
94 <div id=\\"header\\" class=\\"header\\">
95   <img class=\\"nobo\\" src=\\"img/brisk_logo64.png\\">
96   briscola chiamata in salsa ajax
97 </div>
98 <br><b>version '.$G_brisk_version.'</b><br><br>
99 Copyright 2006-2007 <a href=\\"mailto:brisk@alternativeoutput.it\\">Matteo Nastasi</a> (aka mop)<br><br>';
100
101
102 function xcape($s)
103 {
104   $from = array (   '\\',     '@',        '|' );
105   $to   = array ( '\\\\', '&#64;', '&brvbar;' );
106
107   return (str_replace($from, $to, htmlentities($s,ENT_COMPAT,"UTF-8")));
108 }
109
110
111 class Card {
112   var $value; /* 0 - 39 card value */
113   var $stat;  /* 'bunch', 'hand', 'table', 'take' */
114   var $owner; /* (table position 0-4) */
115   // var $pos;   /* Pos in hand. */
116   var $x;     /* When played the X position on the table of the owner. */
117   var $y;     /* When played the Y position on the table of the owner. */
118
119   function Card($value, $stat, $owner)
120   {
121     $this->value = $value;
122     $this->stat  = $stat; // Card stat
123     $this->owner = $owner;
124   }
125
126   function assign($stat,$owner)
127   {
128     $this->stat  = $stat; // Card stat
129     $this->owner = $owner;
130   }
131
132   function setpos($pos)
133   {
134     $this->pos   = $pos;
135   }
136
137   function play($x,$y)
138   {
139     $this->stat = 'table'; // Card stat
140     $this->x = $x;
141     $this->y = $y;
142   }
143
144   function take($newown)
145   {
146     $this->stat = 'take'; // Card stat
147     $this->owner = $newown;
148   }
149 }
150
151 class Table {
152   var $player;
153   var $player_n;
154   var $card;
155   var $mazzo;
156   var $gstart;
157   var $turn;
158
159   var $asta_pla;
160   var $asta_pla_n;
161   var $asta_card;
162   var $asta_pnt;
163   
164   var $mult;
165   var $points;    // points array
166   var $points_n;  // number of row of points
167   var $total;
168
169   var $asta_win;
170   var $briscola;
171   var $friend;
172   
173   var $old_reason;
174   var $old_asta_pnt;
175   var $old_pnt;
176   var $old_win;
177   var $old_friend;
178
179   var $table_token;
180   var $table_start;
181
182   function Table() 
183   {
184   }
185   
186   function &create() 
187   {
188     GLOBAL $G_false;
189
190     if (($thiz = new Table()) == FALSE)
191       return ($G_false);
192
193     $thiz->player    =   array();
194     $thiz->player_n  =   0;
195     $thiz->card      =  &$thiz->bunch_create();
196     $thiz->asta_pla  =   array(); // TRUE: in auction, FALSE: out of the auction
197     $thiz->asta_pla_n=  -1;
198     $thiz->asta_card =  -1;
199     $thiz->asta_pnt  =  -1;
200     $thiz->mult      =   1;
201     $thiz->points    =   array( );
202     $thiz->points_n  =   0;
203     $thiz->total     =   array( 0, 0, 0, 0, 0);
204     $thiz->asta_win  =  -1;
205     $thiz->briscola  =  -1;
206     $thiz->friend    =  -1;
207     $thiz->turn      =   0;
208     $thiz->old_reason   = "";
209     $thiz->old_asta_pnt = -1;
210     $thiz->old_pnt      = -1;
211     $thiz->old_win      = -1;
212     $thiz->old_friend   = -1;
213
214     $thiz->table_token  = "";
215     $thiz->table_start  = 0;
216
217     return ($thiz);
218   }
219
220   function &clone(&$from)
221   {
222     GLOBAL $G_false;
223     
224     if (($thiz = new Table()) == FALSE)
225       return ($G_false);
226     
227     $thiz->player = array();
228     for ($i = 0 ; $i < $from->player_n ; $i++)
229       $thiz->player[$i] = $from->player[$i];
230     $thiz->player_n = $from->player_n;
231     $thiz->card = $from->card;
232     $thiz->mazzo = $from->mazzo; // REVIEW
233     $thiz->gstart = $from->gstart;
234     $thiz->turn = $from->turn;
235
236     $thiz->asta_pla = $from->asta_pla;
237     $thiz->asta_pla_n = $from->asta_pla_n;
238     $thiz->asta_card = $from->asta_card;
239     $thiz->asta_pnt = $from->asta_pnt;
240     
241     $thiz->mult = $from->mult;
242     $thiz->points = $from->points;
243     $thiz->points_n = $from->points_n;
244     $thiz->total = $from->total;
245     
246     $thiz->asta_win = $from->asta_win;
247     $thiz->briscola = $from->briscola;
248     $thiz->friend = $from->friend;
249     
250     $thiz->old_reason = $from->old_reason;
251     $thiz->old_asta_pnt = $from->old_asta_pnt;
252     $thiz->old_pnt = $from->old_pnt;
253     $thiz->old_win = $from->old_win;
254     $thiz->old_friend = $from->old_friend;
255
256     $thiz->table_token  = $from->table_token;
257     $thiz->table_start  = $from->table_start;
258
259     return ($thiz);
260   }
261   
262   function &spawn(&$from)
263   {
264     GLOBAL $G_false;
265     
266     if (($thiz =& new Table()) == FALSE)
267       return ($G_false);
268     
269     $thiz->player_n = $from->player_n;
270     $thiz->card = $from->card;
271     $thiz->mazzo = $from->mazzo;
272     $thiz->gstart = $from->gstart;
273     $thiz->turn = $from->turn;
274
275     $thiz->asta_pla = $from->asta_pla;
276     $thiz->asta_pla_n = $from->asta_pla_n;
277     $thiz->asta_card = $from->asta_card;
278     $thiz->asta_pnt = $from->asta_pnt;
279     
280     $thiz->mult = $from->mult;
281     $thiz->points = $from->points;
282     $thiz->points_n = $from->points_n;
283     $thiz->total = $from->total;
284     
285     $thiz->asta_win = $from->asta_win;
286     $thiz->briscola = $from->briscola;
287     $thiz->friend = $from->friend;
288     
289     $thiz->old_reason = $from->old_reason;
290     $thiz->old_asta_pnt = $from->old_asta_pnt;
291     $thiz->old_pnt = $from->old_pnt;
292     $thiz->old_win = $from->old_win;
293     $thiz->old_friend = $from->old_friend;
294
295     // players are rearranged in an dedicated array
296     $thiz->player = array();
297     for ($i = 0 ; $i < $from->player_n ; $i++)
298       $thiz->player[$i] = $i;
299
300     $thiz->table_token  = $from->table_token;
301     $thiz->table_start  = $from->table_start;
302
303     return ($thiz);
304   }
305   
306   function &bunch_create()
307   {
308     $ret = array();
309
310     for ($i = 0 ; $i < 40 ; $i++) {
311       $ret[$i] =& new Card($i, 'bunch', 'no_owner');
312     }
313
314     $oret = &$ret;
315     return ($oret);
316   }
317
318   function bunch_make()
319   {
320     $ct = array(0,0,0,0,0);
321     
322     mt_srand(make_seed());
323     
324     for ($i = 39 ; $i >= 0 ; $i--) 
325       $rest[$i] = $i;
326
327     for ($i = 39 ; $i >= 0 ; $i--) {
328       $rn = rand(0, $i);
329       
330       if ($rn == 0)
331         log_main("RND ZERO");
332       
333       $id = $rest[$rn];
334
335       $owner = $i % 5;
336       $this->card[$id]->assign('hand', $owner);
337
338       $rest[$rn] = $rest[$i];
339       // $pubbpos[$rn2] = $pubbpos[$i];
340     }
341   }
342
343   function init(&$userarr)
344   {
345     $this->mazzo    = rand(0,PLAYERS_N-1);
346     $this->points_n = 0;
347     $this->mult     = 1;
348     $this->old_win  =-1;
349     $this->old_reason = "";
350     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
351       $this->total[$i] = 0;
352       $user_cur = &$userarr[$this->player[$i]];
353       $user_cur->exitislock = TRUE;
354     }
355
356     log_main("table::init: ci siamo");
357   }
358
359   function game_init(&$userarr)
360   {
361     log_rd2("GSTART 4");
362
363     $this->gstart = ($this->mazzo+1) % PLAYERS_N;
364     $this->bunch_make();
365     
366     
367     $this->asta_pla_n = PLAYERS_N;
368     $this->asta_card = -1;
369     $this->asta_pnt  = 60;
370     $this->asta_win  = -1;
371     $this->briscola  = -1;
372     $this->friend    = -1;
373     $this->turn      =  0;
374     
375     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
376       $this->asta_pla[$i] = TRUE;
377       $user_cur = &$userarr[$this->player[$i]];
378       $user_cur->subst = 'asta';
379       $user_cur->asta_card = -2;
380       $user_cur->asta_pnt  = -1;
381       $user_cur->handpt = $this->hand_points($i);
382       // SEE function calculate_points(&$table)
383     }
384   }
385
386   function game_next()
387   {
388     $this->mazzo  = ($this->mazzo + 1) % PLAYERS_N;
389   }
390
391   function getPlayer($idx)
392   {
393     return ($this->player[$idx]);
394   }
395
396   function setPlayer($idx, $player)
397   {
398     $this->player[$idx] = $player;
399   }
400
401   function user_add($idx)
402   {
403     $this->player[$this->player_n] = $idx;
404     $this->player_n++;
405     
406     return ($this->player_n - 1);
407   }
408   
409   function user_rem(&$room, &$user)
410   {
411     $tabpos = $user->table_pos;
412     
413     /* verifico la consistenza dei dati */
414     if ($room->user[$this->player[$tabpos]] == $user) {
415       
416       /* aggiorna l'array dei giocatori al tavolo. */
417       for ($i = $tabpos ; $i < $this->player_n-1 ; $i++) {
418         $this->player[$i] = $this->player[$i+1];
419         $user_cur = &$room->user[$this->player[$i]];
420         $user_cur->table_pos = $i;
421       }
422       $this->player_n--;
423     }
424     else {
425       log_main("INCONSISTENCY ON TABLE.");
426     }
427   }
428
429   function hand_points($idx)
430   {
431     GLOBAL $G_all_points; 
432     
433     $tot = 0;
434     
435     for ($i = 0 ; $i < 40 ; $i++) {
436       if ($this->card[$i]->owner != $idx)
437         continue;
438
439       $ctt = $this->card[$i]->value % 10;
440       $tot += $G_all_points[$ctt];
441     }
442
443     return ($tot);
444   }
445
446   function exitlock_show(&$userarr, $table_pos)
447   {
448     $ct = $this->exitlock_calc(&$userarr, $table_pos);
449
450     $ret = sprintf('exitlock_show(%d, %s);', $ct, 
451                    ($userarr[$this->player[$table_pos]]->exitislock ? 'true' : 'false'));
452     return ($ret);
453   }
454
455   function exitlock_calc(&$userarr, $table_pos)
456   {
457     $ct = 0;
458
459     for ($i = 0 , $ct = 0 ; $i < PLAYERS_N ; $i++) {    
460       if ($userarr[$this->player[$i]]->exitislock == FALSE)
461         $ct++;
462     }
463
464     return ($ct);
465   }
466 } // End class Table
467   
468 class User {
469   var $name;       // name of the user
470   var $sess;       // session of the user
471   var $ip;         // ip of the user
472   var $lacc;       // last access (for the cleanup)
473   var $laccwr;     // last access (for the cleanup)
474   var $bantime;    // timeout to temporary ban
475   var $stat;       // status (outdoor, room, table, game, ...)
476   var $subst;      // substatus for each status   
477   var $step;       // step of the current status
478   var $trans_step; // step to enable transition between pages (disable == -1)
479   var $comm;       // commands array
480   var $asta_card;  // 
481   var $asta_pnt;   //
482   var $handpt;     // Total card points at the beginning of the current hand.
483   var $exitislock; // Player can exit from the table ?
484   var $table;      // id of the current table (if in table state)
485   var $table_pos;  // idx on the table
486   var $table_token;// token that identify a game on a table
487   var $the_end;    // Flag to change the end of the session
488
489   function User() {
490   }
491
492   function &create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
493     GLOBAL $G_false;
494
495     if (($thiz =& new User()) == FALSE)
496       return ($G_false);
497
498     $thiz->name  = $name;
499     $thiz->sess  = $sess;
500     $thiz->ip    = $ip;
501     $thiz->lacc   = time();
502     $thiz->laccwr = time();
503     $thiz->bantime = 0;
504     $thiz->stat  = $stat;
505     $thiz->subst  = $subst;
506     $thiz->step  = 1;
507     $thiz->trans_step  = -1;
508     $thiz->comm  = array();
509     $thiz->asta_card = -2;
510     $thiz->asta_pnt  = -1;
511     $thiz->handpt = -1;
512     $thiz->exitislock = TRUE;
513     
514     $thiz->table = $table;
515     $thiz->table_pos = -1;
516     $thiz->table_token = "";
517
518     return ($thiz);
519   }
520
521   function &clone(&$from)
522   {
523     GLOBAL $G_false;
524     
525     if (($thiz = new User()) == FALSE)
526       return ($G_false);
527     
528     $thiz->name       = $from->name;
529     $thiz->sess       = $from->sess;
530     $thiz->ip         = $from->ip;
531     $thiz->lacc       = $from->lacc;
532     $thiz->laccwr     = $from->laccwr;
533     $thiz->bantime    = $from->bantime;
534     $thiz->stat       = $from->stat;
535     $thiz->subst      = $from->subst;
536     $thiz->step       = $from->step;
537     $thiz->trans_step = $from->trans_step;
538     $thiz->comm       = array();
539
540     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
541     for ($i = $i_start ; $i < $from->step ; $i++) {
542       $ii = $i % COMM_N;
543       $thiz->comm[$ii] = $from->comm[$ii];
544     }
545     $thiz->asta_card  = $from->asta_card;
546     $thiz->asta_pnt   = $from->asta_pnt;
547     $thiz->handpt     = $from->handpt;
548     $thiz->exitislock = $from->exitislock;
549     $thiz->table      = $from->table;
550     $thiz->table_pos  = $from->table_pos;
551     $thiz->table_token = $from->table_token;
552     $thiz->the_end    = $from->the_end;
553
554     return ($thiz);
555   }
556   
557   function &spawn(&$from, $table, $table_pos)
558   {
559     GLOBAL $G_false;
560     
561     if (($thiz =& new User()) == FALSE)
562       return ($G_false);
563     
564     $thiz->name       = $from->name;
565     $thiz->sess       = $from->sess;
566     $thiz->ip         = $from->ip;
567     $thiz->lacc       = $from->lacc;
568     $thiz->laccwr     = $from->laccwr;
569     $thiz->bantime    = $from->bantime;
570     $thiz->stat       = $from->stat;
571     $thiz->subst      = $from->subst;
572     $thiz->step       = $from->step;
573     $thiz->trans_step = $from->trans_step;
574     $thiz->comm       = array();
575
576     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
577     for ($i = $i_start ; $i < $from->step ; $i++) {
578       log_wr("TRY PUSH:".$i);
579       $ii = $i % COMM_N;
580       $thiz->comm[$ii]   = $from->comm[$ii];
581     }
582     
583     $thiz->asta_card  = $from->asta_card;
584     $thiz->asta_pnt   = $from->asta_pnt;
585     $thiz->handpt     = $from->handpt;
586     $thiz->exitislock = $from->exitislock;
587     $thiz->the_end    = $from->the_end;
588
589     $thiz->table      = $table;
590     $thiz->table_pos  = $table_pos;
591     $thiz->table_token = $from->table_token;
592
593     return ($thiz);
594   }
595   
596   function stat_set($stat) {
597     log_main("sess: [".$this->sess. "] NEW STAT: [".$stat."]"); 
598     $this->stat = "$stat";
599     
600     /*
601     if (validate_sess($this->sess)) {
602       $fp = fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
603       fwrite($fp, sprintf("%s\n",$this->stat));
604       fclose($fp);
605     }
606     */
607   }
608
609   function step_set($step) {
610     $this->step = $step;
611     
612     do {
613       if (validate_sess($this->sess) == FALSE)
614         break;
615       if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
616         break;
617       fwrite($fp, pack("l",$this->step), 4);
618       fclose($fp);
619
620       return (TRUE);
621     } while (0);
622
623     return (FALSE);
624   }
625
626   function step_inc() {
627     $this->step++;
628     
629     if (validate_sess($this->sess)) {
630       $fp = fopen(PROXY_PATH."/".$this->sess.".step", 'w');
631       fwrite($fp, pack("l",$this->step), 4);
632       fclose($fp);
633
634       return (TRUE);
635     }
636     
637     return (FALSE);
638   }
639 }
640
641 function step_get($sess) {
642   $fp = FALSE;
643   $ct = 0;
644   do {
645     if (validate_sess($sess) == FALSE)
646       break;
647   $ct = 1;
648     if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
649       break;
650   $ct = 2;
651     if (($s = fread($fp, 4)) == FALSE)
652       break;
653   $ct = 3;
654     if (strlen($s) != 4)
655       break;
656   $ct = 4;
657     $arr = unpack('l', $s);
658     fclose($fp);
659
660     // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
661     return ($arr[1]);
662   } while (0);
663
664   if ($fp != FALSE)
665     fclose($fp);
666
667   log_rd2("STEP_GET: return false ".$ct);
668   return (FALSE);
669 }
670
671 function step_unproxy($sess) {
672   log_rd2("UNPROXY: ".PROXY_PATH."/".$sess.".step");
673   @unlink(PROXY_PATH."/".$sess.".step");
674 }
675
676
677 class Room {
678   var $user;
679   var $table;
680   var $comm; // commands for many people
681   var $step; // current step of the comm array
682   var $garbage_timeout;
683
684   function Room () {
685     $this->user = array();
686     $this->table = array();
687
688     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
689       $this->user[$i] =& User::create("", "");
690     }
691
692     for ($i = 0 ; $i < TABLES_N ; $i++) 
693       $this->table[$i] =& Table::create();
694     $this->garbage_timeout = 0;
695   }
696
697   function garbage_manager($force)
698   {
699     $ismod = FALSE;
700
701     log_rd2("garbage_manager START");
702
703     /* Garbage collector degli utenti in timeout */
704     $curtime = time();
705     if ($force || $this->garbage_timeout < $curtime) {
706       
707       // Before all align times with table timeout
708       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
709         $table_cur =& $this->table[$table_idx];
710         // if the table is complete and exists its shared mem we get the info about users lacc
711
712         if ($table_cur->player_n == PLAYERS_N) {
713           log_main("PLAYERS == N TABLE ".$table_idx);
714           
715           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
716             log_main("bin5 lock data success");
717             
718             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
719               if ($table_cur->table_token != $bri->table_token) {
720                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
721                 log_main("ERROR: not matching table_start. Room: ".$table_cur->table_start."  Table: ".$bri->table_start);
722                 $bri = FALSE;
723               }
724             }
725             
726             if ($bri != FALSE) {
727               log_main("garbage_manager: bri loaded successfully.");
728               $bri->garbage_manager(TRUE);
729               
730               $bri_table = &$bri->table[0];
731
732               // is the end of the table
733               if ($bri->the_end == TRUE) {
734                 /*
735                  *  DESTROY OF FINISHED TABLE && MOVE PLAYER TO ROOM AGAIN
736                  */
737                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
738                   // stat must be "table" by definition
739                   $user_cur =& $this->user[$table_cur->player[$i]];
740                   $bri_user =& $bri->user[$i];
741
742                   $user_cur->subst      = $bri_user->subst;
743                   $user_cur->step       = $bri_user->step;
744                   $user_cur->trans_step = $bri_user->step;
745                   $user_cur->lacc       = $bri_user->lacc;
746                   $user_cur->laccwr     = $bri_user->lacc;
747                 }
748               
749                 $this->room_join_wakeup(&$user_cur); 
750                 $table_cur->table_token = "";
751
752                 Briskin5::destroy_data($table_idx);
753               }
754               else {
755                 log_main("gm:: save_data");
756
757                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
758                   $this->user[$table_cur->player[$i]]->lacc = $bri->user[$i]->lacc;
759                 }
760               
761                 Briskin5::save_data(&$bri);
762               }
763             } // else if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
764             else {
765               log_main("ERROR: table ".$table_idx." unrecoverable join");
766             }
767           } // bri::lock_data
768         } //  if ($table_cur->player_n == PLAYERS_N) {
769       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
770     
771       log_rd2("out new loop.");
772                 
773       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
774         $user_cur = &$this->user[$i];
775         
776         log_rd2("User: ".$user_cur->name."  stat: ".$user_cur->stat."  subst: ".$user_cur->subst);
777           
778         if ($user_cur->sess == "") 
779           continue;
780         
781         if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) {
782           // Auto logout dell'utente
783           log_rd2("AUTO LOGOUT.".($user_cur->lacc + EXPIRE_TIME_RD)." curtime ".$curtime);
784           
785           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
786             log_auth($user_cur->sess, "Autologout session.");
787             
788             $tmp_sess = $user_cur->sess;
789             $user_cur->sess = "";
790             step_unproxy($tmp_sess);
791             $user_cur->name = "";
792             $user_cur->step = 0;
793             $user_cur->the_end = FALSE;
794             
795             log_rd2("AUTO LOGOUT.");
796             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
797               $this->room_wakeup(&$user_cur);
798             else if ($user_cur->subst == 'standup')
799               $this->room_outstandup(&$user_cur);
800             else
801               log_rd2("LOGOUT FROM WHAT ???");
802           }
803         }
804
805         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < $curtime) { // lo rimettiamo in piedi
806           if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
807             $this->room_wakeup(&$user_cur);
808             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
809             $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);
810             $user_cur->step_inc();
811           }
812         }
813       }
814       log_rd2("GARBAGE UPDATED!");
815       
816       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
817       $ismod = TRUE;
818     }
819
820     return ($ismod);
821   }
822
823
824   function room_wakeup(&$user)
825   {
826     $table_idx = $user->table;
827     $table = &$this->table[$table_idx];
828
829     log_main("WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
830
831     $curtime = time();
832
833     $from_table = ($user->stat == "table");
834     if ($from_table) {
835       log_main("WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
836
837       for ($i = 0 ; $i < $table->player_n ; $i++) {
838         $user_cur = &$this->user[$table->player[$i]];
839         log_main("PREIMPOST: INLOOP name: ".$user_cur->name);
840
841         if ($user_cur != $user) {
842           $user_cur->stat_set("room");
843           $user_cur->subst = "sitdown";
844           $user_cur->laccwr = $curtime;
845         }
846         else if ($user->sess != "") {
847           $user_cur->stat_set("room");
848           $user_cur->subst = "standup";
849           $user_cur->laccwr = $curtime;
850           $user_cur->table = -1;
851         }
852       }
853     }
854     else {
855       $user->stat_set("room");
856       $user->subst = "standup";
857       $user->laccwr = $curtime;
858     }
859     /* aggiorna l'array dei giocatori al tavolo. */
860     $table->user_rem(&$this, &$user);
861
862     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
863       $user_cur = &$this->user[$i];
864       if ($user_cur->sess == '' || $user_cur->stat != 'room')
865         continue;
866       
867       log_main("VALORI: name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
868
869       $ret = "gst.st = ".($user_cur->step+1)."; ";
870       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
871         $ret .= 'gst.st_loc++; the_end=true; window.onunload = null; document.location.assign("index.php");|';
872         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
873         log_main("DOCUMENT.index.php: from table");
874       }
875       else if ($user_cur->stat == "room") {
876         log_main("DOCUMENT.index.php: from table");
877
878         $ret .= table_content($this, $user_cur, $table_idx);
879         $ret .= standup_content($this, $user_cur);
880         
881         $act_content = table_act_content(FALSE, 0, $table_idx, $user->table);
882         $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
883         
884         
885         if ($user_cur == $user) {
886           // set the new status 
887           $ret .=  'subst = "standup"; ';
888           // clean the action buttons in other tables
889           for ($e = 0 ; $e < TABLES_N ; $e++) {
890             if ($this->table[$e]->player_n < PLAYERS_N)
891               $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, table_act_content(TRUE, 0, $e, $user->table));
892           }
893         }
894         else {
895           $act_content = table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table);
896           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
897         }
898       }
899       log_wr("ROOM_WAKEUP: ".$ret);
900       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
901       $user_cur->step_inc();
902     }
903   }
904
905   function room_join_wakeup(&$user, $update_lacc = FALSE)
906   {
907     $table_idx = $user->table;
908     $table = &$this->table[$table_idx];
909     
910     log_main("JOIN_WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
911
912     $curtime = time();
913     $user_wup = array();
914     $user_wup_n = 0;
915     log_main("JOIN WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
916     
917     for ($i = 0 ; $i < $table->player_n ; $i++) {
918       $user_cur = &$this->user[$table->player[$i]];
919       log_main("PREIMPOST INLOOP name: ".$user_cur->name);
920       if ($user_cur->sess != "") {
921         if ($update_lacc == TRUE) {
922           $user_cur->laccwr = $curtime;
923         }
924         log_main("cur: ".$user_cur->name."  subst: ".$user_cur->subst);
925         if ($user_cur->subst == "shutdowned") {
926           $user_cur->stat_set("room");
927           $user_cur->subst = "sitdown";
928         }
929         else if ($user_cur->subst == "shutdowner") {
930           $user_cur->stat_set("room");
931           $user_cur->subst = "standup";
932           $user_cur->table = -1;
933           $user_wup[$user_wup_n++] = &$user_cur;
934         }
935       }
936     }
937
938     for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
939       $table->user_rem(&$this, &$user_wup[$wup_idx]);
940
941     /* aggiorna l'array dei giocatori al tavolo. */
942
943     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
944       log_main("START LOOP");
945       $user_cur = &$this->user[$i];
946       if ($user_cur->sess == '' || $user_cur->stat != 'room') {
947         log_main("name: ".$user_cur->name."skip   subst: ".$user_cur->subst);
948         continue;
949       }
950
951       log_main("___");
952       log_main("VALORI name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
953
954       $ret = "gst.st = ".($user_cur->step+1)."; ";
955       if ($user_cur->stat == "room") {
956         log_main("DOCUMENT.index.php from table");
957
958         $ret .= table_content($this, $user_cur, $table_idx);
959         $ret .= standup_content($this, $user_cur);
960         
961         $act_content = table_act_content(FALSE, 0, $table_idx, $user_cur->table);
962         $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
963         
964         for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
965           if ($user_cur == $user_wup[$wup_idx]) 
966             break;
967
968         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
969
970         if ($wup_idx < $user_wup_n) {
971           log_main("JOIN_WAKEUP less");
972           // set the new status 
973           $ret .=  'subst = "standup"; ';
974           // clean the action buttons in other tables
975           for ($e = 0 ; $e < TABLES_N ; $e++) {
976             if ($this->table[$e]->player_n < PLAYERS_N)
977               $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, table_act_content(TRUE, 0, $e, $user_cur->table));
978           }
979           log_main("JOIN_WAKEUP end less");
980         }
981         else {
982           log_main("JOIN_WAKEUP more");
983           $act_content = table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table);
984           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
985           log_main("JOIN_WAKEUP end more");
986         }
987       }
988       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
989       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
990       $user_cur->step_inc();
991     }
992   }
993
994   function room_outstandup(&$user)
995   {
996     $this->room_sitdown(&$user, -1);
997   }
998   
999   function table_update(&$user)
1000   {
1001     log_main("table_update: pre - USER: ".$user->name);
1002
1003     $table_idx = $user->table;
1004
1005     if ($table_idx > -1) 
1006       $table = &$this->table[$table_idx];
1007     
1008     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1009       $ret = "";
1010       $user_cur = &$this->user[$i];
1011       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1012       continue;
1013       
1014       $ret = "gst.st = ".($user_cur->step+1)."; ";
1015       if ($table_idx > -1)
1016         $ret .= table_content($this, $user_cur, $table_idx);
1017       
1018       if ($user_cur == $user) {
1019         $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
1020       }
1021       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1022       $user_cur->step_inc();
1023     }
1024
1025     log_main("table_update: post");
1026   }
1027
1028   function room_sitdown(&$user, $table_idx)
1029   {
1030     log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1031
1032     if ($table_idx > -1) 
1033       $table = &$this->table[$table_idx];
1034     
1035     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1036       $ret = "";
1037       $user_cur = &$this->user[$i];
1038       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1039       continue;
1040       
1041       $ret = "gst.st = ".($user_cur->step+1)."; ";
1042       if ($table_idx > -1)
1043       $ret .= table_content($this, $user_cur, $table_idx);
1044       $ret .= standup_content($this, $user_cur);
1045       
1046       if ($user_cur == $user) {
1047         $ret .=  'subst = "sitdown"; ';
1048         // clean the action buttons in other tables
1049         for ($e = 0 ; $e < TABLES_N ; $e++) {
1050           $act_content = table_act_content(FALSE, 0, $e, $user_cur->table);
1051           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, $act_content);
1052         }
1053       }
1054       else if ($table_idx > -1) {
1055         if ($table->player_n == PLAYERS_N) {
1056           $act_content = table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table);
1057           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
1058         }
1059       }
1060       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1061       $user_cur->step_inc();
1062     }
1063   }
1064
1065   function chatt_send(&$user, $mesg)
1066   {
1067     if ($user->stat == 'table') {
1068       $table = &$this->table[$user->table];
1069     }
1070     
1071     $user_mesg = substr($mesg,6);
1072     
1073     $timecur = time();
1074     
1075     $dt = date("H:i ", $timecur);
1076     if (strncmp($user_mesg, "/nick ", 6) == 0) {
1077       log_main("chatt_send BEGIN");
1078
1079       if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
1080           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1081           $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));
1082           $user->step_inc();
1083
1084           return;
1085       }
1086       $user_mesg = "COMMAND ".$user_mesg;
1087       // Search dup name
1088       // change
1089       // update local graph
1090       // update remote graphs
1091       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1092         $user_cur = &$this->user[$i];
1093         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1094         if ($user_cur->sess == '')
1095           continue;
1096         if ($user_cur->name == $name_new) {
1097           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1098           $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Nickname <b>%s</b> gi&agrave; in uso.");', $dt.NICKSERV, xcape($name_new));
1099           $user->step_inc();
1100           break;
1101         }
1102       }
1103       if ($i == MAX_PLAYERS) {
1104         $user->name = $name_new;
1105
1106       log_main("chatt_send start set");
1107         
1108
1109         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1110           log_main("chatt_send set loop");
1111           
1112           $user_cur = &$this->user[$i];
1113           if ($user_cur->sess == '')
1114             continue;
1115           if ($user_cur->stat == 'room') {
1116             if ($user->stat == 'room' && $user->subst == 'standup') {
1117               $this->standup_update(&$user);
1118             }
1119             else if ($user->stat == 'room' && $user->subst == 'sitdown' ||
1120                      $user->stat == 'table') {
1121               log_main("chatt_send pre table update");
1122
1123               $this->table_update(&$user);
1124
1125               log_main("chatt_send post table update");
1126             }
1127           }
1128           else if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
1129             $table = &$this->table[$user->table];
1130             
1131             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1132             $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1133                 xcape($this->user[$table->player[($user_cur->table_pos)%PLAYERS_N]]->name),
1134                 xcape($this->user[$table->player[($user_cur->table_pos+1)%PLAYERS_N]]->name),
1135                 xcape($this->user[$table->player[($user_cur->table_pos+2)%PLAYERS_N]]->name),
1136                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3)%PLAYERS_N]]->name)),
1137                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4)%PLAYERS_N]]->name)));
1138             if ($user_cur == $user)
1139               $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>";', 
1140                                                                    xcape($user->name,ENT_COMPAT,"UTF-8"));
1141             $user_cur->step_inc();
1142           }
1143         }
1144       }
1145     }
1146     else {
1147       for ($i = 0 ; $i < ($user->stat == 'room' ? MAX_PLAYERS : PLAYERS_N) ; $i++) {
1148         if ($user->stat == 'room') {
1149           $user_cur = &$this->user[$i];
1150           if ($user_cur->sess == '' || $user_cur->stat != 'room')
1151             continue;
1152         }
1153         else {
1154           $user_cur = &$this->user[$table->player[$i]];
1155         }
1156         
1157         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1158         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s","%s");',
1159                                                              $dt.xcape($user->name), xcape($user_mesg));
1160         $user_cur->step_inc();
1161       }
1162       log_legal($timecur, $user->sess, $user->name, 
1163                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$user_mesg);
1164     }
1165   }
1166
1167   function &get_user($sess, &$idx)
1168   {
1169     GLOBAL $PHP_SELF, $G_false;
1170
1171     if (validate_sess($sess)) {
1172       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1173         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1174           // find it
1175           $idx = $i;
1176           $ret = &$this->user[$i];
1177           return ($ret);
1178         }
1179       }
1180       log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1181       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1182       // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1183     }
1184     else {
1185       log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
1186     }
1187
1188     return ($G_false);
1189   }
1190
1191   /*
1192    * function &add_user(&$room, &$sess, &$idx, $name, $ip)
1193    *
1194    * RETURN VALUE:
1195    *   if ($idx != -1 && ret == FALSE)  =>  duplicated nick
1196    *   if ($idx == -2 && ret == FALSE)  =>  invalid name
1197    *   if ($idx == -1 && ret == FALSE)  =>  no space left
1198    *   if (ret == TRUE)                 =>  SUCCESS
1199    */
1200   function &add_user(&$sess, &$idx, $name, $ip)
1201   {
1202     GLOBAL $G_false;
1203
1204     $idx = -1;
1205     $idfree = -1;
1206     
1207     if (($name_new = validate_name($name)) == FALSE) {
1208       $idx = -2;
1209       return ($G_false);
1210     }
1211
1212     log_auth("XXX", sprintf("ARRIVA: [%s]", $sess));
1213     if (validate_sess($sess) == FALSE) 
1214       $sess = "";
1215
1216     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1217       /* free user ? */
1218       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1219         if ($idx == -1)
1220           $idx = $i;
1221       }
1222       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
1223         $idfree = $i;
1224       }
1225       if (strcmp($this->user[$i]->name, $name_new) == 0) {
1226         $idx = $i;
1227         break;
1228       }
1229     }
1230     if ($idx == -1)
1231       $idx = $idfree;
1232
1233     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1234
1235     if ($idx != -1 && $i == MAX_PLAYERS) {
1236       /* SUCCESS */
1237       $curtime = time();
1238       if ($sess == "") {
1239         $this->user[$idx]->sess = uniqid("");
1240         $sess = $this->user[$idx]->sess;
1241         
1242       }
1243       else {
1244         $this->user[$idx]->sess = $sess;
1245       }
1246       $this->user[$idx]->name = $name_new;
1247       $this->user[$idx]->stat_set("room");
1248       // MOP $this->user[$idx]->step_set(0);
1249       $this->user[$idx]->subst = "standup";
1250       $this->user[$idx]->lacc =   $curtime;
1251       $this->user[$idx]->laccwr = $curtime;
1252       $this->user[$idx]->bantime = 0;
1253       $this->user[$idx]->ip = $ip;
1254       log_main(sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1255       
1256       return ($this->user[$idx]);
1257     }
1258
1259     return ($G_false);
1260   }
1261   
1262   function standup_update(&$user)
1263   {
1264     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1265       $user_cur = &$this->user[$i];
1266       if ($user_cur->sess == '')
1267         continue;
1268
1269       log_main("STANDUP START: ".$user_cur->stat);
1270       
1271       if ($user_cur->stat == 'room') {
1272         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".standup_content($this, $user_cur);
1273         if ($user_cur == $user)
1274           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
1275         
1276         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1277         
1278         $user_cur->step_inc();
1279       }
1280     }
1281   }
1282
1283   // Static functions
1284   function &init_data()
1285   {
1286     $room =& new Room();
1287     
1288     return $room;
1289   }
1290   
1291
1292   function &load_data() 
1293   {
1294     GLOBAL $G_false, $sess;
1295     
1296     if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1297       echo "FTOK FAILED";
1298       exit;
1299     }
1300     
1301     if ($shm = shm_attach($tok, SHM_DIMS)) {
1302       $room = @shm_get_var($shm, $tok);
1303       
1304       log_only("bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
1305       if (isset($room)) 
1306         log_only("bri count ".count($room));
1307       
1308       if ($room == FALSE) {
1309         log_only("INIT MAIN DATA");
1310         
1311         $room =& Room::init_data();
1312         if (shm_put_var($shm, $tok, $room) == FALSE) {
1313           log_only("PUT_VAR FALLITA ".strlen(serialize($room)));
1314           log_only(serialize($room));
1315         }
1316       }
1317       
1318       shm_detach($shm);
1319       
1320       $ret = &$room;
1321       return ($ret);
1322     }
1323     
1324     return ($G_false);
1325   }
1326   
1327
1328   function save_data(&$room) 
1329   {
1330     GLOBAL $sess;
1331     
1332     $ret =   FALSE;
1333     $shm =   FALSE;
1334     $isacq = FALSE;
1335     
1336     // var_dump($room);
1337     
1338     if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
1339       return (FALSE);
1340     
1341     do {
1342       $isacq = TRUE;
1343       
1344       if (($shm = shm_attach($tok, SHM_DIMS)) == FALSE)
1345         break;
1346       
1347       // log_only("PUT_VAR DI ".strlen(serialize($room)));
1348       if (shm_put_var($shm, $tok, $room) == FALSE) {
1349         log_only("PUT_VAR FALLITA ".strlen(serialize($room)));
1350         log_only(serialize($room));
1351         break;
1352       }
1353       // log_main("QUI CI ARRIVA [".$room->user[0]->name."]");
1354       $ret = TRUE;
1355     } while (0);
1356     
1357     if ($shm)
1358       shm_detach($shm);
1359     
1360     return ($ret);
1361   }
1362
1363   function lock_data()
1364   {
1365     GLOBAL $sess; 
1366     
1367     //  echo "LOCK: ".FTOK_PATH."/main";
1368     //  exit;
1369     if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1370       echo "FTOK FAILED";
1371       exit;
1372     }
1373     // echo "FTOK ".$tok."<br>";
1374     if (($res = sem_get($tok)) == FALSE) {
1375       echo "SEM_GET FAILED";
1376       exit;
1377     }
1378     if (sem_acquire($res)) {   
1379       log_lock("LOCK room");
1380       return ($res);
1381     }
1382     else
1383       return (FALSE);
1384   }
1385   
1386   function unlock_data($res)
1387   {
1388     GLOBAL $sess; 
1389     
1390     log_lock("UNLOCK room");
1391
1392     return (sem_release($res));
1393   }
1394 } // end class Room
1395
1396 function make_seed()
1397 {
1398   list($usec, $sec) = explode(' ', microtime());
1399   return (float) $sec + ((float) $usec * 100000);
1400 }
1401
1402
1403 function log_only2($log) {
1404   if ((BRISK_DEBUG & DBG_ONL2) == 0)
1405     return;
1406   
1407   GLOBAL $sess;
1408
1409   if (isset($sess) == FALSE)
1410     $ssess = "XXXX";
1411   else
1412     $ssess = $sess;
1413       
1414
1415   //   if (($fp = @fopen("/tmp/brisk_only2.log", 'a')) != FALSE) {
1416   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1417     fwrite($fp, sprintf("ONL2: [%s] [%s]\n", $ssess, $log));
1418     fclose($fp);
1419   }
1420 }
1421
1422 function log_only($log) {
1423   if ((BRISK_DEBUG & DBG_ONLY) == 0)
1424     return;
1425   
1426   GLOBAL $sess;
1427
1428   if (isset($sess) == FALSE)
1429     $ssess = "XXXX";
1430   else
1431     $ssess = $sess;
1432       
1433
1434   //  if (($fp = @fopen("/tmp/brisk_only.log", 'a')) != FALSE) {
1435   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1436     fwrite($fp, sprintf("ONLY: [%s] [%s]\n", $ssess, $log));
1437     fclose($fp);
1438   }
1439 }
1440
1441 function log_main($log) {
1442   if ((BRISK_DEBUG & DBG_MAIN) == 0)
1443     return;
1444   
1445   GLOBAL $sess;
1446
1447   if (isset($sess) == FALSE)
1448     $ssess = "XXXX";
1449   else
1450     $ssess = $sess;
1451       
1452
1453   //  if (($fp = @fopen("/tmp/brisk_main.log", 'a')) != FALSE) {
1454   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1455     fwrite($fp, sprintf("MAIN: [%s] [%s]\n", $ssess, $log));
1456     fclose($fp);
1457   }
1458 }
1459
1460 function log_rd($log) {
1461   if ((BRISK_DEBUG & DBG_READ) == 0)
1462     return;
1463   
1464   GLOBAL $sess;
1465
1466   if (isset($sess) == FALSE)
1467     $ssess = "XXXX";
1468   else
1469     $ssess = $sess;
1470       
1471
1472   //  if (($fp = @fopen("/tmp/brisk_rd.log", 'a')) != FALSE) {
1473   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1474     fwrite($fp, sprintf("READ: [%s] [%s]\n", $ssess, $log));
1475     fclose($fp);
1476   }
1477 }
1478
1479 function log_rd2($log) {
1480   if ((BRISK_DEBUG & DBG_REA2) == 0)
1481     return;
1482   
1483   GLOBAL $sess;
1484
1485   if (isset($sess) == FALSE)
1486     $ssess = "XXXX";
1487   else
1488     $ssess = $sess;
1489       
1490
1491   //  if (($fp = @fopen("/tmp/brisk_rd2.log", 'a')) != FALSE) {
1492   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1493     fwrite($fp, sprintf("REA2: [%s] [%s]\n", $ssess, $log));
1494     fclose($fp);
1495   }
1496 }
1497
1498 function log_send($log) {
1499   if ((BRISK_DEBUG & DBG_SEND) == 0)
1500     return;
1501   
1502   GLOBAL $sess;
1503
1504   if (isset($sess) == FALSE)
1505     $ssess = "XXXX";
1506   else
1507     $ssess = $sess;
1508       
1509
1510   //  if (($fp = @fopen("/tmp/brisk_send.log", 'a')) != FALSE) {
1511   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1512     fwrite($fp, sprintf("SEND: [%s] [%s]\n", $ssess, $log));
1513     fclose($fp);
1514   }
1515 }
1516
1517 function log_lock($log) {
1518   if ((BRISK_DEBUG & DBG_LOCK) == 0)
1519     return;
1520   
1521   GLOBAL $sess;
1522
1523   if (isset($sess) == FALSE)
1524     $ssess = "XXXX";
1525   else
1526     $ssess = $sess;
1527       
1528
1529   //  if (($fp = @fopen("/tmp/brisk_lock.log", 'a')) != FALSE) {
1530   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1531     fwrite($fp, sprintf("LOCK: [%s] [%s]\n", $ssess, $log));
1532     fclose($fp);
1533   }
1534 }
1535
1536 function log_wr($log) {
1537   if ((BRISK_DEBUG & DBG_WRIT) == 0)
1538     return;
1539   
1540   GLOBAL $sess;
1541
1542   if (isset($sess) == FALSE)
1543     $ssess = "XXXX";
1544   else
1545     $ssess = $sess;
1546       
1547
1548   //  if (($fp = @fopen("/tmp/brisk_wr.log", 'a')) != FALSE) {
1549   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1550     fwrite($fp, sprintf("WRIT: [%s] [%s]\n", $ssess, $log));
1551     fclose($fp);
1552   }
1553 }
1554
1555 function log_load($log) {
1556   if ((BRISK_DEBUG & DBG_LOAD) == 0)
1557     return;
1558   
1559   GLOBAL $sess;
1560
1561   if (isset($sess) == FALSE)
1562     $ssess = "XXXX";
1563   else
1564     $ssess = $sess;
1565       
1566
1567   //  if (($fp = @fopen("/tmp/brisk_load.log", 'a')) != FALSE) {
1568   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1569     fwrite($fp, sprintf("LOAD: [%s] [%s]\n", $ssess, $log));
1570     fclose($fp);
1571   }
1572 }
1573
1574 function log_auth($sess, $log) {
1575   if ((BRISK_DEBUG & DBG_AUTH) == 0)
1576     return;
1577
1578   //  if (($fp = @fopen("/tmp/brisk_auth.log", 'a')) != FALSE) {
1579   if (($fp = @fopen("/tmp/brisk.log", 'a')) != FALSE) {
1580     fwrite($fp, sprintf("AUTH: [%s] [%d] [%s]\n", $sess, time(), $log));
1581     fclose($fp);
1582   }
1583 }
1584
1585
1586 function log_legal($timecur, $sess, $name, $where, $mesg) 
1587 {
1588   GLOBAL $_SERVER;
1589
1590   if (($fp = @fopen(LEGAL_PATH, 'a')) != FALSE) {
1591     /* Unix time | session | nickname | IP | where was | mesg */
1592     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $timecur, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
1593     fclose($fp);
1594   }
1595 }
1596
1597
1598
1599
1600 function lock_banlist()
1601 {
1602   if (($tok = ftok(FTOK_PATH."/main", "L")) == -1) {
1603     echo "FTOK FAILED";
1604     exit;
1605   }
1606   if (($res = sem_get($tok)) == FALSE) {
1607     echo "SEM_GET FAILED";
1608     exit;
1609   }
1610   if (sem_acquire($res)) 
1611     return ($res);
1612   else
1613     return (FALSE);
1614 }
1615
1616 function unlock_banlist($res)
1617 {
1618   return (sem_release($res));
1619 }
1620
1621 function table_act_content($isstanding, $sitted, $table, $cur_table)
1622 {
1623   $ret = "";
1624
1625   if ($isstanding) {
1626     if ($sitted < PLAYERS_N) {
1627       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
1628     }
1629   }
1630   else {
1631     if ($table == $cur_table)
1632       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
1633     else
1634       $ret = "";
1635   }
1636   return ($ret);
1637 }
1638
1639 function table_content($room, $user, $table_idx)
1640 {
1641   $content = "";
1642   $ret = "";
1643   // TODO
1644   //
1645   //   Si possono usare i dati nella classe table
1646   //
1647
1648   $sess = $user->sess;
1649   $table = &$room->table[$table_idx];
1650
1651   if ($user->stat != 'room')
1652     return;
1653
1654   for ($i = 0 ; $i < $table->player_n ; $i++) {
1655     $user_cur = &$room->user[$table->player[$i]];
1656
1657     if ($user_cur == $user) 
1658         { $hilion = "<b>"; $hilioff = "</b>"; }
1659       else
1660         { $hilion = ""; $hilioff = ""; }
1661
1662     log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
1663     
1664     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1665   }
1666   /*
1667   for ( ; $i < PLAYERS_N ; $i++)
1668     $content .= "<br>";
1669   */
1670
1671   $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1672   
1673   return ($ret);
1674 }
1675
1676 function standup_content(&$room, $user)
1677 {
1678   $ret = "";
1679   $content = "";
1680
1681   if ($user->stat != 'room')
1682     return;
1683
1684   for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1685     if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
1686       continue;
1687     $ct++;
1688   }
1689
1690   $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1691
1692   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1693     if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
1694       continue;
1695
1696
1697     if ($room->user[$e]->subst == "standup") {
1698       if (($ct % 4) == 0) {
1699         $content .= '<tr>';
1700       }
1701       if ($room->user[$e] == $user) 
1702         { $hilion = "<b>"; $hilioff = "</b>"; }
1703       else
1704         { $hilion = ""; $hilioff = ""; }
1705
1706       $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($room->user[$e]->name), $hilioff);
1707       if (($ct % 4) == 3) {
1708         $content .= '</tr>';
1709       }
1710       $ct++;
1711     }
1712   }
1713   $content .= '</table>';
1714         
1715   $content2 = '<input class=\\"button\\" name=\\"logout\\" value=\\"Esco.\\" onclick=\\"window.onunload = null; act_logout();\\" type=\\"button\\">';
1716   $ret .= sprintf('$("standup").innerHTML = "%s";  $("esco").innerHTML = "%s";', 
1717                   $content, $content2);
1718
1719   return ($ret);
1720 }
1721
1722
1723 function show_notify($text, $tout, $butt, $w, $h)
1724 {
1725   log_main("SHOW_NOTIFY: ".$text);
1726   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
1727 }
1728
1729 function briscola_show($room, $table, $user)
1730 {
1731   $ptnadd = "";
1732   $ret = "";
1733
1734   if ($table->asta_card == 9) 
1735     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
1736   
1737   /* text of caller cell */
1738   if ($user->table_pos == $table->asta_win) 
1739     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
1740   else 
1741     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
1742                     xcape($room->user[$table->player[$table->asta_win]]->name), $ptnadd);
1743
1744   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1745                   $table->asta_win);
1746   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1747   $ret .= sprintf('$("caller").style.visibility = "visible";');
1748   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1749   $ret .= sprintf('$("astalascio").style.visibility = "";');
1750   $ret .= sprintf('$("asta").style.visibility = "hidden";');
1751   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1752   
1753   return ($ret);
1754 }
1755
1756
1757 function game_result($asta_pnt, $pnt)
1758 {
1759   if ($asta_pnt == 61) {
1760     if ($pnt > 60)
1761       return (1);
1762     else if ($pnt == 60)
1763       return (0);
1764     else
1765       return (-1);
1766   }
1767   else {
1768     if ($pnt >= $asta_pnt)
1769       return (1);
1770     else
1771       return (-1);
1772   }
1773 }
1774
1775 function multoval($mult)
1776 {
1777   if ($mult == 2)
1778     return ("doppio");
1779   else if ($mult == 4)
1780     return ("quadruplo");
1781   else
1782     return (sprintf("%d-plo", $mult));
1783 }
1784
1785 function show_table_info(&$room, &$table, $table_pos)
1786 {
1787   $ret = "";
1788   $user = &$room->user[$table->player[$table_pos]];
1789
1790   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1791   $noty = sprintf('<table class=\"points\"><tr><th></th>');
1792   
1793   // Names.
1794   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1795     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($room->user[$table->player[$i]]->name));
1796   $noty .= sprintf("</tr>");
1797
1798   // Points.
1799   log_main("show_table_info: pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1800
1801   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1802     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1803     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1804       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1805     $noty .= "</tr>";
1806   }
1807
1808   // Total points.
1809   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1810   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1811     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1812   $noty .= "</tr></table>";
1813
1814   if ($table->old_reason != "") {
1815     $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1816   }
1817
1818   if ($table->old_win != -1) {
1819     $win = $table->player[$table->old_win];
1820     $fri = $table->player[$table->old_friend];
1821
1822     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1823
1824     if ($win != $fri) {
1825       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
1826                        xcape($room->user[$win]->name),
1827                        xcape($room->user[$fri]->name));
1828       if ($table->old_pnt == 120) {
1829         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
1830       }
1831       else {
1832         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
1833                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1834                           'pi&ugrave; di 60'), $table->old_pnt,
1835                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1836       }
1837     }
1838     else {
1839       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
1840                        xcape($room->user[$win]->name));
1841       if ($table->old_pnt == 120) {
1842         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
1843       }
1844       else {
1845         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
1846                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1847                           'pi&ugrave; di 60'), $table->old_pnt,
1848                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1849       }
1850     }
1851   }
1852   if ($table->mazzo == $table_pos) 
1853     $noty .= "Fai <b>tu</b> il mazzo,";
1854   else {
1855     $unam = xcape($room->user[$table->player[$table->mazzo]]->name);
1856     $noty .= "Il mazzo a <b>$unam</b>,";
1857   }
1858
1859   if ($user->subst == 'asta') {
1860     if ($table->asta_win == -1)  // auction case
1861       $curplayer = $table->gstart % PLAYERS_N;
1862     else 
1863       $curplayer = $table->asta_win;
1864   }
1865   else if ($user->subst == 'game') {
1866     $curplayer = ($table->gstart + $table->turn) % PLAYERS_N;
1867   }
1868
1869
1870   if ($curplayer == $table_pos) {
1871     $noty .= " tocca a <b>te</b> giocare.";
1872   }
1873   else {
1874     $unam = xcape($room->user[$table->player[$curplayer]]->name);
1875     $noty .= " tocca a <b>$unam</b> giocare.";
1876   }
1877
1878   if ($table->mult > 1) {
1879     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
1880   }
1881   $noty .= "<hr><br>";
1882
1883   $ret .= show_notify($noty, 3000, "torna alla partita", 500, 400);
1884   
1885   return ($ret);
1886 }
1887
1888 function root_wellcome($user)
1889 {
1890   GLOBAL $root_wellarr;
1891   $ret = "";
1892
1893   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
1894     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $root_wellarr[$i]));
1895
1896   return ($ret);
1897 }
1898
1899 function table_wellcome($user)
1900 {
1901   GLOBAL $table_wellarr;
1902   $ret = "";
1903
1904   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
1905     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $table_wellarr[$i]));
1906
1907   return ($ret);
1908 }
1909
1910 function show_room(&$room, &$user)
1911 {
1912   $ret = sprintf('gst.st = %d;',  $user->step);
1913   $ret .= sprintf('stat = "%s";',  $user->stat);
1914
1915   $ret .= root_wellcome($user);
1916   $ret .= sprintf('subst = "%s";', $user->subst);
1917   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1918   for ($i = 0 ; $i < TABLES_N ; $i++) {
1919     $ret .= table_content($room, $user, $i);
1920     $act_content = table_act_content(($user->subst == 'standup'), 
1921                                      $room->table[$i]->player_n, $i, $user->table);
1922     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
1923   }
1924   $ret .= standup_content($room, $user);
1925   
1926   return ($ret);
1927 }
1928
1929
1930
1931 /* show table 
1932 is_transition (is from room to table ?)
1933 is_again      (is another game)
1934
1935 Examples                    of $is_transition, $is_again:
1936   from reload of the page:              FALSE, FALSE
1937   from sitdown in room:                  TRUE, FALSE
1938   from table: asta cmd e tutti passano:  TRUE, TRUE
1939   from table: fine partita:              TRUE, TRUE
1940  */
1941 function show_table(&$room, &$user, $sendstep, $is_transition, $is_again)
1942 {
1943   $table_idx = $user->table;
1944   $table = &$room->table[$table_idx];
1945   $table_pos = $user->table_pos;
1946
1947   $ret = "table_init();";
1948   $ret .= $table->exitlock_show(&$room->user, $table_pos);
1949   if (!$is_again) {
1950     /* GENERAL STATUS */
1951     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1952                      $sendstep, $user->stat, $user->subst, $table_pos);
1953
1954     log_rd(sprintf( 'SHOW_TABLE: gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1955                      $sendstep, $user->stat, $user->subst, $table_pos));
1956
1957     /* BACKGROUND */
1958     $ret .= "background_set();";
1959     
1960     /* USERS INFO */
1961     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1962     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1963                     xcape($room->user[$table->player[($table_pos)%PLAYERS_N]]->name),
1964                     xcape($room->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
1965                     xcape($room->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
1966                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
1967                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
1968   }
1969   /* NOTIFY FOR THE CARD MAKER */
1970   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1971     $ret .= show_table_info(&$room, &$table, $table_pos);
1972   }
1973   if (!$is_again) 
1974     $ret .= table_wellcome($user);
1975
1976   if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1977     $ret .= playsound("cow.mp3");
1978   }
1979
1980
1981   /* CARDS */
1982   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1983     $ret .= "|";
1984     
1985     for ($i = 0 ; $i < 8 ; $i++) {
1986       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
1987         $ct = 0;
1988         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1989           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
1990             $ct++;
1991             if ($ct == $i+1)
1992               break;
1993           }
1994         }
1995         log_rd("O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1996         
1997         $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
1998                          $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
1999                               $table->card[$o]->value : -1), 
2000                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
2001       }
2002     }    
2003   }
2004   else {
2005     $taked  = array(0,0,0,0,0);
2006     $inhand = array(0,0,0,0,0);
2007     $ontabl  = array(-1,-1,-1,-1,-1);
2008     $cards  = array();
2009
2010     for ($i = 0 ; $i < 40 ; $i++) {
2011       if ($table->card[$i]->stat == 'hand') {
2012         if ($table->card[$i]->owner == $table_pos) {
2013           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
2014         }
2015         $inhand[$table->card[$i]->owner]++;
2016       }
2017       else if ($table->card[$i]->stat == 'take') {
2018         log_main("Card taked: ".$table->card[$i]->value."OWN: ".$table->card[$i]->owner);
2019         $taked[$table->card[$i]->owner]++;
2020       }
2021       else if ($table->card[$i]->stat == 'table') {
2022         $ontabl[$table->card[$i]->owner] = $i;
2023       }
2024     }
2025     $logg = "\n";
2026     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2027       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
2028     }
2029     log_main("Stat table: ".$logg);
2030
2031     /* Set ours cards. */
2032     $oursarg = "";
2033     for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
2034       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
2035     for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
2036       $oursarg .= ($i == 0 ? "" : ", ")."-1";
2037     $ret .= sprintf('card_setours(%s);', $oursarg);
2038
2039     /* Dispose all cards */
2040     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2041       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
2042       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
2043                       $inhand[$i], $taked[$i]);
2044
2045       if ($ontabl[$i] != -1) {
2046         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
2047                         $table->card[$ontabl[$i]]->value, 
2048                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
2049       }
2050     }
2051   }
2052
2053   /* Show auction */
2054   if ($user->subst == 'asta') {
2055
2056     /* show users auction status */
2057     $showst = "";
2058     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2059       $user_cur = &$room->user[$table->player[$i]];
2060       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
2061                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
2062     }
2063     if (PLAYERS_N == 3)
2064         $showst .= ",-2,-2";
2065     $ret .= sprintf('show_astat(%s);', $showst);
2066
2067     if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
2068       /* show card chooser */
2069       $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
2070                       $table->asta_card);
2071     }
2072     else {
2073       /* show auction */
2074       if ($table_pos == ($table->gstart % PLAYERS_N) &&
2075           $table->asta_win == -1) 
2076         $ret .= sprintf('dispose_asta(%d,%d, %s);', 
2077                         $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
2078       else
2079         $ret .= sprintf('dispose_asta(%d,%d, %s);',
2080                         $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
2081     }
2082
2083     /* Remark */
2084     if ($table->asta_win == -1) { // auction case
2085       if ($table_pos == ($table->gstart % PLAYERS_N)) 
2086         $ret .= "remark_on();";
2087       else
2088         $ret .= "remark_off();";
2089     }
2090     else { // chooseed case
2091       if ($table_pos == $table->asta_win) 
2092         $ret .= "remark_on();";
2093       else
2094         $ret .= "remark_off();";
2095     }
2096   }
2097   else if ($user->subst == 'game') {
2098     /* HIGHLIGHT */
2099     if (($table->gstart + $table->turn) % PLAYERS_N == $table_pos) 
2100       $ret .= "is_my_time = true; remark_on();";
2101     else
2102       $ret .= "remark_off();";
2103     
2104     /* WHO CALL AND WATH */
2105     $ret .= briscola_show($room, $table, $user);
2106     
2107   }
2108   return ($ret);
2109 } // end function show_table(...
2110
2111 function calculate_winner(&$table)
2112 {
2113   $briontab = FALSE;
2114   $ontab = array();
2115   $ontid = array();
2116   $cur_win  =  -1;
2117   $cur_val  = 100;
2118   $cur_seed = $table->briscola - ($table->briscola % 10);
2119
2120   for ($i = 0 ; $i < 40 ; $i++) {
2121     if ($table->card[$i]->stat != "table")
2122       continue;
2123
2124     log_wr(sprintf("Card On table: [%d]", $i));
2125
2126     $v = $table->card[$i]->value; 
2127     $ontab[$table->card[$i]->owner] = $v;
2128     $ontid[$table->card[$i]->owner] = $i;
2129     /* se briscola setto il flag */
2130     if (($v - ($v % 10)) == $cur_seed)
2131       $briontab = TRUE;
2132   }
2133
2134   if ($briontab == FALSE) {
2135     $cur_win  = $table->gstart;
2136     $cur_val  = $ontab[$cur_win];
2137     $cur_seed = $cur_val - ($cur_val % 10);
2138   }
2139
2140   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2141     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
2142       if ($ontab[$i] < $cur_val) {
2143         $cur_val = $ontab[$i];
2144         $cur_win = $i;
2145       }
2146     }
2147   }
2148
2149   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2150     $table->card[$ontid[$i]]->owner = $cur_win;
2151     $table->card[$ontid[$i]]->stat =  "take"; // Card stat
2152   }
2153   return ($cur_win);
2154 }
2155
2156 function calculate_points(&$table)
2157 {
2158   GLOBAL $G_all_points; 
2159
2160   $pro = 0;
2161
2162   if ($table->asta_pnt == 60)
2163     $table->asta_pnt = 61;
2164
2165   $table->old_reason = "";
2166   $table->old_win = $table->asta_win;
2167   $table->old_friend = $table->friend;
2168   $table->old_asta_pnt = $table->asta_pnt;
2169
2170   for ($i = 0 ; $i < 40 ; $i++) {
2171     $ctt = $table->card[$i]->value % 10;
2172     $own = $table->card[$i]->owner;
2173     if ($own == $table->asta_win || $own == $table->friend) 
2174       $pro += $G_all_points[$ctt];
2175   }
2176
2177   log_wr(sprintf("PRO: [%d]", $pro));
2178
2179   
2180   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
2181     $table->points[$table->points_n % MAX_POINTS] = array();
2182     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
2183       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
2184     $table->points_n++;
2185     $table->old_pnt = $pro;
2186     $table->mult *= 2;
2187
2188     return;
2189   }
2190
2191   if ($pro >= $table->asta_pnt) 
2192     $sig = 1;
2193   else
2194     $sig = -1;
2195
2196   $table->points[$table->points_n % MAX_POINTS] = array();
2197   for ($i = 0 ; $i < 5 ; $i++) {
2198     if ($i == $table->asta_win) 
2199       $pt = ($i == $table->friend ? 4 : 2);
2200     else if ($i == $table->friend) 
2201       $pt = 1;
2202     else
2203       $pt = -1;
2204
2205     log_wr(sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
2206
2207     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
2208
2209     log_wr(sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
2210     
2211     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
2212     $table->total[$i] += $pt;
2213   }
2214   $table->points_n++;
2215   $table->old_pnt = $pro;
2216   $table->mult = 1;
2217 }
2218
2219 function validate_sess($sess) 
2220 {
2221   if (strlen($sess) == SESS_LEN) 
2222     return (TRUE);
2223   else
2224     return (FALSE);
2225 }
2226
2227 function validate_name($name) 
2228 {
2229   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
2230
2231   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2232     $c = $name_new[$i];
2233     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2234       return ($name_new);
2235   }
2236
2237   return (FALSE);
2238 }
2239
2240 function playsound($filename)
2241 {
2242   return (sprintf('playsound("flasou", "%s");', $filename));
2243 }
2244
2245 function secstoword($secs)
2246 {
2247   $mins = floor($secs / 60);
2248   $secs = $secs % 60;
2249   if ($mins > 0) 
2250     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
2251   
2252   if ($secs > 0)
2253     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
2254   
2255   return ($ret);
2256 }
2257
2258 ?>