state present added
[brisk.git] / web / Obj / brisk.phh
1 <?php
2 /*
3  *  brisk - brisk.phh
4  *
5  *  Copyright (C) 2006-2008 Matteo Nastasi
6  *                          mailto: nastasi@alternativeoutput.it 
7  *                                  matteo.nastasi@milug.org
8  *                          web: http://www.alternativeoutput.it
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details. You should have received a
19  * copy of the GNU General Public License along with this program; if
20  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
21  * Suite 330, Boston, MA 02111-1307, USA.
22  *
23  */
24
25
26 define(BRISK_CONF, "brisk.conf.pho");
27 define(FTOK_PATH, "/var/lib/brisk");
28 define(LEGAL_PATH, "/tmp/legal_brisk");
29 define(PROXY_PATH, "/var/lib/brisk_proxy");
30 define(TABLES_N, 32);
31 define(PLAYERS_N, 3);
32 define(MAX_POINTS, 5);
33 define(MAX_PLAYERS, (20 + (PLAYERS_N * TABLES_N)));
34 define(SHM_DIMS_MIN, (50000 + 10000 * TABLES_N + 15000 * MAX_PLAYERS));
35 define(SHM_DIMS_MAX, SHM_DIMS_MIN + 1048576);
36 define(SHM_DIMS_DLT, 65536);
37  
38 define(COMM_N, 18);
39 define(COMM_GEN_N, 50);
40
41 define(CHAT_N, 3);
42 define(CHAT_ILL_TIME, 6);
43
44 define(SESS_LEN, 13);
45 define(STREAM_TIMEOUT, 20);
46 define(EXPIRE_TIME_RD, 180);
47 define(EXPIRE_TIME_SMAMMA, 360); 
48 define(EXPIRE_TIME_WAG, 10);
49 define(WAKEUP_TIME, 12); 
50 // BAN_TIME da allineare anche in commons.js
51 define(BAN_TIME, 3600); 
52 define(GARBAGE_TIMEOUT, 10);
53 define(NICKSERV, "<i>BriskServ</i>");
54
55 define(DBG_ONL2, 0x0001);
56 define(DBG_ONLY, 0x0002);
57 define(DBG_MAIN, 0x0004);
58 define(DBG_READ, 0x0008);
59 define(DBG_REA2, 0x0010);
60 define(DBG_SEND, 0x0020);
61 define(DBG_LOCK, 0x0040);
62 define(DBG_WRIT, 0x0080);
63 define(DBG_LOAD, 0x0100);
64 define(DBG_AUTH, 0x0200);
65 define(DBG_CRIT, 0x0400);
66
67 define(BRISK_DEBUG, 0);
68
69 define(BRISK_SINGLE_DEBUG,0);
70 define(BRISK_SINGLE_SESS, "");
71 // define(DEBUGGING, "local");
72
73 require_once("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
74
75 $G_false = FALSE;
76
77 $G_all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
78 $G_brisk_version = "2.1.3 - trusty";
79
80 $root_wellarr = Array ( 'Brisk (Ver. '.$G_brisk_version.'), <b>NOVITA\'</b>: Garanzia dal sito e stato degli utenti (guarda l\'help).',
81                         'Se vuoi iscriverti alla <a target="_blank" href="http://www.milug.org/cgi-bin/mailman/listinfo/ml-briscola">Mailing List</a>, cliccala!' );
82 $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.');
83
84
85 $G_room_help= '
86 <div style=\\"text-align: left; padding: 8px;\\">
87 <b>Descrizione</b><br>
88 Questa รจ un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
89 <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>
90 <b>Configurazione del browser.</b><br>
91 Occorre abilitare i cookies.<br>
92 <br>
93 <b>Uso del sito</b><br>
94 Potete sedervi a un tavolo o rimanere in piedi.<br>
95 Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la partita.<br>
96 <br>
97 <b>Partita</b><br>
98 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>
99 Chi vince l\'asta dovr&agrave; decidere il seme della carta scelta e inizier&agrave; la mano.<br>
100 Per giocare le carte dovrete trascinarle nel quadrato al centro del vostro schermo.<br><br>
101 Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno al quadrato al centro del vostro schermo.<br><br>
102 Durante la partita, se vorrete ricaricare la pagina, usate l\'apposito bottone \\"reload\\" in basso a destra.<br>
103 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.
104 <dl>
105 <dt><b>Comandi della chat</b>
106 <dd><b>/nick <i>&lt;nuovo_nickname&gt;</i></b> - cambio di nickname
107 <dd><b>/tav <i>&lt;frase di invito&gt;</i></b> - invito per gli altri giocatori al tavolo dove si &egrave; seduti 
108 <dd><b>/st <i>&lt;stato&gt;</i></b> - cambia l\'icona associata al tuo user; <i>stato</i> pu&ograve; valere: \\"normale\\", \\"fuori\\", \\"pausa\\", \\"cibo\\", \\"cane\\", \\"lavoro\\" oppure \\"sigaretta\\"
109 <dd><b>/garante</b> - se si &egrave; autenticati permette di garantire per un utente fidato
110 </dl>
111 </div>
112 ';
113
114 //  
115
116 $G_room_about= '<br>
117 <div id=\\"header\\" class=\\"header\\">
118   <img class=\\"nobo\\" src=\\"img/brisk_logo64.png\\">
119   briscola chiamata in salsa ajax
120 </div>
121 <br><b>version '.$G_brisk_version.'</b><br><br>
122 Copyright 2006-2008 <a href=\\"mailto:brisk@alternativeoutput.it\\">Matteo Nastasi</a> (aka mop)<br><br>';
123
124
125 function xcape($s)
126 {
127   $from = array (   '\\',     '@',        '|' );
128   $to   = array ( '\\\\', '&#64;', '&brvbar;' );
129
130   return (str_replace($from, $to, htmlentities($s,ENT_COMPAT,"UTF-8")));
131 }
132
133 function xcapelt($s)
134 {
135   $from = array (   '\\',     '|' );
136   $to   = array ( '\\\\',   '\\|' );
137
138   return (str_replace($from, $to, $s));
139 }
140
141 class Card {
142   var $value; /* 0 - 39 card value */
143   var $stat;  /* 'bunch', 'hand', 'table', 'take' */
144   var $owner; /* (table position 0-4) */
145   // var $pos;   /* Pos in hand. */
146   var $x;     /* When played the X position on the table of the owner. */
147   var $y;     /* When played the Y position on the table of the owner. */
148
149   function Card($value, $stat, $owner)
150   {
151     $this->value = $value;
152     $this->stat  = $stat; // Card stat
153     $this->owner = $owner;
154   }
155
156   function assign($stat,$owner)
157   {
158     $this->stat  = $stat; // Card stat
159     $this->owner = $owner;
160   }
161
162   function setpos($pos)
163   {
164     $this->pos   = $pos;
165   }
166
167   function play($x,$y)
168   {
169     $this->stat = 'table'; // Card stat
170     $this->x = $x;
171     $this->y = $y;
172   }
173
174   function take($newown)
175   {
176     $this->stat = 'take'; // Card stat
177     $this->owner = $newown;
178   }
179 } // end class Card
180
181 class Table {
182   var $idx;
183   var $player;
184   var $player_n;
185   var $card;
186   var $mazzo;
187   var $gstart;
188   var $turn;
189   var $auth_only;
190
191   var $wag_own;
192   var $wag_com;
193   var $wag_tout;
194
195   var $asta_pla;
196   var $asta_pla_n;
197   var $asta_card;
198   var $asta_pnt;
199   
200   var $mult;
201   var $points;    // points array
202   var $points_n;  // number of row of points
203   var $total;
204
205   var $asta_win;
206   var $briscola;
207   var $friend;
208   
209   var $old_reason;
210   var $old_asta_pnt;
211   var $old_pnt;
212   var $old_win;
213   var $old_friend;
214
215   var $table_token;
216   var $table_start;
217
218   var $wakeup_time;
219
220   function Table() 
221   {
222   }
223   
224   function &create($idx) 
225   {
226     GLOBAL $G_false;
227
228     if (($thiz =& new Table()) == FALSE)
229       return ($G_false);
230
231     $thiz->idx       =   $idx;
232     $thiz->player    =   array();
233     $thiz->player_n  =   0;
234     $thiz->card      =   FALSE;
235     $thiz->asta_pla  =   array(); // TRUE: in auction, FALSE: out of the auction
236     $thiz->asta_pla_n=  -1;
237     $thiz->asta_card =  -1;
238     $thiz->asta_pnt  =  -1;
239     $thiz->mult      =   1;
240     
241     $thiz->auth_only =   FALSE;
242
243     $thiz->points    =   array( );
244     $thiz->points_n  =   0;
245     $thiz->total     =   array( 0, 0, 0, 0, 0);
246     $thiz->asta_win  =  -1;
247     $thiz->briscola  =  -1;
248     $thiz->friend    =  -1;
249     $thiz->turn      =   0;
250
251     $thiz->wag_own   =  NULL;
252     $thiz->wag_com   =  "";
253     $thiz->wag_tout   =  0;
254
255     $thiz->old_reason   = "";
256     $thiz->old_asta_pnt = -1;
257     $thiz->old_pnt      = -1;
258     $thiz->old_win      = -1;
259     $thiz->old_friend   = -1;
260
261     $thiz->table_token  = "";
262     $thiz->table_start  = 0;
263     
264     $thiz->wakeup_time = 0;
265
266     return ($thiz);
267   }
268
269   function &clone(&$from)
270   {
271     GLOBAL $G_false;
272     
273     if (($thiz =& new Table()) == FALSE)
274       return ($G_false);
275     
276     $thiz->idx = $from->idx;
277     $thiz->player = array();
278     for ($i = 0 ; $i < $from->player_n ; $i++)
279       $thiz->player[$i] = $from->player[$i];
280     $thiz->player_n = $from->player_n;
281     $thiz->card = $from->card;
282     $thiz->mazzo = $from->mazzo; // REVIEW
283     $thiz->gstart = $from->gstart;
284     $thiz->turn = $from->turn;
285
286     $thiz->auth_only =  $from->auth_only;
287
288     $thiz->wag_own   =  $from->wag_own;
289     $thiz->wag_com   =  $from->wag_com;
290     $thiz->wag_tout  =  $from->wag_taut;
291
292     $thiz->asta_pla = $from->asta_pla;
293     $thiz->asta_pla_n = $from->asta_pla_n;
294     $thiz->asta_card = $from->asta_card;
295     $thiz->asta_pnt = $from->asta_pnt;
296     
297     $thiz->mult = $from->mult;
298     $thiz->points = $from->points;
299     $thiz->points_n = $from->points_n;
300     $thiz->total = $from->total;
301     
302     $thiz->asta_win = $from->asta_win;
303     $thiz->briscola = $from->briscola;
304     $thiz->friend = $from->friend;
305     
306     $thiz->old_reason = $from->old_reason;
307     $thiz->old_asta_pnt = $from->old_asta_pnt;
308     $thiz->old_pnt = $from->old_pnt;
309     $thiz->old_win = $from->old_win;
310     $thiz->old_friend = $from->old_friend;
311
312     $thiz->table_token  = $from->table_token;
313     $thiz->table_start  = $from->table_start;
314
315     $thiz->wakeup_time = $from->wakeup_time;
316
317     return ($thiz);
318   }
319   
320   function &spawn(&$from)
321   {
322     GLOBAL $G_false;
323     
324     if (($thiz =& new Table()) == FALSE)
325       return ($G_false);
326     
327     $thiz->idx = $from->idx;
328     $thiz->player_n = $from->player_n;
329     $thiz->card = &$thiz->bunch_create();
330     $thiz->mazzo = $from->mazzo;
331     $thiz->gstart = $from->gstart;
332     $thiz->turn = $from->turn;
333
334     $thiz->auth_only =  $from->auth_only;
335
336     $thiz->wag_own = $from->wag_own;
337     $thiz->wag_com = $from->wag_com;
338     $thiz->wag_tout  =  $from->wag_taut;
339
340     $thiz->asta_pla = $from->asta_pla;
341     $thiz->asta_pla_n = $from->asta_pla_n;
342     $thiz->asta_card = $from->asta_card;
343     $thiz->asta_pnt = $from->asta_pnt;
344     
345     $thiz->mult = $from->mult;
346     $thiz->points = $from->points;
347     $thiz->points_n = $from->points_n;
348     $thiz->total = $from->total;
349     
350     $thiz->asta_win = $from->asta_win;
351     $thiz->briscola = $from->briscola;
352     $thiz->friend = $from->friend;
353     
354     $thiz->old_reason = $from->old_reason;
355     $thiz->old_asta_pnt = $from->old_asta_pnt;
356     $thiz->old_pnt = $from->old_pnt;
357     $thiz->old_win = $from->old_win;
358     $thiz->old_friend = $from->old_friend;
359
360     // players are rearranged in an dedicated array
361     $thiz->player = array();
362     for ($i = 0 ; $i < $from->player_n ; $i++)
363       $thiz->player[$i] = $i;
364
365     $thiz->table_token  = $from->table_token;
366     $thiz->table_start  = $from->table_start;
367
368     $thiz->wakeup_time = $from->wakeup_time;
369
370     return ($thiz);
371   }
372   
373   function &bunch_create()
374   {
375     $ret = array();
376
377     for ($i = 0 ; $i < 40 ; $i++) {
378       $ret[$i] =& new Card($i, 'bunch', 'no_owner');
379     }
380
381     $oret = &$ret;
382     return ($oret);
383   }
384
385   function wag_set(&$user, $mesg)
386   {
387     log_main("WAG_SET");
388
389     $this->wag_own  = &$user;
390     $this->wag_com  =  $mesg;
391     $this->wag_tout =  0;
392   }
393
394   function wag_reset($timeout)
395   {
396     log_main("WAG_RESET");
397
398     unset($this->wag_own);
399     $this->wag_own = NULL;
400     $this->wag_com  = "";
401     $this->wag_tout = $timeout;
402   }
403
404   function bunch_make()
405   {
406     $ct = array(0,0,0,0,0);
407     
408     mt_srand(make_seed());
409     
410     for ($i = 39 ; $i >= 0 ; $i--) 
411       $rest[$i] = $i;
412
413     for ($i = 39 ; $i >= 0 ; $i--) {
414       $rn = rand(0, $i);
415       
416       if ($rn == 0)
417         log_main("RND ZERO");
418       
419       $id = $rest[$rn];
420
421       $owner = $i % 5;
422       $this->card[$id]->assign('hand', $owner);
423
424       $rest[$rn] = $rest[$i];
425       // $pubbpos[$rn2] = $pubbpos[$i];
426     }
427   }
428
429   function init(&$userarr)
430   {
431     $this->mazzo    = rand(0,PLAYERS_N-1);
432     $this->points_n = 0;
433     $this->mult     = 1;
434     $this->old_win  =-1;
435     $this->old_reason = "";
436     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
437       $this->total[$i] = 0;
438       $user_cur = &$userarr[$this->player[$i]];
439       $user_cur->exitislock = TRUE;
440     }
441
442     log_main("table::init: ci siamo");
443   }
444
445   function game_init(&$userarr)
446   {
447     log_rd2("GSTART 4");
448
449     $this->gstart = ($this->mazzo+1) % PLAYERS_N;
450     $this->bunch_make();
451     
452     
453     $this->asta_pla_n = PLAYERS_N;
454     $this->asta_card = -1;
455     $this->asta_pnt  = 60;
456     $this->asta_win  = -1;
457     $this->briscola  = -1;
458     $this->friend    = -1;
459     $this->turn      =  0;
460     
461     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
462       $this->asta_pla[$i] = TRUE;
463       $user_cur = &$userarr[$this->player[$i]];
464       $user_cur->subst = 'asta';
465       $user_cur->asta_card = -2;
466       $user_cur->asta_pnt  = -1;
467       $user_cur->handpt = $this->hand_points($i);
468       // SEE function calculate_points(&$table)
469     }
470   }
471
472   function game_next()
473   {
474     $this->mazzo  = ($this->mazzo + 1) % PLAYERS_N;
475   }
476
477   function getPlayer($idx)
478   {
479     return ($this->player[$idx]);
480   }
481
482   function setPlayer($idx, $player)
483   {
484     $this->player[$idx] = $player;
485   }
486
487   function user_add($idx)
488   {
489     $this->player[$this->player_n] = $idx;
490     $this->player_n++;
491     
492     return ($this->player_n - 1);
493   }
494   
495   function user_rem(&$room, &$user)
496   {
497     $tabpos = $user->table_pos;
498     
499     /* verifico la consistenza dei dati */
500     if ($room->user[$this->player[$tabpos]] == $user) {
501       
502       /* aggiorna l'array dei giocatori al tavolo. */
503       for ($i = $tabpos ; $i < $this->player_n-1 ; $i++) {
504         $this->player[$i] = $this->player[$i+1];
505         $user_cur = &$room->user[$this->player[$i]];
506         $user_cur->table_pos = $i;
507       }
508       $this->player_n--;
509     }
510     else {
511       log_main("INCONSISTENCY ON TABLE.");
512     }
513   }
514
515   function hand_points($idx)
516   {
517     GLOBAL $G_all_points; 
518     
519     $tot = 0;
520     
521     for ($i = 0 ; $i < 40 ; $i++) {
522       if ($this->card[$i]->owner != $idx)
523         continue;
524
525       $ctt = $this->card[$i]->value % 10;
526       $tot += $G_all_points[$ctt];
527     }
528
529     return ($tot);
530   }
531
532   function exitlock_show(&$userarr, $table_pos)
533   {
534     $ct = $this->exitlock_calc(&$userarr, $table_pos);
535
536     $ret = sprintf('exitlock_show(%d, %s);', $ct, 
537                    ($userarr[$this->player[$table_pos]]->exitislock ? 'true' : 'false'));
538     return ($ret);
539   }
540
541   function exitlock_calc(&$userarr, $table_pos)
542   {
543     $ct = 0;
544
545     for ($i = 0 , $ct = 0 ; $i < PLAYERS_N ; $i++) {    
546       if ($userarr[$this->player[$i]]->exitislock == FALSE)
547         $ct++;
548     }
549
550     return ($ct);
551   }
552
553
554
555
556   //      $ret .= table_act_content(($user->subst == 'standup'), $this->table[$i]->player_n, $i, $user->table, 
557   //                              ($this->table[$i]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
558
559   // function act_content($isstanding, $sitted, $table, $cur_table, $allowed)
560   function act_content(&$user)
561   {
562     $ret = "";
563     $isstanding = ($user->subst == 'standup');
564     $sitted = $this->player_n;
565     $table = $this->idx;
566     $cur_table = $user->table;
567     $allowed = TRUE;
568
569     if ($isstanding) {
570       if ($sitted < PLAYERS_N) {
571         if ($this->auth_only) {
572           if ($user->flags & USER_FLAG_AUTH) 
573             $act = "sitreser";
574           else
575             $act = 'reserved';
576         }
577         else {
578           $act = 'sit';
579         }
580       }
581       else {
582         $act = 'none';
583       }
584     }
585     else {
586       if ($table == $cur_table)
587         $act = 'wake';
588       else
589         $act = 'none';
590     }
591     
592     if ($act != '')
593       $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
594     
595     return ($ret);
596   }
597
598
599 } // end class Table
600   
601
602 // User flags
603 define(USER_FLAG_AUTH, 0x02);
604
605 //   user status
606 define(USER_FLAG_S_NORM,  0x000); // done
607 define(USER_FLAG_S_PAU,   0x100); // done
608 define(USER_FLAG_S_OUT,   0x200); // done
609 define(USER_FLAG_S_DOG,   0x300); // done
610 define(USER_FLAG_S_EAT,   0x400); // done
611 define(USER_FLAG_S_WRK,   0x500); // done
612 define(USER_FLAG_S_SMK,   0x600); // done
613 define(USER_FLAG_S_EYE,   0x700); // done
614
615 define(USER_FLAG_S_ALL,   0xf00); // done
616
617 class User {
618   var $name;       // name of the user
619   var $sess;       // session of the user
620   var $ip;         // ip of the user
621   var $lacc;       // last access (for the cleanup)
622   var $laccwr;     // last access (for the cleanup)
623   var $bantime;    // timeout to temporary ban
624   var $stat;       // status (outdoor, room, table, game, ...)
625   var $subst;      // substatus for each status   
626   var $step;       // step of the current status
627   var $trans_step; // step to enable transition between pages (disable == -1)
628   var $comm;       // commands array
629   var $asta_card;  // 
630   var $asta_pnt;   //
631   var $handpt;     // Total card points at the beginning of the current hand.
632   var $exitislock; // Player can exit from the table ?
633   var $table;      // id of the current table (if in table state)
634   var $table_pos;  // idx on the table
635   var $table_token;// token that identify a game on a table
636   var $flags;      // Bitfield with: AUTHENTICATE: 0x02 
637   var $the_end;    // Flag to change the end of the session
638
639   var $chat_lst;      // Last chat line
640   var $chattime;      // Array of chat times
641   var $chat_cur;      // Current chat line number
642   var $chat_ban;      // Time for ban chat
643   var $chat_dlt;      // Delta t for ban
644   function User() {
645   }
646
647   function &create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
648     GLOBAL $G_false;
649
650     if (($thiz =& new User()) == FALSE)
651       return ($G_false);
652
653     $thiz->name  = $name;
654     $thiz->sess  = $sess;
655     $thiz->ip    = $ip;
656     $thiz->lacc   = time();
657     $thiz->laccwr = time();
658     $thiz->bantime = 0;
659     $thiz->stat  = $stat;
660     $thiz->subst  = $subst;
661     $thiz->step  = 1;
662     $thiz->trans_step  = -1;
663     $thiz->comm  = array();
664     $thiz->asta_card = -2;
665     $thiz->asta_pnt  = -1;
666     $thiz->handpt = -1;
667     $thiz->exitislock = TRUE;
668
669     $thiz->flags = 0x00;
670     
671     $thiz->chattime = array_fill(0, CHAT_N, 0);
672     $thiz->chat_cur = 0;
673     $thiz->chat_lst = "";
674     $thiz->chat_ban = 0;
675     $thiz->chat_dlt = 0;
676
677     $thiz->table = $table;
678     $thiz->table_pos = -1;
679     $thiz->table_token = "";
680
681     return ($thiz);
682   }
683
684   function &clone(&$from)
685   {
686     GLOBAL $G_false;
687     
688     if (($thiz =& new User()) == FALSE)
689       return ($G_false);
690     
691     $thiz->name       = $from->name;
692     $thiz->sess       = $from->sess;
693     $thiz->ip         = $from->ip;
694     $thiz->lacc       = $from->lacc;
695     $thiz->laccwr     = $from->laccwr;
696     $thiz->bantime    = $from->bantime;
697     $thiz->stat       = $from->stat;
698     $thiz->subst      = $from->subst;
699     $thiz->step       = $from->step;
700     $thiz->trans_step = $from->trans_step;
701     $thiz->comm       = array();
702
703     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
704     for ($i = $i_start ; $i < $from->step ; $i++) {
705       $ii = $i % COMM_N;
706       $thiz->comm[$ii] = $from->comm[$ii];
707     }
708     $thiz->asta_card  = $from->asta_card;
709     $thiz->asta_pnt   = $from->asta_pnt;
710     $thiz->handpt     = $from->handpt;
711     $thiz->exitislock = $from->exitislock;
712
713     $thiz->flags = $from->flags;
714
715     $thiz->chattime = array();
716     for ($i = 0 ; $i < CHAT_N ; $i++)
717       $thiz->chattime[$i] = $from->chattime[$i];
718     $thiz->chat_cur = $from->chat_cur;
719     $thiz->chat_lst = $from->chat_lst;
720     $thiz->chat_ban = $from->chat_ban;
721     $thiz->chat_dlt = $from->chat_dlt;
722
723     $thiz->table      = $from->table;
724     $thiz->table_pos  = $from->table_pos;
725     $thiz->table_token = $from->table_token;
726     $thiz->the_end    = $from->the_end;
727
728     return ($thiz);
729   }
730   
731   function &spawn(&$from, $table, $table_pos)
732   {
733     GLOBAL $G_false;
734     
735     if (($thiz =& new User()) == FALSE)
736       return ($G_false);
737     
738     $thiz->name       = $from->name;
739     $thiz->sess       = $from->sess;
740     $thiz->ip         = $from->ip;
741     $thiz->lacc       = $from->lacc;
742     $thiz->laccwr     = $from->laccwr;
743     $thiz->bantime    = $from->bantime;
744     $thiz->stat       = $from->stat;
745     $thiz->subst      = $from->subst;
746     $thiz->step       = $from->step;
747     $thiz->trans_step = $from->trans_step;
748     $thiz->comm       = array();
749
750     /*
751     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
752     for ($i = $i_start ; $i < $from->step ; $i++) {
753       log_wr("TRY PUSH:".$i);
754       $ii = $i % COMM_N;
755       $thiz->comm[$ii]   = $from->comm[$ii];
756     }
757     */
758     $thiz->asta_card  = $from->asta_card;
759     $thiz->asta_pnt   = $from->asta_pnt;
760     $thiz->handpt     = $from->handpt;
761     $thiz->exitislock = $from->exitislock;
762     $thiz->the_end    = $from->the_end;
763
764     $thiz->flags      = $from->flags;
765
766     $thiz->chattime   = array_fill(0, CHAT_N, 0);
767     $thiz->chat_cur   = 0;
768     $thiz->chat_lst   = "";
769     $thiz->chat_ban   = 0;
770     $thiz->chat_dlt   = 0;
771
772
773     $thiz->table      = $table;
774     $thiz->table_pos  = $table_pos;
775     $thiz->table_token = $from->table_token;
776
777     return ($thiz);
778   }
779   
780   function stat_set($stat) {
781     log_main("sess: [".$this->sess. "] NEW STAT: [".$stat."]"); 
782     $this->stat = "$stat";
783     
784     /*
785     if (validate_sess($this->sess)) {
786       if (file_exists(PROXY_PATH) == FALSE)
787         mkdir(PROXY_PATH);
788       $fp = fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
789       fwrite($fp, sprintf("%s\n",$this->stat));
790       fclose($fp);
791     }
792     */
793   }
794
795   function step_set($step) {
796     $this->step = $step;
797     
798     do {
799       if (validate_sess($this->sess) == FALSE)
800         break;
801       if (file_exists(PROXY_PATH) == FALSE)
802         mkdir(PROXY_PATH);
803       if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
804         break;
805       fwrite($fp, pack("l",$this->step), 4);
806       fclose($fp);
807
808       return (TRUE);
809     } while (0);
810
811     return (FALSE);
812   }
813
814   function step_inc($delta = 1) {
815     $this->step += $delta;
816     
817     if (validate_sess($this->sess)) {
818       if (file_exists(PROXY_PATH) == FALSE)
819         mkdir(PROXY_PATH);
820       $fp = fopen(PROXY_PATH."/".$this->sess.".step", 'w');
821       fwrite($fp, pack("l",$this->step), 4);
822       fclose($fp);
823
824       return (TRUE);
825     }
826     
827     return (FALSE);
828   }
829
830   function reset() {
831     $curtime = time();
832     log_legal($curtime, $this->sess, $this->name, "STAT:LOGOUT", '');
833
834     $tmp_sess = $this->sess;
835     $this->sess = "";
836     step_unproxy($tmp_sess);
837     $this->name = "";  // OK here
838     while (array_pop($this->comm) != NULL);
839     $this->step = 0;
840     $this->chattime = array_fill(0, CHAT_N, 0);
841     $this->chat_cur = 0;
842     $this->chat_lst = "";
843     $this->chat_ban = 0;
844     $this->chat_dlt = 0;
845     $this->the_end = FALSE;
846   }
847 } // end class User
848
849
850 function step_get($sess) {
851   $fp = FALSE;
852   do {
853     if (validate_sess($sess) == FALSE)
854       break;
855
856     if (file_exists(PROXY_PATH) == FALSE)
857       mkdir(PROXY_PATH);
858     if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
859       break;
860     if (($s = fread($fp, 4)) == FALSE)
861       break;
862     if (strlen($s) != 4)
863       break;
864     $arr = unpack('l', $s);
865     fclose($fp);
866
867     // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
868     return ($arr[1]);
869   } while (0);
870
871   if ($fp != FALSE)
872     fclose($fp);
873
874   log_rd2("STEP_GET: return false ");
875
876   return (FALSE);
877 }
878
879 function step_unproxy($sess) {
880   log_rd2("UNPROXY: ".PROXY_PATH."/".$sess.".step");
881   if (file_exists(PROXY_PATH) == FALSE)
882     mkdir(PROXY_PATH);
883   @unlink(PROXY_PATH."/".$sess.".step");
884 }
885
886
887 class Room {
888   var $user;
889   var $table;
890   var $comm; // commands for many people
891   var $step; // current step of the comm array
892   var $garbage_timeout;
893   var $shm_sz;
894
895   function Room () {
896     $this->user = array();
897     $this->table = array();
898
899     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
900       $this->user[$i] =& User::create("", "");
901     }
902
903     for ($i = 0 ; $i < TABLES_N ; $i++) {
904       $this->table[$i] =& Table::create($i);
905       if ($i < 12) {
906         $row = ( (((int)($i / 4)) % 2) == 0 );
907         $col = ($i % 2 == 0);
908         $this->table[$i]->auth_only = (($row && $col) || (!$row && !$col));
909       }
910       else {
911         $this->table[$i]->auth_only = FALSE;
912       }
913     }
914     $this->garbage_timeout = 0;
915   }
916
917   function garbage_manager($force)
918   {
919     $ismod = FALSE;
920
921     log_rd2("garbage_manager START");
922
923     /* Garbage collector degli utenti in timeout */
924     $curtime = time();
925     if ($force || $this->garbage_timeout < $curtime) {
926       
927       // Before all align times with table timeout
928       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
929         $table_cur =& $this->table[$table_idx];
930         // if the table is complete and exists its shared mem we get the info about users lacc
931
932         if ($table_cur->player_n == PLAYERS_N) {
933           log_main("PLAYERS == N TABLE ".$table_idx);
934           
935           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
936             log_main("bin5 lock data success");
937             
938             $no_recovery = FALSE;
939             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
940               if ($table_cur->table_token != $bri->table_token) {
941                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
942                 log_main("ERROR: not matching table_start. Room: ".$table_cur->table_start."  Table: ".$bri->table_start);
943                 $no_recovery = TRUE;
944                 $bri = FALSE;
945               }
946             }
947             
948             if ($bri != FALSE) {
949               //
950               //  SPAWN: JOIN
951               //
952               log_main("garbage_manager: bri loaded successfully.");
953               $bri->garbage_manager(TRUE);
954               
955               $bri_table = &$bri->table[0];
956
957               // is the end of the table
958               if ($bri->the_end == TRUE) {
959                 /*
960                  *  DESTROY OF FINISHED TABLE && MOVE PLAYER TO ROOM AGAIN
961                  */
962                 log_main("garbage_manager: INSIDE THE END.");
963
964                 $plist = "$table_cur->table_token|$user_cur->table|$table_cur->player_n";
965                 for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
966                   $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
967                 }
968
969                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
970                   // stat must be "table" by definition
971                   $user_cur =& $this->user[$table_cur->player[$i]];
972                   $bri_user =& $bri->user[$i];
973                   
974                   $user_cur->subst      = $bri_user->subst;
975                   $user_cur->step       = $bri_user->step;
976                   $user_cur->lacc       = $bri_user->lacc;
977                   $user_cur->laccwr     = $bri_user->lacc;
978                   $user_cur->bantime    = $bri_user->bantime;
979                 }
980
981                 log_legal($curtime, $user_cur->sess, $user_cur->name, "STAT:DESTROY_GAME", $plist);
982
983                 $this->room_join_wakeup(&$user_cur, FALSE, 0); 
984                 $table_cur->table_token = "";
985                 $table_cur->wakeup_time = $curtime + WAKEUP_TIME;
986                 Briskin5::destroy_data($table_idx);
987               }
988               else {
989                 log_main("gm:: save_data");
990
991                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
992                   $this->user[$table_cur->player[$i]]->lacc = $bri->user[$i]->lacc;
993                 }
994               
995                 Briskin5::save_data(&$bri);
996               }
997             } // else if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
998             else if ($no_recovery == FALSE) {
999               log_crit("ERROR: table ".$table_idx." unrecoverable join");
1000
1001               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
1002                 $user_cur = &$this->user[$table_cur->player[$i]];
1003                 $user_cur->subst = "shutdowner";
1004                 $user_cur->step_inc();
1005                 
1006                 $ret = sprintf('stat = "%s"; subst = "%s";',  $user_cur->stat, $user_cur->subst);
1007                 $ret .= "gst.st = ".($user_cur->step+1)."; ";
1008                 $ret .= show_notify("<br>I dati del tavolo n&deg; ".$user_cur->table." sono inconsistenti, verranno resettati.<br><br>Torni in piedi.<br><br>", 2000, "Chiudi.", 400, 110);
1009                 $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1010                 $user_cur->step_inc();
1011               }
1012
1013               $plist = "$table_cur->table_token|$user_cur->table|$table_cur->player_n";
1014               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
1015                 $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
1016               }
1017               log_legal($curtime, $user_cur->sess, $user_cur->name, "STAT:DESTROY_GAME(RECOVERY)", $plist);
1018               
1019               $this->room_join_wakeup(&$user_cur, TRUE, -2); 
1020               $table_cur->table_token = "";
1021             }
1022
1023             Briskin5::unlock_data($sem);
1024           } // bri::lock_data
1025         } //  if ($table_cur->player_n == PLAYERS_N) {
1026       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1027     
1028       log_rd2("out new loop.");
1029                 
1030       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1031         $user_cur = &$this->user[$i];
1032         
1033         log_rd2("User: ".$user_cur->name."  stat: ".$user_cur->stat."  subst: ".$user_cur->subst);
1034           
1035         if ($user_cur->sess == "") 
1036           continue;
1037         
1038         if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) {
1039           // Auto logout dell'utente
1040           log_rd2("AUTO LOGOUT.".($user_cur->lacc + EXPIRE_TIME_RD)." curtime ".$curtime);
1041           
1042           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
1043             log_auth($user_cur->sess, "Autologout session.");
1044             
1045             $user_cur->reset();
1046             
1047             log_rd2("AUTO LOGOUT.");
1048             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
1049               $this->room_wakeup(&$user_cur);
1050             else if ($user_cur->subst == 'standup')
1051               $this->room_outstandup(&$user_cur);
1052             else
1053               log_rd2("LOGOUT FROM WHAT ???");
1054           }
1055         }
1056
1057         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < $curtime) { // lo rimettiamo in piedi
1058           if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
1059             $this->room_wakeup(&$user_cur);
1060             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1061             $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);
1062             $user_cur->step_inc();
1063           }
1064         }
1065       }
1066       log_rd2("GARBAGE UPDATED!");
1067       
1068       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
1069       $ismod = TRUE;
1070     }
1071
1072     return ($ismod);
1073   }
1074
1075   function show_room($user_step, &$user)
1076   {
1077     log_main("show_room: username: ".$user->name);
1078     
1079     
1080     $ret = sprintf('gst.st = %d; ',  $user_step);
1081     if ($user->subst == 'standup')
1082       $ret .= "tra.show(); ";
1083     else
1084       $ret .= "tra.hide(); ";
1085
1086     $ret .= sprintf('stat = "%s";',  $user->stat);
1087     
1088     $ret .= root_wellcome($user);
1089     $ret .= sprintf('subst = "%s";', $user->subst);
1090     $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1091     $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1092     $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>";', $itin, xcape($user->name), $itou);
1093     for ($i = 0 ; $i < TABLES_N ; $i++) {
1094       $ret .= $this->table_content($user, $i);
1095       // $ret .= table_act_content(($user->subst == 'standup'), $this->table[$i]->player_n, $i, $user->table, 
1096       //                          ($this->table[$i]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
1097       $ret .=  $this->table[$i]->act_content($user);
1098       if ($this->table[$i]->wag_own != NULL) 
1099         $ret .= sprintf('tra.add(%d, "%s: %s"); ', $i,  $this->table[$i]->wag_own->name, $this->table[$i]->wag_com);
1100       else 
1101         $ret .= sprintf('tra.rem(%d); ', $i);
1102     }
1103     $ret .= $this->standup_content($user);
1104     
1105     return ($ret);
1106   }
1107   
1108
1109   function room_wakeup(&$user)
1110   {
1111     $table_idx = $user->table;
1112     $table = &$this->table[$table_idx];
1113
1114     log_main("WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1115
1116     $curtime = time();
1117
1118     $from_table = ($user->stat == "table");
1119     if ($from_table) {
1120       log_main("WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1121
1122       for ($i = 0 ; $i < $table->player_n ; $i++) {
1123         $user_cur = &$this->user[$table->player[$i]];
1124         log_main("PREIMPOST: INLOOP name: ".$user_cur->name);
1125
1126         if ($user_cur != $user) {
1127           $user_cur->stat_set("room");
1128           $user_cur->subst = "sitdown";
1129           $user_cur->laccwr = $curtime;
1130         }
1131         else if ($user->sess != "") {
1132           $user_cur->stat_set("room");
1133           $user_cur->subst = "standup";
1134           $user_cur->laccwr = $curtime;
1135           $user_cur->table = -1;
1136         }
1137       }
1138     }
1139     else {
1140       $user->stat_set("room");
1141       $user->subst = "standup";
1142       $user->laccwr = $curtime;
1143     }
1144     
1145     $remove_wagon = false;
1146     if($table->wag_own == $user) {
1147       $remove_wagon = true;
1148       $table->wag_reset($curtime);
1149       
1150     }
1151     
1152
1153     /* aggiorna l'array dei giocatori al tavolo. */
1154     $table->user_rem(&$this, &$user);
1155
1156     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1157       $user_cur = &$this->user[$i];
1158       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1159         continue;
1160       
1161       log_main("VALORI: name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
1162
1163       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1164       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
1165         $ret .= 'gst.st_loc++; the_end=true; window.onunload = null; window.onbeforeunload = null; document.location.assign("index.php");|';
1166         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
1167         log_main("DOCUMENT.index.php: from table");
1168       }
1169       else if ($user_cur->stat == "room") {
1170         log_main("DOCUMENT.index.php: from table");
1171
1172         $ret .= $this->table_content($user_cur, $table_idx);
1173         $ret .= $this->standup_content($user_cur);
1174         
1175         // $ret .= table_act_content(FALSE, 0, $table_idx, $user->table, FALSE);
1176         $ret .= $table->act_content($user);
1177
1178         if ($user_cur == $user) {
1179           // set the new status 
1180           $ret .=  'subst = "standup"; tra.show(); ';
1181           // clean the action buttons in other tables
1182           for ($e = 0 ; $e < TABLES_N ; $e++) {
1183             if ($this->table[$e]->player_n < PLAYERS_N) {
1184               // $ret .= table_act_content(TRUE, 0, $e, $user->table, 
1185               //                           ($this->table[$e]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
1186               $ret .= $this->table[$e]->act_content($user);
1187             }
1188           }
1189         }
1190         else {
1191           // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
1192           //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1193           $ret .= $table->act_content($user_cur);
1194         }
1195       }
1196       log_wr("ROOM_WAKEUP: ".$ret);
1197       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1198       $user_cur->step_inc();
1199     }
1200   }
1201
1202   function room_join_wakeup(&$user, $update_lacc = FALSE, $trans_delta)
1203   {
1204     $table_idx = $user->table;
1205     $table = &$this->table[$table_idx];
1206     
1207     log_main("JOIN_WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1208
1209     $curtime = time();
1210     $user_wup = array();
1211     $user_wup_n = 0;
1212     $user_tab = array();
1213     $user_tab_n = 0;
1214     log_main("JOIN WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1215     
1216     for ($i = 0 ; $i < $table->player_n ; $i++) {
1217       $user_cur = &$this->user[$table->player[$i]];
1218       log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1219       if ($user_cur->sess != "") {
1220         if ($update_lacc == TRUE) {
1221           $user_cur->laccwr = $curtime;
1222         }
1223         log_main("cur: ".$user_cur->name."  subst: ".$user_cur->subst);
1224         if ($user_cur->subst == "shutdowned") {
1225           $user_cur->stat_set("room");
1226           $user_cur->subst = "sitdown";
1227         }
1228         else if ($user_cur->subst == "shutdowner") {
1229           $user_cur->stat_set("room");
1230           $user_cur->subst = "standup";
1231           $user_cur->table = -1;
1232           $user_wup[$user_wup_n++] = &$user_cur;
1233           
1234           $remove_wagon = false;
1235           if($table->wag_own == $user_cur) {
1236             $remove_wagon = true;
1237             $table->wag_reset($curtime);
1238           }
1239         }
1240         $user_tab[$user_tab_n++] = &$user_cur;
1241       }
1242     }
1243
1244     for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
1245       $table->user_rem(&$this, &$user_wup[$wup_idx]);
1246
1247     /* aggiorna l'array dei giocatori al tavolo. */
1248
1249     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1250       log_main("START LOOP");
1251       $user_cur = &$this->user[$i];
1252       if ($user_cur->sess == '' || $user_cur->stat != 'room') {
1253         log_main("name: ".$user_cur->name."skip   subst: ".$user_cur->subst);
1254         continue;
1255       }
1256
1257       log_main("___");
1258       log_main("VALORI name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
1259
1260       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1261       if ($user_cur->stat == "room") {
1262         log_main("DOCUMENT.index.php from table");
1263
1264         $ret .= $this->table_content($user_cur, $table_idx);
1265         $ret .= $this->standup_content($user_cur);
1266         
1267         // $ret .= table_act_content(FALSE, 0, $table_idx, $user_cur->table,
1268         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1269         $ret .= $table->act_content($user_cur);
1270
1271
1272         for ($tab_idx = 0 ; $tab_idx < $user_tab_n  ; $tab_idx++)
1273           if ($user_cur == $user_tab[$tab_idx]) 
1274             break;
1275
1276         // for users that wakeup the room will be reconstructed by index_rd.php
1277         if ($tab_idx < $user_tab_n) {
1278           log_main("PRE show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1279
1280 //        ARRAY_POP DISABLED
1281 //        if ($trans_delta == 0)
1282 //          while (array_pop($user_cur->comm) != NULL);
1283
1284           $user_cur->trans_step = $user_cur->step + 1 + $trans_delta;
1285           $user_cur->comm[$user_cur->step % COMM_N] = "";
1286           $user_cur->step_inc();
1287           $user_cur->comm[$user_cur->step % COMM_N] = $this->show_room(($user_cur->step + 1), &$user_cur);
1288           $user_cur->step_inc();
1289           log_main("POST show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1290
1291           continue;
1292         }
1293         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
1294
1295         log_main("JOIN_WAKEUP more");
1296         // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
1297         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1298         $ret .= $table->act_content($user_cur);
1299
1300         log_main("JOIN_WAKEUP end more");
1301       }
1302       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
1303       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1304       $user_cur->step_inc();
1305     }
1306   }
1307
1308   function room_outstandup(&$user)
1309   {
1310     $this->room_sitdown(&$user, -1);
1311   }
1312   
1313   function table_update(&$user)
1314   {
1315     log_main("table_update: pre - USER: ".$user->name);
1316
1317     $table_idx = $user->table;
1318
1319     if ($table_idx > -1) 
1320       $table = &$this->table[$table_idx];
1321     
1322     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1323       $ret = "";
1324       $user_cur = &$this->user[$i];
1325       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1326       continue;
1327       
1328       $ret = "gst.st = ".($user_cur->step+1)."; ";
1329       if ($table_idx > -1)
1330         $ret .= $this->table_content($user_cur, $table_idx);
1331       
1332       if ($user_cur == $user) {
1333         $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1334         $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1335         $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', $itin, xcape($user->name), $itou);
1336       }
1337       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1338       $user_cur->step_inc();
1339     }
1340
1341     log_main("table_update: post");
1342   }
1343
1344   function room_sitdown(&$user, $table_idx)
1345   {
1346     log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1347
1348     $train_app = "";
1349
1350     if ($table_idx > -1 && $table_idx < TABLES_N) { 
1351       $table = &$this->table[$table_idx];
1352
1353       // wagon shutdown 
1354       if ($table->wag_own != NULL && $table->player_n == PLAYERS_N) {        
1355         for ($i = 0 ; $i < TABLES_N ; $i++) {
1356           $user_cur =& $this->user[$table->player[$i]];
1357           if ($user_cur == $table->wag_own) {
1358             $train_app = sprintf("tra.rem(%d); ", $table_idx); 
1359             $table->wag_reset(time());
1360             break;
1361           }
1362         }
1363       }
1364     }
1365
1366     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1367       $ret = "";
1368       $user_cur = &$this->user[$i];
1369       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1370       continue;
1371       
1372       $ret = "gst.st = ".($user_cur->step+1)."; ".$train_app;
1373       if ($table_idx > -1)
1374       $ret .= $this->table_content($user_cur, $table_idx);
1375       $ret .= $this->standup_content($user_cur);
1376       
1377       if ($user_cur == $user) {
1378         $ret .=  'subst = "sitdown"; tra.hide(); ';
1379         // clean the action buttons in other tables
1380         for ($e = 0 ; $e < TABLES_N ; $e++) {
1381           // $ret .= table_act_content(FALSE, 0, $e, $user_cur->table, FALSE);
1382           $ret .= $this->table[$e]->act_content($user_cur);
1383         }
1384       }
1385       else if ($table_idx > -1) {
1386         if ($table->player_n == PLAYERS_N) {
1387           // $ret .= table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table,
1388           ///                      ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1389           $ret .= $table->act_content($user_cur);
1390         }
1391       }
1392       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1393       $user_cur->step_inc();
1394     }
1395   }
1396
1397   function chatt_send(&$user, $mesg)
1398   {
1399     GLOBAL $G_alarm_passwd;
1400     $only_you = FALSE;
1401     
1402     // common settings
1403     $msg = substr($mesg, 6, 128);
1404     $curtime = time();
1405     $dt = date("H:i ", $curtime);
1406
1407     //
1408     //  Compute actions
1409     //
1410
1411     $to_user     = FALSE;
1412     $to_all      = FALSE;
1413     $to_room     = FALSE;
1414     $to_tabl     = FALSE;
1415     $update_room = FALSE;
1416
1417     if (strcmp($msg,  "/tav") == 0 || 
1418         strncmp($msg, "/tav ", 5) == 0) {
1419       do {
1420         if ($user->stat != 'room' || $user->subst != 'sitdown') {
1421           $msg = "<br>Per attivare il messaggio di segnalazione del tavolo occorre essere seduti.<br><br>";
1422           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1423
1424           break;
1425         }
1426
1427         $table = &$this->table[$user->table];
1428         
1429         if ($table->wag_own != NULL) {
1430           $msg = "<br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br>";
1431           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1432
1433           break;
1434         }
1435
1436         $dtime = $curtime - $table->wag_tout;
1437         if ($dtime  < EXPIRE_TIME_WAG) {
1438           $msg = sprintf("<br>Il messaggio di segnalazione del tavolo<br>&egrave; disattivato ancora per %d second%s.<br><br>",
1439                          EXPIRE_TIME_WAG - $dtime, (EXPIRE_TIME_WAG - $dtime == 1 ? "o" : "i"));
1440           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1441
1442           break;
1443         }
1444         
1445         $msg = substr($msg, 5);
1446         
1447         $table->wag_set($user, $msg);
1448         $to_user = sprintf('tra.add(%d, "%s");', $user->table, xcape(sprintf("%s: %s", $user->name, $msg)));
1449         $to_room = $to_user;
1450         
1451       } while (0);
1452     } // /tav chat command
1453
1454     else if (strncmp($msg, "/alarm ", 7) == 0) {
1455       if (strncmp($msg, "/alarm to ", 10) == 0) {
1456         $sp_pos = strpos($msg, " ", 10);
1457         $target = substr($msg, 10, $sp_pos - 10);
1458         $alarm_check = "/alarm to ".$target." ".$G_alarm_passwd." ";
1459       }
1460       else {
1461         $target = "";
1462         $alarm_check = "/alarm ".$G_alarm_passwd." ";
1463       }
1464       do {
1465         if (strncmp($msg, $alarm_check, strlen($alarm_check)) != 0) {
1466           $msg = "<br>La password digitata non &egrave; corretta.<br><br>";
1467           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1468
1469           break;
1470         }
1471
1472         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Alarm <b>%s</b> inviato a <b>%s</b>.");', 
1473                            $dt, NICKSERV, xcape(substr($msg, strlen($alarm_check))), 
1474                            ($target == "" ? "tutti" : xcape($target)) );
1475
1476         $msg = sprintf("<br><b>%s<br><br>%s</b><br><br>",
1477                        $dt.NICKSERV, xcape(substr($msg, strlen($alarm_check))));
1478         $to_all = show_notify($msg, 0, "chiudi", 400, 120);
1479       } while (0);
1480     } // /alarm chat command
1481     else if (strncmp($msg, "/garante", 8) == 0) {
1482       if ($user->flags & USER_FLAG_AUTH) {
1483         $to_user = sprintf('authbox(300,200);');
1484       }
1485       else {
1486         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Per autenticare qualcuno devi a tua volta essere autenticato.</b>");', $dt, NICKSERV);
1487       }
1488     }
1489     else if (strncmp($msg, "/nick ", 6) == 0) {
1490       log_main("chatt_send BEGIN");
1491
1492       do {
1493         if (($name_new = validate_name(substr($msg, 6))) == FALSE) {
1494           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Il nickname deve contenere almeno una lettera dell\'alfabeto o una cifra.");', $dt, NICKSERV);
1495           break;
1496         }
1497
1498         $msg = "COMMAND ".$msg;
1499         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1500           $user_cur = &$this->user[$i];
1501
1502           if ($user_cur->sess == '')
1503             continue;
1504           if ($user_cur->name == $name_new)
1505             break;
1506           }
1507         if ($i <  MAX_PLAYERS) {
1508           $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Nickname <b>%s</b> gi&agrave; in uso.");', $dt, NICKSERV, xcape($name_new));
1509           break;
1510         }
1511         
1512         if ($user->flags & USER_FLAG_AUTH) {
1513           if (strcasecmp($user->name,$name_new) != 0) {
1514             if ($user->subst == 'standup' || ($user->subst != 'standup' && $this->table[$user->table]->auth_only == FALSE)) {
1515               $user->flags &= ~USER_FLAG_AUTH; // Remove auth if name changed
1516               for ($i = 0 ; $i < TABLES_N ; $i++) {
1517                 $to_user .= $this->table[$i]->act_content($user);
1518               }
1519             }
1520             else {
1521               $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Non puoi cambiare nick a un tavolo per soli autenticati.</b>");', $dt, NICKSERV);
1522               break;
1523             }
1524           }
1525         }
1526         $user->name = $name_new; // OK - nick changed
1527         
1528         /* se nome gia' in uso, segnala cosa potrebbe capitare */
1529         if (($user->flags & USER_FLAG_AUTH) == 0) {
1530           $userdb = new LoginDB();
1531           if ($userdb->login_exists($name_new)) {
1532             $to_user .= sprintf('chatt_sub("%s", [2, "%s"],"Il nickname <b>\'%s\'</b> &egrave; gi&agrave; registrato, <b>se il suo proprietario si autentificher&agrave; verrai rinominato d\'ufficio come ghost<i>N</i>.</b>");', $dt, NICKSERV, xcape($name_new));
1533           }
1534         }
1535
1536         log_main("chatt_send start set");
1537
1538         $update_room = TRUE;
1539       } while (0);
1540     } // nick chat command
1541
1542     else if (strncmp($msg, "/st ", 4) == 0) {
1543       log_main("chatt_send BEGIN");
1544
1545       do {
1546         $st_str = substr($msg, 4);
1547         
1548         if (strcasecmp($st_str, "normale") == 0) {
1549           $st = USER_FLAG_S_NORM;
1550         }
1551         else if (strcasecmp($st_str, "pausa") == 0) {
1552           $st = USER_FLAG_S_PAU;
1553         }
1554         else if (strcasecmp($st_str, "fuori") == 0) {
1555           $st = USER_FLAG_S_OUT;
1556         }
1557         else if (strcasecmp($st_str, "cane") == 0) {
1558           $st = USER_FLAG_S_DOG;
1559         }
1560         else if (strcasecmp($st_str, "cibo") == 0) {
1561           $st = USER_FLAG_S_EAT;
1562         }
1563         else if (strcasecmp($st_str, "lavoro") == 0) {
1564           $st = USER_FLAG_S_WRK;
1565         }
1566         else if (strcasecmp($st_str, "sigaretta") == 0) {
1567           $st = USER_FLAG_S_SMK;
1568         }
1569         else if (strcasecmp($st_str, "presente") == 0) {
1570           $st = USER_FLAG_S_EYE;
1571         }
1572         else {
1573           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Questo stato non esiste.");', $dt, NICKSERV);
1574           break;
1575         }
1576
1577         log_main("chatt_send start set");
1578         if (($user->flags & USER_FLAG_S_ALL) != $st) {
1579           $update_room = TRUE;
1580           $user->flags = ($user->flags & ~USER_FLAG_S_ALL) | $st;
1581         }
1582       } while (0);
1583     } // nick chat command
1584
1585     else { // normal chat line
1586       if ($curtime < ($user->chat_ban + $user->chat_dlt)) {
1587         $only_you = TRUE;
1588         $user->chat_dlt = $user->chat_dlt * 2; 
1589         if ($user->chat_dlt > 120)
1590           $user->chat_dlt = 120; 
1591       }
1592       else if ($user->chat_lst == $msg)
1593         $only_you = TRUE;
1594       else if ($curtime - $user->chattime[($user->chat_cur + 1) % CHAT_N] < CHAT_ILL_TIME) {
1595         $user->chat_ban = $curtime;
1596         $user->chat_dlt = 5;
1597         $only_you = TRUE;
1598       }
1599       else {
1600         $user->chat_ban = 0;
1601         $user->chat_dlt = 0;
1602       }
1603
1604       if ($only_you) {
1605         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape("== chat ban =="));
1606       }
1607       else {
1608         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape($msg));
1609         // temporary silentiation for troll (will became array check)
1610         if (strcasecmp($user->name,'JackRokka') != 0 && $user->sess != '47ea653f602e8')
1611           $to_room = $to_user;
1612       }
1613
1614       log_legal($curtime, $user->sess, $user->name, 
1615                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$msg);
1616       
1617       $user->chat_lst = "$msg";
1618       $user->chattime[$user->chat_cur % CHAT_N] = $curtime;
1619       $user->chat_cur++;
1620     }
1621
1622     if ($to_all) {
1623       $to_room = $to_all;
1624       $to_tabl = $to_all;
1625     }
1626
1627     //
1628     //  Output to clients
1629     //
1630
1631     if ($to_user != FALSE) {
1632       $user->comm[$user->step % COMM_N] =  "gst.st = ".($user->step+1)."; ";
1633       $user->comm[$user->step % COMM_N] .= $to_user;
1634       $user->step_inc();
1635     }
1636
1637     if ($to_room != FALSE) {
1638       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1639         $user_cur = &$this->user[$i];
1640         if ($target != "" && $user_cur->name != $target)
1641           continue;
1642         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1643         if ($user_cur->sess == '' || $user_cur->stat == 'table' || $user_cur == $user)
1644           continue;
1645         
1646         $user_cur->comm[$user_cur->step % COMM_N] =  "gst.st = ".($user_cur->step+1)."; ";
1647         $user_cur->comm[$user_cur->step % COMM_N] .= $to_room; 
1648         $user_cur->step_inc();
1649       }
1650     }
1651     
1652     if ($to_tabl) {
1653       // Before all align times with table timeout
1654       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1655         $table_cur =& $this->table[$table_idx];
1656         // if the table is complete and exists its shared mem we get the info about users lacc
1657         
1658         if ($table_cur->player_n == PLAYERS_N) {
1659           log_main("PLAYERS == N TABLE ".$table_idx);
1660         
1661           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
1662             log_main("bin5 lock data success");
1663             
1664             $no_recovery = FALSE;
1665             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1666               if ($table_cur->table_token != $bri->table_token) {
1667                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
1668                 $bri = FALSE;
1669               }
1670             }
1671             
1672             if ($bri != FALSE) {
1673               $bri_table = &$bri->table[0];
1674               for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
1675                 // stat must be "table" by definition
1676                 $bri_user =& $bri->user[$i];
1677               
1678                 if ($target != "" && $bri_user->name != $target)
1679                   continue;
1680                 log_main("writa: ".$user_mesg);
1681                 $bri_user->comm[$bri_user->step % COMM_N] = "gst.st = ".($bri_user->step+1)."; ";
1682                 $bri_user->comm[$bri_user->step % COMM_N] .= $to_tabl;
1683                 $bri_user->step_inc();
1684               }
1685               Briskin5::save_data(&$bri);
1686             }
1687             Briskin5::unlock_data($sem);
1688           } // bri::lock_data
1689         } //  if ($table_cur->player_n == PLAYERS_N) {
1690       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1691     } // if ($to_tabl == true ...
1692
1693     if ($update_room) {
1694       if ($user->stat == 'room' && $user->subst == 'standup') {
1695         $this->standup_update(&$user);
1696       }
1697       else if ($user->stat == 'room' && $user->subst == 'sitdown') {
1698         log_main("chatt_send pre table update");
1699         $this->table_update(&$user);
1700         log_main("chatt_send post table update");
1701       }
1702     } // if ($update_room ...
1703
1704     return;
1705   } // function chatt_send( ...
1706
1707   function &get_user($sess, &$idx)
1708   {
1709     GLOBAL $PHP_SELF, $G_false;
1710
1711     if (validate_sess($sess)) {
1712       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1713         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1714           // find it
1715           $idx = $i;
1716           $ret = &$this->user[$i];
1717           return ($ret);
1718         }
1719       }
1720       log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1721       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1722       // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1723     }
1724     else {
1725       log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
1726     }
1727
1728     return ($G_false);
1729   }
1730
1731   
1732
1733   /*
1734    * function &add_user(&$room, &$sess, &$idx, $name, $pass, $ip)
1735    *
1736    * RETURN VALUE:
1737    *   if ($idx >  -1    && ret == FALSE)  =>  duplicated nick
1738    *   if ($idx == -2    && ret == FALSE)  =>  invalid name
1739    *   if ($idx == -3    && ret == FALSE)  =>  wrong password
1740    *   if ($idx == -1    && ret == FALSE)  =>  no space left
1741    *   if ($idx ==  0    && ret == user)   =>  SUCCESS
1742    *   if ($idx == -$idx && ret == user)   =>  SUCCESS (but the login exists in the auth db 
1743    */
1744
1745
1746
1747   function &add_user(&$sess, &$idx, $name, $pass, $ip)
1748   {
1749     GLOBAL $G_false;
1750
1751     $idx = 0;
1752
1753     $authenticate = FALSE;
1754     $login_exists = FALSE;
1755     $ghost = -1;
1756     $ghost_auth = FALSE;
1757     $idx = -1;
1758     $idfree = -1;
1759     
1760     if (($name_new = validate_name($name)) == FALSE) {
1761       $idx = -2;
1762       return ($G_false);
1763     }
1764
1765     log_auth("XXX", sprintf("ARRIVA: [%s] pass:[%s]", $sess, ($pass == FALSE ? "FALSE" : $pass)));
1766     if (validate_sess($sess) == FALSE) 
1767       $sess = "";
1768
1769     /* if pass != FALSE verify the login with pass */
1770     log_auth("XXX", "auth1");
1771     $userdb = new LoginDB();
1772     if ($pass != FALSE) {
1773       log_auth("XXX", "auth2");
1774       $authenticate = $userdb->login_verify($name_new, $pass);
1775       log_auth("XXX", "authenticate: ".($authenticate == TRUE ? "TRUE" : "FALSE"));
1776       
1777       if ($authenticate == FALSE) {
1778         $idx = -3;
1779         return ($G_false);
1780       }
1781     }
1782     else {
1783       $login_exists =  $userdb->login_exists($name_new);
1784     }
1785     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1786       /* free user ? */
1787       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1788         if ($idx == -1)
1789           $idx = $i;
1790       }
1791       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
1792         $idfree = $i;
1793         continue; // NOTE: CHECK IT !!
1794       }
1795       if (strcasecmp($this->user[$i]->name, $name_new) == 0) {
1796         if ($authenticate == FALSE) {
1797           $idx = $i;
1798           break;
1799         }
1800         else {
1801           $ghost = $i;
1802           $ghost_auth = ($this->user[$i]->flags & USER_FLAG_AUTH);
1803         }
1804       }
1805     }
1806     if ($idx == -1)
1807       $idx = $idfree;
1808
1809     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1810
1811     if ($ghost > -1 && $authenticate) {
1812       /* swap session */
1813
1814       $ghost_user =& $this->user[$ghost];
1815       $curtime = time();
1816       $ghost_user->step_inc();
1817       if ($sess == "") {
1818         $sess = uniqid(""); 
1819         $ghost_user->sess = $sess;
1820       }
1821       else {
1822         $ghost_user->sess = $sess;
1823       }
1824       
1825       // If user at the table we need to update the table data too
1826       $table_idx = $ghost_user->table;
1827       if ($ghost_user->stat == "table" && $this->table[$table_idx]->player_n == PLAYERS_N) {
1828         if (($brisem = Briskin5::lock_data($table_idx)) != FALSE) { 
1829           if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1830             if ($bri->the_end != TRUE) {
1831               $bri->user[$ghost_user->table_pos]->step_inc();
1832               $bri->user[$ghost_user->table_pos]->sess = $sess;
1833               Briskin5::save_data(&$bri);
1834             }
1835           }
1836           Briskin5::unlock_data($brisem);
1837         }
1838       }
1839
1840       $idx = $ghost;
1841       return ($this->user[$ghost]);
1842     }
1843     else if ($idx != -1 && $i == MAX_PLAYERS) {
1844       /* SUCCESS */
1845       $curtime = time();
1846       if ($sess == "") {
1847         $sess = uniqid("");
1848         $this->user[$idx]->sess = $sess;
1849       }
1850       else {
1851         $this->user[$idx]->sess = $sess;
1852       }
1853       $this->user[$idx]->name = $name_new; // OK - add new user
1854       $this->user[$idx]->stat_set("room");
1855       $this->user[$idx]->step_set(0);
1856       while (array_pop($this->user[$idx]->comm) != NULL);
1857       $this->user[$idx]->subst = "standup";
1858       $this->user[$idx]->lacc =   $curtime;
1859       $this->user[$idx]->laccwr = $curtime;
1860       $this->user[$idx]->bantime = 0;
1861       $this->user[$idx]->ip = $ip;
1862
1863       $this->user[$idx]->flags = ($authenticate ? USER_FLAG_AUTH : 0x00);
1864
1865       if ($ghost > -1) {
1866         log_main("ghost: rename!");
1867         $ghost_user =& $this->user[$ghost];
1868
1869         if ($ghost_auth == FALSE) {
1870           for ($sfx = 1 ; $sfx <= MAX_PLAYERS ; $sfx++) {
1871             $ghostname = 'ghost'.$sfx;
1872             for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1873               if (strcmp("", $this->user[$i]->sess) == 0) 
1874                 continue;
1875               
1876               if (strcmp($this->user[$i]->name, $ghostname) == 0) {
1877                 $ghostname = '';
1878                 break;
1879               }
1880             }
1881             if ($ghostname != '')
1882               break;
1883           }
1884           
1885           $ghost_user->name = $ghostname;
1886           
1887           if ($ghost_user->stat == 'room' && $ghost_user->subst == 'standup') {
1888             $this->standup_update(&$ghost_user);
1889           }
1890           else {
1891             log_main("chatt_send pre table update");
1892             $this->table_update(&$ghost_user);
1893           log_main("chatt_send post table update");
1894           }
1895         } // if ($ghost_auth == FALSE
1896         else {
1897           // FIXME: cacciare il vecchio utente room && table (if needed)
1898           $ghost_user->the_end = TRUE;
1899           $ghost_user->lacc = 0;
1900           $this->garbage_manager(TRUE);
1901         }
1902       } //  if ($ghost > -1) {
1903
1904       log_main(sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1905       $real_idx = $idx;
1906       if ($login_exists)
1907         $idx = -($idx + 1);
1908       return ($this->user[$real_idx]);
1909     }
1910
1911     return ($G_false);
1912   }
1913   
1914   function standup_update(&$user)
1915   {
1916     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1917       $user_cur = &$this->user[$i];
1918       if ($user_cur->sess == '')
1919         continue;
1920
1921       log_main("STANDUP START: ".$user_cur->stat);
1922       
1923       if ($user_cur->stat == 'room') {
1924         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".$this->standup_content($user_cur);
1925         if ($user_cur == $user) {
1926           $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1927           $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1928
1929           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', 
1930                                                                $itin, xcape($user->name), $itou);
1931         }
1932         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1933         
1934         $user_cur->step_inc();
1935       }
1936     }
1937   }
1938
1939   // Static functions
1940   function &init_data()
1941   {
1942     $room =& new Room();
1943     
1944     return $room;
1945   }
1946   
1947
1948   function &load_data() 
1949   {
1950     GLOBAL $G_false, $sess;
1951     $doexit = FALSE;
1952     do {
1953       if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1954         log_main("ftok failed");
1955         $doexit = TRUE;
1956         break;
1957       }
1958     
1959       if (($shm_sz = sharedmem_sz($tok)) == -1) {
1960         log_main("shmop_open failed");
1961       }
1962         
1963       if ($shm_sz == -1)
1964         $shm_sz = SHM_DIMS_MIN;
1965
1966       if ($shm = shm_attach($tok, $shm_sz)) {
1967         $room = @shm_get_var($shm, $tok);
1968         
1969         log_only("bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
1970         if (isset($room)) 
1971           log_only("bri count ".count($room));
1972         
1973         if ($room == FALSE) {
1974           log_only("INIT MAIN DATA");
1975           
1976           $room =& Room::init_data();
1977           if (@shm_put_var($shm, $tok, $room) == FALSE) {
1978             log_only("PUT_VAR FALLITA ".strlen(serialize($room)));
1979             log_only(serialize($room));
1980           }
1981         }
1982         $room->shm_sz = $shm_sz;
1983         
1984         shm_detach($shm);
1985       }
1986       $ret = &$room;
1987       return ($ret);
1988     } while (0);
1989     
1990     if ($doexit)
1991       exit();
1992     
1993     return ($G_false);
1994   }
1995   
1996
1997   function save_data(&$room) 
1998   {
1999     GLOBAL $sess;
2000     
2001     $shm =   FALSE;
2002     
2003     // var_dump($room);
2004     
2005     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) 
2006       return (FALSE);
2007     
2008     while ($room->shm_sz < SHM_DIMS_MAX) {
2009       if (($shm = shm_attach($tok, $room->shm_sz)) == FALSE)
2010         break;
2011       
2012       // log_only("PUT_VAR DI ".strlen(serialize($room)));
2013       if (shm_put_var($shm, $tok, $room) != FALSE) {
2014         shm_detach($shm);
2015         return (TRUE);
2016       }
2017       if (shm_remove($shm) === FALSE) {
2018         log_only("REMOVE FALLITA");
2019         break;
2020       }
2021       shm_detach($shm);
2022       $room->shm_sz += SHM_DIMS_DLT;
2023     } 
2024
2025     if ($shm)
2026       shm_detach($shm);
2027     
2028     return (FALSE);
2029   }
2030
2031   function lock_data()
2032   {
2033     GLOBAL $sess; 
2034     
2035     //  echo "LOCK: ".FTOK_PATH."/main";
2036     //  exit;
2037     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
2038       echo "FTOK FAILED";
2039       exit;
2040     }
2041     // echo "FTOK ".$tok."<br>";
2042     if (($res = sem_get($tok)) == FALSE) {
2043       echo "SEM_GET FAILED";
2044       exit;
2045     }
2046     if (sem_acquire($res)) {   
2047       log_lock("LOCK room");
2048       return ($res);
2049     }
2050     else
2051       return (FALSE);
2052   }
2053   
2054   function unlock_data($res)
2055   {
2056     GLOBAL $sess; 
2057     
2058     log_lock("UNLOCK room");
2059
2060     return (sem_release($res));
2061   }
2062
2063
2064   function standup_content($user)
2065   {
2066     $ret = "";
2067     $content = "";
2068     
2069     if ($user->stat != 'room')
2070       return;
2071     
2072     for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
2073       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
2074         continue;
2075       $ct++;
2076     }
2077     
2078     // $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
2079     
2080     $content = ' j_stand_cont( [ ';
2081
2082     for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
2083       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
2084         continue;
2085       
2086       $flags = $this->user[$e]->flags;
2087       
2088       if ($this->user[$e]->subst == "standup") {
2089         if ($this->user[$e] == $user) 
2090           { 
2091             $flags |= 1;
2092           }
2093         
2094         $content .= sprintf('%s[ %d, "%s" ]',($ct > 0 ? ', ' : ''), $flags, xcape($this->user[$e]->name));
2095         $ct++;
2096       }
2097     }
2098     $content .= ' ]);';
2099     
2100     return ($content);
2101   }
2102   
2103   function table_content_old($user, $table_idx)
2104   {
2105     $content = "";
2106     $ret = "";
2107     // TODO
2108     //
2109     //   Si possono usare i dati nella classe table
2110     //
2111     
2112     $sess = $user->sess;
2113     $table = &$this->table[$table_idx];
2114     
2115     if ($user->stat != 'room')
2116       return;
2117     
2118     for ($i = 0 ; $i < $table->player_n ; $i++) {
2119       $user_cur = &$this->user[$table->player[$i]];
2120       
2121       if ($user_cur == $user) 
2122         { $hilion = "<b>"; $hilioff = "</b>"; }
2123       else
2124         { $hilion = ""; $hilioff = ""; }
2125       
2126       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2127       
2128       $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
2129     }
2130     /*
2131   for ( ; $i < PLAYERS_N ; $i++)
2132     $content .= "<br>";
2133     */
2134     
2135     $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
2136     
2137     return ($ret);
2138   }
2139
2140
2141   function table_content($user, $table_idx)
2142   {
2143     $content = "";
2144     $ret = "";
2145     // TODO
2146     //
2147     //   Si possono usare i dati nella classe table
2148     //
2149     
2150     $sess = $user->sess;
2151     $table = &$this->table[$table_idx];
2152     
2153     if ($user->stat != 'room')
2154       return;
2155     
2156     $content = "[ ";
2157     for ($i = 0 ; $i < $table->player_n ; $i++) {
2158       $user_cur = &$this->user[$table->player[$i]];
2159
2160       $flags = $user_cur->flags;
2161
2162       if ($user_cur == $user) 
2163         $flags |= 1;
2164       
2165       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2166       
2167       $content .= sprintf('%s[ %d, "%s" ]',($i == 0 ? '' : ', '), $flags, xcape($user_cur->name));
2168     }
2169
2170     $content .= ' ]';
2171
2172     $ret .= sprintf('j_tab_cont(%d, %s);', $table_idx, $content);
2173     
2174     return ($ret);
2175   }
2176
2177 } // end class Room
2178
2179 function make_seed()
2180 {
2181   list($usec, $sec) = explode(' ', microtime());
2182   return (float) $sec + ((float) $usec * 100000);
2183 }
2184
2185
2186 function log_only2($log) {
2187   GLOBAL $sess;
2188
2189   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONL2) == 0)
2190     return;
2191
2192   if (isset($sess) == FALSE)
2193     $ssess = "XXXX";
2194   else
2195     $ssess = $sess;
2196
2197   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONL2) == 0)
2198     return;
2199
2200   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2201     fwrite($fp, sprintf("ONL2: [%s] [%s]\n", $ssess, $log));
2202     fclose($fp);
2203   }
2204 }
2205
2206 function log_crit($log) {
2207   GLOBAL $sess;
2208
2209   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CRIT) == 0)
2210     return;
2211
2212   if (isset($sess) == FALSE)
2213     $ssess = "XXXX";
2214   else
2215     $ssess = $sess;
2216
2217   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CRIT) == 0)
2218     return;
2219
2220   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2221     fwrite($fp, sprintf("CRIT: [%s] [%s]\n", $ssess, $log));
2222     fclose($fp);
2223   }
2224 }
2225
2226 function log_only($log) {
2227   GLOBAL $sess;
2228
2229   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONLY) == 0)
2230     return;
2231
2232   if (isset($sess) == FALSE)
2233     $ssess = "XXXX";
2234   else
2235     $ssess = $sess;
2236
2237   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONLY) == 0)
2238     return;
2239
2240   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2241     fwrite($fp, sprintf("ONLY: [%s] [%s]\n", $ssess, $log));
2242     fclose($fp);
2243   }
2244 }
2245
2246 function log_main($log) {
2247   GLOBAL $sess;
2248
2249   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_MAIN) == 0)
2250     return;
2251
2252   if (isset($sess) == FALSE)
2253     $ssess = "XXXX";
2254   else
2255     $ssess = $sess;
2256
2257   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_MAIN) == 0)
2258     return;
2259
2260   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2261     fwrite($fp, sprintf("MAIN: [%s] [%s]\n", $ssess, $log));
2262     fclose($fp);
2263   }
2264 }
2265
2266 function log_rd($log) {
2267   GLOBAL $sess;
2268
2269   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_READ) == 0)
2270     return;
2271
2272   if (isset($sess) == FALSE)
2273     $ssess = "XXXX";
2274   else
2275     $ssess = $sess;
2276
2277   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_READ) == 0)
2278     return;
2279
2280   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2281     fwrite($fp, sprintf("READ: [%s] [%s]\n", $ssess, $log));
2282     fclose($fp);
2283   }
2284 }
2285
2286 function log_rd2($log) {
2287   GLOBAL $sess;
2288
2289   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_REA2) == 0)
2290     return;
2291
2292   if (isset($sess) == FALSE)
2293     $ssess = "XXXX";
2294   else
2295     $ssess = $sess;
2296       
2297   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_REA2) == 0)
2298     return;
2299
2300   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2301     fwrite($fp, sprintf("REA2: [%s] [%s]\n", $ssess, $log));
2302     fclose($fp);
2303   }
2304 }
2305
2306 function log_send($log) {
2307   GLOBAL $sess;
2308
2309   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SEND) == 0)
2310     return;
2311
2312   if (isset($sess) == FALSE)
2313     $ssess = "XXXX";
2314   else
2315     $ssess = $sess;
2316       
2317   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SEND) == 0)
2318     return;
2319
2320   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2321     fwrite($fp, sprintf("SEND: [%s] [%s]\n", $ssess, $log));
2322     fclose($fp);
2323   }
2324 }
2325
2326 function log_lock($log) {
2327   GLOBAL $sess;
2328
2329   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOCK) == 0)
2330     return;
2331
2332   if (isset($sess) == FALSE)
2333     $ssess = "XXXX";
2334   else
2335     $ssess = $sess;
2336
2337   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOCK) == 0)
2338     return;
2339
2340   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2341     fwrite($fp, sprintf("LOCK: [%s] [%s]\n", $ssess, $log));
2342     fclose($fp);
2343   }
2344 }
2345
2346 function log_wr($log) {
2347   GLOBAL $sess;
2348
2349   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_WRIT) == 0)
2350     return;
2351
2352   if (isset($sess) == FALSE)
2353     $ssess = "XXXX";
2354   else
2355     $ssess = $sess;
2356       
2357   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_WRIT) == 0)
2358     return;
2359
2360   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2361     fwrite($fp, sprintf("WRIT: [%s] [%s]\n", $ssess, $log));
2362     fclose($fp);
2363   }
2364 }
2365
2366 function log_load($log) {
2367   GLOBAL $sess;
2368
2369   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOAD) == 0)
2370     return;
2371
2372   if (isset($sess) == FALSE)
2373     $ssess = "XXXX";
2374   else
2375     $ssess = $sess;
2376
2377   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOAD) == 0)
2378     return;
2379       
2380   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2381     fwrite($fp, sprintf("LOAD: [%s] [%s]\n", $ssess, $log));
2382     fclose($fp);
2383   }
2384 }
2385
2386 function log_auth($sess, $log) {
2387   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_AUTH) == 0)
2388     return;
2389
2390   if (( (BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_AUTH) == 0)
2391     return;
2392
2393   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2394     fwrite($fp, sprintf("AUTH: [%s] [%d] [%s]\n", $sess, time(), $log));
2395     fclose($fp);
2396   }
2397 }
2398
2399
2400 function log_legal($curtime, $sess, $name, $where, $mesg) 
2401 {
2402   GLOBAL $_SERVER;
2403
2404   if (($fp = @fopen(LEGAL_PATH."/legal.log", 'a')) != FALSE) {
2405     /* Unix time | session | nickname | IP | where was | mesg */
2406     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $curtime, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
2407     fclose($fp);
2408   }
2409 }
2410
2411
2412
2413
2414 function lock_banlist()
2415 {
2416   if (($tok = @ftok(FTOK_PATH."/main", "L")) == -1) {
2417     echo "FTOK FAILED";
2418     exit;
2419   }
2420   if (($res = sem_get($tok)) == FALSE) {
2421     echo "SEM_GET FAILED";
2422     exit;
2423   }
2424   if (sem_acquire($res)) 
2425     return ($res);
2426   else
2427     return (FALSE);
2428 }
2429
2430 function unlock_banlist($res)
2431 {
2432   return (sem_release($res));
2433 }
2434
2435 function table_act_content_old($isstanding, $sitted, $table, $cur_table)
2436 {
2437   $ret = "";
2438
2439   if ($isstanding) {
2440     if ($sitted < PLAYERS_N) {
2441       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
2442     }
2443   }
2444   else {
2445     if ($table == $cur_table)
2446       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
2447     else
2448       $ret = "";
2449   }
2450   return ($ret);
2451 }
2452
2453 function table_act_content($isstanding, $sitted, $table, $cur_table, $allowed)
2454 {
2455   $ret = "";
2456
2457   if ($isstanding) {
2458     if ($sitted < PLAYERS_N) {
2459       if ($allowed)
2460         $act = 'sit';
2461       else
2462         $act = 'reserved';
2463     }
2464   }
2465   else {
2466     if ($table == $cur_table)
2467       $act = 'wake';
2468     else
2469       $act = 'none';
2470   }
2471
2472   if ($act != '')
2473     $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
2474
2475   return ($ret);
2476 }
2477
2478 function show_notify($text, $tout, $butt, $w, $h)
2479 {
2480   log_main("SHOW_NOTIFY: ".$text);
2481   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
2482 }
2483
2484 function briscola_show($room, $table, $user)
2485 {
2486   $ptnadd = "";
2487   $ret = "";
2488
2489   if ($table->asta_card == 9) 
2490     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
2491   
2492   /* text of caller cell */
2493   if ($user->table_pos == $table->asta_win) 
2494     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
2495   else 
2496     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
2497                     xcape($room->user[$table->player[$table->asta_win]]->name), $ptnadd);
2498
2499   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
2500                   $table->asta_win);
2501   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
2502   $ret .= sprintf('$("caller").style.visibility = "visible";');
2503   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
2504   $ret .= sprintf('$("astalascio").style.visibility = "";');
2505   $ret .= sprintf('$("asta").style.visibility = "hidden";');
2506   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
2507   
2508   return ($ret);
2509 }
2510
2511
2512 function game_result($asta_pnt, $pnt)
2513 {
2514   if ($asta_pnt == 61) {
2515     if ($pnt > 60)
2516       return (1);
2517     else if ($pnt == 60)
2518       return (0);
2519     else
2520       return (-1);
2521   }
2522   else {
2523     if ($pnt >= $asta_pnt)
2524       return (1);
2525     else
2526       return (-1);
2527   }
2528 }
2529
2530 function multoval($mult)
2531 {
2532   if ($mult == 2)
2533     return ("doppio");
2534   else if ($mult == 4)
2535     return ("quadruplo");
2536   else
2537     return (sprintf("%d-plo", $mult));
2538 }
2539
2540 function show_table_info(&$room, &$table, $table_pos)
2541 {
2542   $ret = "";
2543   $user = &$room->user[$table->player[$table_pos]];
2544
2545   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
2546   $noty = sprintf('<table class=\"points\"><tr><th></th>');
2547   
2548   // Names.
2549   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
2550     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($room->user[$table->player[$i]]->name));
2551   $noty .= sprintf("</tr>");
2552
2553   // Points.
2554   log_main("show_table_info: pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
2555
2556   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
2557     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
2558     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
2559       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
2560     $noty .= "</tr>";
2561   }
2562
2563   // Total points.
2564   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
2565   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
2566     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
2567   $noty .= "</tr></table>";
2568
2569   if ($table->old_reason != "") {
2570     $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
2571   }
2572
2573   if ($table->old_win != -1) {
2574     $win = $table->player[$table->old_win];
2575     $fri = $table->player[$table->old_friend];
2576
2577     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
2578
2579     if ($win != $fri) {
2580       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
2581                        xcape($room->user[$win]->name),
2582                        xcape($room->user[$fri]->name));
2583       if ($table->old_pnt == 120) {
2584         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
2585       }
2586       else {
2587         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
2588                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
2589                           'pi&ugrave; di 60'), $table->old_pnt,
2590                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
2591       }
2592     }
2593     else {
2594       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
2595                        xcape($room->user[$win]->name));
2596       if ($table->old_pnt == 120) {
2597         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
2598       }
2599       else {
2600         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
2601                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
2602                           'pi&ugrave; di 60'), $table->old_pnt,
2603                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
2604       }
2605     }
2606   }
2607   if ($table->mazzo == $table_pos) 
2608     $noty .= "Fai <b>tu</b> il mazzo,";
2609   else {
2610     $unam = xcape($room->user[$table->player[$table->mazzo]]->name);
2611     $noty .= "Il mazzo a <b>$unam</b>,";
2612   }
2613
2614   if ($user->subst == 'asta') {
2615     if ($table->asta_win == -1)  // auction case
2616       $curplayer = $table->gstart % PLAYERS_N;
2617     else 
2618       $curplayer = $table->asta_win;
2619   }
2620   else if ($user->subst == 'game') {
2621     $curplayer = ($table->gstart + $table->turn) % PLAYERS_N;
2622   }
2623
2624
2625   if ($curplayer == $table_pos) {
2626     $noty .= " tocca a <b>te</b> giocare.";
2627   }
2628   else {
2629     $unam = xcape($room->user[$table->player[$curplayer]]->name);
2630     $noty .= " tocca a <b>$unam</b> giocare.";
2631   }
2632   
2633   if ($table->mult > 1) {
2634     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
2635   }
2636   $noty .= "<hr><br>";
2637   $ret .= show_notify($noty, 3000, "torna alla partita", 500, 400);
2638   /* NOTE: show_notify($noty, 3000, "torna alla partita", 500, 
2639    *                   130 + ($table->points_n > 0 ? 50 : 0) + 
2640    *                   (120 * ($table->points_n / MAX_POINTS)));
2641    *       will be used when we refact notify js function following 
2642    *       photoo class logic 
2643    */ 
2644   
2645   return ($ret);
2646 }
2647
2648 function root_wellcome($user)
2649 {
2650   GLOBAL $root_wellarr;
2651   $ret = "";
2652
2653   $curtime = time();
2654   $dt = date("H:i ", $curtime);
2655     
2656   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
2657     $ret .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, str_replace('"', '\"', $root_wellarr[$i]));
2658
2659   return ($ret);
2660 }
2661
2662 function table_wellcome($user)
2663 {
2664   GLOBAL $table_wellarr;
2665   $ret = "";
2666
2667   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
2668     $ret .= sprintf('chatt_sub("%s", [2, "ChanServ: "],"%s");', "", str_replace('"', '\"', $table_wellarr[$i]));
2669
2670   return ($ret);
2671 }
2672
2673
2674
2675 /* show table 
2676 is_transition (is from room to table ?)
2677 is_again      (is another game)
2678
2679 Examples                    of $is_transition, $is_again:
2680   from reload of the page:              FALSE, FALSE
2681   from sitdown in room:                  TRUE, FALSE
2682   from table: asta cmd e tutti passano:  TRUE, TRUE
2683   from table: fine partita:              TRUE, TRUE
2684  */
2685 function show_table(&$room, &$user, $sendstep, $is_transition, $is_again)
2686 {
2687   $table_idx = $user->table;
2688   $table = &$room->table[$table_idx];
2689   $table_pos = $user->table_pos;
2690
2691   $ret = "table_init();";
2692   $ret .= $table->exitlock_show(&$room->user, $table_pos);
2693   if (!$is_again) {
2694     /* GENERAL STATUS */
2695     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
2696                      $sendstep, $user->stat, $user->subst, $table_pos);
2697
2698     log_rd(sprintf( 'SHOW_TABLE: gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
2699                      $sendstep, $user->stat, $user->subst, $table_pos));
2700
2701     /* BACKGROUND */
2702     $ret .= "background_set();";
2703     
2704     /* USERS INFO */
2705     $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
2706     $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
2707
2708     $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>";', $itin, xcape($user->name), $itou);
2709     $ret .= sprintf('set_names([%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"]); ',
2710                     $room->user[$table->player[($table_pos)%PLAYERS_N]]->flags,
2711                     xcape($room->user[$table->player[($table_pos)%PLAYERS_N]]->name),
2712
2713                     $room->user[$table->player[($table_pos+1)%PLAYERS_N]]->flags,
2714                     xcape($room->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
2715
2716                     $room->user[$table->player[($table_pos+2)%PLAYERS_N]]->flags,
2717                     xcape($room->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
2718
2719                     (PLAYERS_N == 3 ? 0 : $room->user[$table->player[($table_pos+3)%PLAYERS_N]]->flags),
2720                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
2721
2722                     (PLAYERS_N == 3 ? 0 : $room->user[$table->player[($table_pos+4)%PLAYERS_N]]->flags),
2723                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
2724   }
2725   /* NOTIFY FOR THE CARD MAKER */
2726   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
2727     $ret .= show_table_info(&$room, &$table, $table_pos);
2728   }
2729   if (!$is_again) 
2730     $ret .= table_wellcome($user);
2731
2732   if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
2733     $ret .= playsound("cow.mp3");
2734   }
2735
2736
2737   /* CARDS */
2738   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
2739     $ret .= "|";
2740     
2741     for ($i = 0 ; $i < 8 ; $i++) {
2742       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
2743         $ct = 0;
2744         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
2745           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
2746             $ct++;
2747             if ($ct == $i+1)
2748               break;
2749           }
2750         }
2751         log_rd("O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
2752         
2753         $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
2754                          $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
2755                               $table->card[$o]->value : -1), 
2756                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
2757       }
2758     }    
2759   }
2760   else {
2761     $taked  = array(0,0,0,0,0);
2762     $inhand = array(0,0,0,0,0);
2763     $ontabl  = array(-1,-1,-1,-1,-1);
2764     $cards  = array();
2765
2766     for ($i = 0 ; $i < 40 ; $i++) {
2767       if ($table->card[$i]->stat == 'hand') {
2768         if ($table->card[$i]->owner == $table_pos) {
2769           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
2770         }
2771         $inhand[$table->card[$i]->owner]++;
2772       }
2773       else if ($table->card[$i]->stat == 'take') {
2774         log_main("Card taked: ".$table->card[$i]->value."OWN: ".$table->card[$i]->owner);
2775         $taked[$table->card[$i]->owner]++;
2776       }
2777       else if ($table->card[$i]->stat == 'table') {
2778         $ontabl[$table->card[$i]->owner] = $i;
2779       }
2780     }
2781     $logg = "\n";
2782     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2783       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
2784     }
2785     log_main("Stat table: ".$logg);
2786
2787     /* Set ours cards. */
2788     $oursarg = "";
2789     for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
2790       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
2791     for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
2792       $oursarg .= ($i == 0 ? "" : ", ")."-1";
2793     $ret .= sprintf('card_setours(%s);', $oursarg);
2794
2795     /* Dispose all cards */
2796     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2797       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
2798       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
2799                       $inhand[$i], $taked[$i]);
2800
2801       if ($ontabl[$i] != -1) {
2802         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
2803                         $table->card[$ontabl[$i]]->value, 
2804                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
2805       }
2806     }
2807   }
2808
2809   /* Show auction */
2810   if ($user->subst == 'asta') {
2811
2812     /* show users auction status */
2813     $showst = "";
2814     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2815       $user_cur = &$room->user[$table->player[$i]];
2816       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
2817                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
2818     }
2819     if (PLAYERS_N == 3)
2820         $showst .= ",-2,-2";
2821     $ret .= sprintf('show_astat(%s);', $showst);
2822
2823     if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
2824       /* show card chooser */
2825       $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
2826                       $table->asta_card);
2827     }
2828     else {
2829       /* show auction */
2830       if ($table_pos == ($table->gstart % PLAYERS_N) &&
2831           $table->asta_win == -1) 
2832         $ret .= sprintf('dispose_asta(%d,%d, %s);', 
2833                         $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
2834       else
2835         $ret .= sprintf('dispose_asta(%d,%d, %s);',
2836                         $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
2837     }
2838
2839     /* Remark */
2840     if ($table->asta_win == -1) { // auction case
2841       if ($table_pos == ($table->gstart % PLAYERS_N)) 
2842         $ret .= "remark_on();";
2843       else
2844         $ret .= "remark_off();";
2845     }
2846     else { // chooseed case
2847       if ($table_pos == $table->asta_win) 
2848         $ret .= "remark_on();";
2849       else
2850         $ret .= "remark_off();";
2851     }
2852   }
2853   else if ($user->subst == 'game') {
2854     /* HIGHLIGHT */
2855     if (($table->gstart + $table->turn) % PLAYERS_N == $table_pos) 
2856       $ret .= "is_my_time = true; remark_on();";
2857     else
2858       $ret .= "remark_off();";
2859     
2860     /* WHO CALL AND WATH */
2861     $ret .= briscola_show($room, $table, $user);
2862     
2863   }
2864   return ($ret);
2865 } // end function show_table(...
2866
2867 function calculate_winner(&$table)
2868 {
2869   $briontab = FALSE;
2870   $ontab = array();
2871   $ontid = array();
2872   $cur_win  =  -1;
2873   $cur_val  = 100;
2874   $cur_seed = $table->briscola - ($table->briscola % 10);
2875
2876   for ($i = 0 ; $i < 40 ; $i++) {
2877     if ($table->card[$i]->stat != "table")
2878       continue;
2879
2880     log_wr(sprintf("Card On table: [%d]", $i));
2881
2882     $v = $table->card[$i]->value; 
2883     $ontab[$table->card[$i]->owner] = $v;
2884     $ontid[$table->card[$i]->owner] = $i;
2885     /* se briscola setto il flag */
2886     if (($v - ($v % 10)) == $cur_seed)
2887       $briontab = TRUE;
2888   }
2889
2890   if ($briontab == FALSE) {
2891     $cur_win  = $table->gstart;
2892     $cur_val  = $ontab[$cur_win];
2893     $cur_seed = $cur_val - ($cur_val % 10);
2894   }
2895
2896   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2897     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
2898       if ($ontab[$i] < $cur_val) {
2899         $cur_val = $ontab[$i];
2900         $cur_win = $i;
2901       }
2902     }
2903   }
2904
2905   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2906     $table->card[$ontid[$i]]->owner = $cur_win;
2907     $table->card[$ontid[$i]]->stat =  "take"; // Card stat
2908   }
2909   return ($cur_win);
2910 }
2911
2912 function calculate_points(&$table)
2913 {
2914   GLOBAL $G_all_points; 
2915
2916   $pro = 0;
2917
2918   if ($table->asta_pnt == 60)
2919     $table->asta_pnt = 61;
2920
2921   $table->old_reason = "";
2922   $table->old_win = $table->asta_win;
2923   $table->old_friend = $table->friend;
2924   $table->old_asta_pnt = $table->asta_pnt;
2925
2926   for ($i = 0 ; $i < 40 ; $i++) {
2927     $ctt = $table->card[$i]->value % 10;
2928     $own = $table->card[$i]->owner;
2929     if ($own == $table->asta_win || $own == $table->friend) 
2930       $pro += $G_all_points[$ctt];
2931   }
2932
2933   log_wr(sprintf("PRO: [%d]", $pro));
2934
2935   
2936   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
2937     $table->points[$table->points_n % MAX_POINTS] = array();
2938     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
2939       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
2940     $table->points_n++;
2941     $table->old_pnt = $pro;
2942     $table->mult *= 2;
2943
2944     return;
2945   }
2946
2947   if ($pro >= $table->asta_pnt) 
2948     $sig = 1;
2949   else
2950     $sig = -1;
2951
2952   $table->points[$table->points_n % MAX_POINTS] = array();
2953   for ($i = 0 ; $i < 5 ; $i++) {
2954     if ($i == $table->asta_win) 
2955       $pt = ($i == $table->friend ? 4 : 2);
2956     else if ($i == $table->friend) 
2957       $pt = 1;
2958     else
2959       $pt = -1;
2960
2961     log_wr(sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
2962
2963     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
2964
2965     log_wr(sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
2966     
2967     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
2968     $table->total[$i] += $pt;
2969   }
2970   $table->points_n++;
2971   $table->old_pnt = $pro;
2972   $table->mult = 1;
2973 }
2974
2975 function validate_sess($sess) 
2976 {
2977   if (strlen($sess) == SESS_LEN) 
2978     return (TRUE);
2979   else
2980     return (FALSE);
2981 }
2982
2983 function validate_name($name) 
2984 {
2985   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
2986
2987   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2988     $c = $name_new[$i];
2989     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2990       return ($name_new);
2991   }
2992
2993   return (FALSE);
2994 }
2995
2996 function playsound($filename)
2997 {
2998   return (sprintf('playsound("flasou", "%s");', $filename));
2999 }
3000
3001 function secstoword($secs)
3002 {
3003   $mins = floor($secs / 60);
3004   $secs = $secs % 60;
3005   if ($mins > 0) 
3006     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
3007   
3008   if ($secs > 0)
3009     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
3010   
3011   return ($ret);
3012 }
3013
3014 function sharedmem_sz($tok)
3015 {
3016   if (($shm_id = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
3017     log_main("shmop_open failed");
3018     return (-1);
3019   }
3020   $shm_sz = shmop_size($shm_id);
3021   shmop_close($shm_id);
3022   
3023   log_main("shm_sz: ".$shm_sz."   SHM_DIMS: ".SHM_DIMS);
3024   return ($shm_sz);
3025 }    
3026
3027 class Warrant {
3028   function lock_data()
3029   {
3030     GLOBAL $sess; 
3031     
3032     if (($tok = @ftok(FTOK_PATH."/warrant", "B")) == -1) {
3033       echo "FTOK FAILED";
3034       exit;
3035     }
3036     // echo "FTOK ".$tok."<br>";
3037     if (($res = sem_get($tok)) == FALSE) {
3038       echo "SEM_GET FAILED";
3039       exit;
3040     }
3041     if (sem_acquire($res)) {   
3042       log_lock("LOCK room");
3043       return ($res);
3044     }
3045     else
3046       return (FALSE);
3047   }
3048   
3049   function unlock_data($res)
3050   {
3051     GLOBAL $sess; 
3052     
3053     log_lock("UNLOCK room");
3054     
3055     return (sem_release($res));
3056   }
3057
3058   
3059 }
3060 ?>