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