'alarm bug' fixed
[brisk.git] / web / Obj / brisk.phh
1 <?php
2 /*
3  *  brisk - brisk.phh
4  *
5  *  Copyright (C) 2006-2009 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, 36);
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, 0xffffffbf);
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 $G_lang = "it";
78 $G_lng = "";
79 // $G_lang = "en";
80 // $G_lng = "_en";
81
82 $G_all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
83 $G_brisk_version = "2.1.7 - trusty";
84
85 /* MLANG: ALL THE INFO STRINGS IN brisk.phh */
86 $root_wellarr = Array ( 'Brisk (Ver. '.$G_brisk_version.'), <b>NOVITA\'</b>: menu comandi, filtro opzionale sui non autenticati e "return bug" corretto.',
87                         'Se vuoi iscriverti alla <a target="_blank" href="http://www.milug.org/cgi-bin/mailman/listinfo/ml-briscola">Mailing List</a>, cliccala!' );
88
89 $G_room_help= '
90 <div style=\\"text-align: left; padding: 8px;\\">
91 <b>Descrizione</b><br>
92 Questa รจ un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
93 <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>
94 <b>Configurazione del browser.</b><br>
95 Occorre abilitare i cookies.<br>
96 <br>
97 <b>Uso del sito</b><br>
98 Potete sedervi a un tavolo o rimanere in piedi.<br>
99 Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la partita.<br>
100 <br>
101 <b>Partita</b><br>
102 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>
103 Chi vince l\'asta dovr&agrave; decidere il seme della carta scelta e inizier&agrave; la mano.<br>
104 Per giocare le carte dovrete trascinarle nel quadrato al centro del vostro schermo.<br><br>
105 Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno al quadrato al centro del vostro schermo.<br><br>
106 Durante la partita, se vorrete ricaricare la pagina, usate l\'apposito bottone \\"reload\\" in basso a destra.<br>
107 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.
108 <dl>
109 <dt><b>Comandi della chat</b>
110 <dd><b>/nick <i>&lt;nuovo_nickname&gt;</i></b> - cambio di nickname
111 <dd><b>/tav <i>&lt;frase di invito&gt;</i></b> - invito per gli altri giocatori al tavolo dove si &egrave; seduti 
112 <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\\"
113 <dd><b>/garante</b> - se si &egrave; autenticati permette di garantire per un utente fidato
114 <dd><b>/mesgtoadm</b> - se si &egrave; autenticati permette di lasciare un messaggio all\'amministratore del sito
115 <dd><b>/listen &lt;all or auth&gt;</b> - se si &egrave; autenticati permette leggere solo i messaggi degli altri autenticati (auth) o di tutti (all)
116 </dl>
117 </div>
118 ';
119
120 //  
121
122 $G_room_about= '<br>
123 <div id=\\"header\\" class=\\"header\\">
124   <img class=\\"nobo\\" src=\\"img/brisk_logo64.png\\">
125   briscola chiamata in salsa ajax
126 </div>
127 <br><b>version '.$G_brisk_version.'</b><br><br>
128 Copyright 2006-2008 <a href=\\"mailto:brisk@alternativeoutput.it\\">Matteo Nastasi</a> (aka mop)<br><br>';
129
130
131 function xcape($s)
132 {
133   $from = array (   '\\',     '@',        '|' );
134   $to   = array ( '\\\\', '&#64;', '&brvbar;' );
135
136   return (str_replace($from, $to, htmlentities($s,ENT_COMPAT,"UTF-8")));
137 }
138
139 function xcapelt($s)
140 {
141   $from = array (   '\\',     '|',  "\t",  "\n");
142   $to   = array ( '\\\\',   '\\|', "\\t", "\\n");
143
144   return (str_replace($from, $to, $s));
145 }
146
147 function xcapemesg($s)
148 {
149   $from = array (  "\n");
150   $to   = array ( "\\n");
151
152   return (str_replace($from, $to, $s));
153 }
154
155
156 class Table {
157   var $idx;
158   var $player;
159   var $player_n;
160
161   var $auth_only;     // se tavolo riservato o libero
162
163   var $wag_own;
164   var $wag_com;
165   var $wag_tout;
166
167   var $table_token;
168   var $table_start;   // information field
169
170   var $wakeup_time;
171
172   function Table() 
173   {
174   }
175   
176   function &create($idx) 
177   {
178     GLOBAL $G_false;
179
180     if (($thiz =& new Table()) == FALSE)
181       return ($G_false);
182
183     $thiz->idx       =   $idx;
184     $thiz->player    =   array();
185     $thiz->player_n  =   0;
186     $thiz->auth_only =   FALSE;
187
188     $thiz->wag_own   =  NULL;
189     $thiz->wag_com   =  "";
190     $thiz->wag_tout   =  0;
191
192     $thiz->table_token  = "";
193     $thiz->table_start  = 0;
194     
195     $thiz->wakeup_time = 0;
196
197     return ($thiz);
198   }
199
200   function copy(&$from)
201   {
202     GLOBAL $G_false;
203     
204     $this->idx = $from->idx;
205     $this->player = array();
206     for ($i = 0 ; $i < $from->player_n ; $i++)
207       $this->player[$i] = $from->player[$i];
208     $this->player_n = $from->player_n;
209
210     log_main("PLAYER_N - parent::copy.".$this->player_n);
211     
212     $this->auth_only =  $from->auth_only;
213
214     $this->wag_own   =  $from->wag_own;
215     $this->wag_com   =  $from->wag_com;
216     $this->wag_tout  =  $from->wag_tout;
217
218     $this->table_token  = $from->table_token;
219     $this->table_start  = $from->table_start;
220
221     $this->wakeup_time = $from->wakeup_time;
222   }
223
224   function &clone(&$from)
225   {
226     GLOBAL $G_false;
227     
228     if (($thiz =& new Table()) == FALSE)
229       return ($G_false);
230
231     $this->copy($from);
232
233     return ($thiz);
234   }
235   
236   function &spawn(&$from)
237   {
238     GLOBAL $G_false;
239     
240     if (($thiz =& new Table()) == FALSE)
241       return ($G_false);
242     
243     $thiz->idx = $from->idx;
244     $thiz->player = array();
245     for ($i = 0 ; $i < $from->player_n ; $i++)
246       $thiz->player[$i] = $i;
247     $thiz->player_n = $from->player_n;
248
249     $thiz->auth_only =  $from->auth_only;
250
251     $thiz->wag_own = $from->wag_own;
252     $thiz->wag_com = $from->wag_com;
253     $thiz->wag_tout  =  $from->wag_tout;
254
255     $thiz->table_token  = $from->table_token;
256     $thiz->table_start  = $from->table_start;
257
258     $thiz->wakeup_time = $from->wakeup_time;
259
260     return ($thiz);
261   }
262
263   function wag_set(&$user, $mesg)
264   {
265     log_main("WAG_SET");
266
267     $this->wag_own  = &$user;
268     $this->wag_com  =  $mesg;
269     $this->wag_tout =  0;
270   }
271
272   function wag_reset($timeout)
273   {
274     log_main("WAG_RESET");
275
276     unset($this->wag_own);
277     $this->wag_own = NULL;
278     $this->wag_com  = "";
279     $this->wag_tout = $timeout;
280   }
281
282   function getPlayer($idx)
283   {
284     return ($this->player[$idx]);
285   }
286
287   function setPlayer($idx, $player)
288   {
289     $this->player[$idx] = $player;
290   }
291
292   function user_add($idx)
293   {
294     $this->player[$this->player_n] = $idx;
295     $this->player_n++;
296     
297     return ($this->player_n - 1);
298   }
299   
300   function user_rem(&$room, &$user)
301   {
302     $tabpos = $user->table_pos;
303     
304     /* verifico la consistenza dei dati */
305     if ($room->user[$this->player[$tabpos]] == $user) {
306       
307       /* aggiorna l'array dei giocatori al tavolo. */
308       for ($i = $tabpos ; $i < $this->player_n-1 ; $i++) {
309         $this->player[$i] = $this->player[$i+1];
310         $user_cur = &$room->user[$this->player[$i]];
311         $user_cur->table_pos = $i;
312       }
313       $this->player_n--;
314     }
315     else {
316       log_main("INCONSISTENCY ON TABLE.");
317     }
318   }
319
320
321
322   //      $ret .= table_act_content(($user->subst == 'standup'), $this->table[$i]->player_n, $i, $user->table, 
323   //                              ($this->table[$i]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
324
325   // function act_content($isstanding, $sitted, $table, $cur_table, $allowed)
326   function act_content(&$user)
327   {
328     $ret = "";
329     $isstanding = ($user->subst == 'standup');
330     $sitted = $this->player_n;
331     $table = $this->idx;
332     $cur_table = $user->table;
333     $allowed = TRUE;
334
335     if ($isstanding) {
336       if ($sitted < PLAYERS_N) {
337         if ($this->auth_only) {
338           if ($user->flags & USER_FLAG_AUTH) 
339             $act = "sitreser";
340           else
341             $act = 'reserved';
342         }
343         else {
344           $act = 'sit';
345         }
346       }
347       else {
348         $act = 'none';
349       }
350     }
351     else {
352       if ($table == $cur_table)
353         $act = 'wake';
354       else
355         $act = 'none';
356     }
357     
358     if ($act != '')
359       $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
360     
361     return ($ret);
362   }
363 } // end class Table
364
365
366 // User flags
367 define(USER_FLAG_AUTH,     0x02);
368 define(USER_FLAG_LISTAUTH, 0x04);
369
370 //   user status
371 define(USER_FLAG_S_NORM,  0x000); // done
372 define(USER_FLAG_S_PAU,   0x100); // done
373 define(USER_FLAG_S_OUT,   0x200); // done
374 define(USER_FLAG_S_DOG,   0x300); // done
375 define(USER_FLAG_S_EAT,   0x400); // done
376 define(USER_FLAG_S_WRK,   0x500); // done
377 define(USER_FLAG_S_SMK,   0x600); // done
378 define(USER_FLAG_S_EYE,   0x700); // done
379
380 define(USER_FLAG_S_ALL,   0xf00); // done
381
382 class User {
383   var $name;       // name of the user
384   var $sess;       // session of the user
385   var $ip;         // ip of the user
386   var $lacc;       // last access (for the cleanup)
387   var $laccwr;     // last access (for the cleanup)
388   var $bantime;    // timeout to temporary ban
389   var $stat;       // status (outdoor, room, table, game, ...)
390   var $subst;      // substatus for each status   
391   var $step;       // step of the current status
392   var $trans_step; // step to enable transition between pages (disable == -1)
393   var $comm;       // commands array
394   // var $asta_card;  // 
395   // var $asta_pnt;   //
396   // var $handpt;     // Total card points at the beginning of the current hand.
397   // var $exitislock; // Player can exit from the table ?
398
399   // FIXME: the table_orig field must be removed after table field verify of index management (in spawned table
400   //        it is allways ZERO
401   var $table_orig; // id of the current table (if in table state)
402   var $table;      // id of the current table (if in table state)
403   var $table_pos;  // idx on the table
404   var $table_token;// token that identify a game on a table
405   var $flags;      // Bitfield with: AUTHENTICATE: 0x02 
406   var $the_end;    // Flag to change the end of the session
407
408   var $chat_lst;      // Last chat line
409   var $chattime;      // Array of chat times
410   var $chat_cur;      // Current chat line number
411   var $chat_ban;      // Time for ban chat
412   var $chat_dlt;      // Delta t for ban
413   function User() {
414   }
415
416   function &create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
417     GLOBAL $G_false;
418
419     if (($thiz =& new User()) == FALSE)
420       return ($G_false);
421
422     $thiz->name  = $name;
423     $thiz->sess  = $sess;
424     $thiz->ip    = $ip;
425     $thiz->lacc   = time();
426     $thiz->laccwr = time();
427     $thiz->bantime = 0;
428     $thiz->stat  = $stat;
429     $thiz->subst  = $subst;
430     $thiz->step  = 1;
431     $thiz->trans_step  = -1;
432     $thiz->comm  = array();
433     $thiz->asta_card = -2;
434     $thiz->asta_pnt  = -1;
435     $thiz->handpt = -1;
436     $thiz->exitislock = TRUE;
437
438     $thiz->flags = 0x00;
439     
440     $thiz->chattime = array_fill(0, CHAT_N, 0);
441     $thiz->chat_cur = 0;
442     $thiz->chat_lst = "";
443     $thiz->chat_ban = 0;
444     $thiz->chat_dlt = 0;
445
446     $thiz->table_orig = $table;
447     $thiz->table      = $table;
448     $thiz->table_pos = -1;
449     $thiz->table_token = "";
450
451     return ($thiz);
452   }
453
454   function copy(&$from)
455   {
456     GLOBAL $G_false;
457     
458     $this->name       = $from->name;
459     $this->sess       = $from->sess;
460     $this->ip         = $from->ip;
461     $this->lacc       = $from->lacc;
462     $this->laccwr     = $from->laccwr;
463     $this->bantime    = $from->bantime;
464     $this->stat       = $from->stat;
465     $this->subst      = $from->subst;
466     $this->step       = $from->step;
467     $this->trans_step = $from->trans_step;
468     $this->comm       = array();
469
470     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
471     for ($i = $i_start ; $i < $from->step ; $i++) {
472       $ii = $i % COMM_N;
473       $this->comm[$ii] = $from->comm[$ii];
474     }
475     $this->asta_card  = $from->asta_card;
476     $this->asta_pnt   = $from->asta_pnt;
477     $this->handpt     = $from->handpt;
478     $this->exitislock = $from->exitislock;
479
480     $this->flags = $from->flags;
481
482     $this->chattime = array();
483     for ($i = 0 ; $i < CHAT_N ; $i++)
484       $this->chattime[$i] = $from->chattime[$i];
485     $this->chat_cur = $from->chat_cur;
486     $this->chat_lst = $from->chat_lst;
487     $this->chat_ban = $from->chat_ban;
488     $this->chat_dlt = $from->chat_dlt;
489
490     $this->table_orig = $from->table_orig;
491     $this->table      = $from->table;
492     $this->table_pos  = $from->table_pos;
493     $this->table_token = $from->table_token;
494     $this->the_end    = $from->the_end;
495
496     return (TRUE);
497   }
498
499
500   function &clone(&$from)
501   {
502     GLOBAL $G_false;
503     
504     if (($thiz =& new User()) == FALSE)
505       return ($G_false);
506     
507     $thiz->copy($from);
508
509     return ($thiz);
510   }
511   
512   function &spawn(&$from, $table, $table_pos)
513   {
514     GLOBAL $G_false;
515     
516     if (($thiz =& new User()) == FALSE)
517       return ($G_false);
518     
519     $thiz->name       = $from->name;
520     $thiz->sess       = $from->sess;
521     $thiz->ip         = $from->ip;
522     $thiz->lacc       = $from->lacc;
523     $thiz->laccwr     = $from->laccwr;
524     $thiz->bantime    = $from->bantime;
525     $thiz->stat       = $from->stat;
526     $thiz->subst      = $from->subst;
527     $thiz->step       = $from->step;
528     $thiz->trans_step = $from->trans_step;
529     $thiz->comm       = array();
530
531     /*
532     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
533     for ($i = $i_start ; $i < $from->step ; $i++) {
534       log_wr("TRY PUSH:".$i);
535       $ii = $i % COMM_N;
536       $thiz->comm[$ii]   = $from->comm[$ii];
537     }
538     */
539     $thiz->asta_card  = $from->asta_card;
540     $thiz->asta_pnt   = $from->asta_pnt;
541     $thiz->handpt     = $from->handpt;
542     $thiz->exitislock = $from->exitislock;
543     $thiz->the_end    = $from->the_end;
544
545     $thiz->flags      = $from->flags;
546
547     $thiz->chattime   = array_fill(0, CHAT_N, 0);
548     $thiz->chat_cur   = 0;
549     $thiz->chat_lst   = "";
550     $thiz->chat_ban   = 0;
551     $thiz->chat_dlt   = 0;
552
553
554     $thiz->table_orig = $table;
555     $thiz->table      = 0;
556     $thiz->table_pos  = $table_pos;
557     $thiz->table_token = $from->table_token;
558
559     return ($thiz);
560   }
561   
562   function stat_set($stat) {
563     log_main("sess: [".$this->sess. "] NEW STAT: [".$stat."]"); 
564     $this->stat = "$stat";
565     
566     /*
567     if (validate_sess($this->sess)) {
568       if (file_exists(PROXY_PATH) == FALSE)
569         mkdir(PROXY_PATH);
570       $fp = fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
571       fwrite($fp, sprintf("%s\n",$this->stat));
572       fclose($fp);
573     }
574     */
575   }
576
577   function step_set($step) {
578     $this->step = $step;
579     
580     do {
581       if (validate_sess($this->sess) == FALSE)
582         break;
583       if (file_exists(PROXY_PATH) == FALSE)
584         mkdir(PROXY_PATH);
585       if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
586         break;
587       fwrite($fp, pack("l",$this->step), 4);
588       fclose($fp);
589
590       return (TRUE);
591     } while (0);
592
593     return (FALSE);
594   }
595
596   function step_inc($delta = 1) {
597     $this->step += $delta;
598     
599     if (validate_sess($this->sess)) {
600       if (file_exists(PROXY_PATH) == FALSE)
601         mkdir(PROXY_PATH);
602       $fp = fopen(PROXY_PATH."/".$this->sess.".step", 'w');
603       fwrite($fp, pack("l",$this->step), 4);
604       fclose($fp);
605
606       return (TRUE);
607     }
608     
609     return (FALSE);
610   }
611
612   function reset() {
613     $curtime = time();
614     log_legal($curtime, $this, "STAT:LOGOUT", '');
615
616     $tmp_sess = $this->sess;
617     $this->sess = "";
618     step_unproxy($tmp_sess);
619     $this->name = "";  // OK here
620     while (array_pop($this->comm) != NULL);
621     $this->step = 0;
622     $this->chattime = array_fill(0, CHAT_N, 0);
623     $this->chat_cur = 0;
624     $this->chat_lst = "";
625     $this->chat_ban = 0;
626     $this->chat_dlt = 0;
627     $this->the_end = FALSE;
628   }
629 } // end class User
630
631
632
633
634
635
636
637 function step_get($sess) {
638   $fp = FALSE;
639   do {
640     if (validate_sess($sess) == FALSE)
641       break;
642
643     if (file_exists(PROXY_PATH) == FALSE)
644       mkdir(PROXY_PATH);
645     if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
646       break;
647     if (($s = fread($fp, 4)) == FALSE)
648       break;
649     if (strlen($s) != 4)
650       break;
651     $arr = unpack('l', $s);
652     fclose($fp);
653
654     // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
655     return ($arr[1]);
656   } while (0);
657
658   if ($fp != FALSE)
659     fclose($fp);
660
661   log_rd2("STEP_GET: return false ");
662
663   return (FALSE);
664 }
665
666 function step_unproxy($sess) {
667   log_rd2("UNPROXY: ".PROXY_PATH."/".$sess.".step");
668   if (file_exists(PROXY_PATH) == FALSE)
669     mkdir(PROXY_PATH);
670   @unlink(PROXY_PATH."/".$sess.".step");
671 }
672
673
674 class Room {
675   var $user;
676   var $table;
677   var $comm; // commands for many people
678   var $step; // current step of the comm array
679   var $garbage_timeout;
680   var $shm_sz;
681
682   function Room () {
683     $this->user = array();
684     $this->table = array();
685
686     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
687       $this->user[$i] =& User::create("", "");
688     }
689
690     for ($i = 0 ; $i < TABLES_N ; $i++) {
691       $this->table[$i] =& Table::create($i);
692       /* OLD METHOD
693       if ($i < 12) {
694         $row = ( (((int)($i / 4)) % 2) == 0 );
695         $col = ($i % 2 == 0);
696         $this->table[$i]->auth_only = (($row && $col) || (!$row && !$col));
697       }
698       else {
699         $this->table[$i]->auth_only = FALSE;
700       }
701       */
702       if ($i < 12) 
703         $this->table[$i]->auth_only = TRUE;
704       else
705         $this->table[$i]->auth_only = FALSE;
706     }
707     $this->garbage_timeout = 0;
708   }
709
710   function garbage_manager($force)
711   {
712     $ismod = FALSE;
713
714     log_rd2("garbage_manager START");
715
716     /* Garbage collector degli utenti in timeout */
717     $curtime = time();
718     if ($force || $this->garbage_timeout < $curtime) {
719       
720       // FIXME BRISK4: include for each kind of table
721       require_once("briskin5/Obj/briskin5.phh");
722
723       // Before all align times with table timeout
724       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
725         $table_cur =& $this->table[$table_idx];
726         // if the table is complete and exists its shared mem we get the info about users lacc
727
728         if ($table_cur->player_n == PLAYERS_N) {
729           log_main("PLAYERS == N TABLE ".$table_idx);
730           
731           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
732             log_main("bin5 lock data success");
733             
734             $no_recovery = FALSE;
735             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
736               if ($table_cur->table_token != $bri->table_token) {
737                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
738                 log_main("ERROR: not matching table_start. Room: ".$table_cur->table_start."  Table: ".$bri->table_start);
739                 $no_recovery = TRUE;
740                 $bri = FALSE;
741               }
742             }
743             
744             if ($bri != FALSE) {
745               //
746               //  SPAWN: JOIN
747               //
748               log_main("garbage_manager: bri loaded successfully.");
749               $bri->garbage_manager(TRUE);
750               
751               $bri_table = &$bri->table[0];
752
753               // is the end of the table
754               if ($bri->the_end == TRUE) {
755                 /*
756                  *  DESTROY OF FINISHED TABLE && MOVE PLAYER TO ROOM AGAIN
757                  */
758                 log_main("garbage_manager: INSIDE THE END.");
759
760                 $plist = "$table_cur->table_token|$table_cur->idx|$table_cur->player_n";
761                 for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
762                   $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
763                 }
764
765                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
766                   // stat must be "table" by definition
767                   $user_cur =& $this->user[$table_cur->player[$i]];
768                   $bri_user =& $bri->user[$i];
769                   
770                   $user_cur->subst      = $bri_user->subst;
771                   $user_cur->step       = $bri_user->step;
772                   $user_cur->lacc       = $bri_user->lacc;
773                   $user_cur->laccwr     = $bri_user->lacc;
774                   $user_cur->bantime    = $bri_user->bantime;
775                 }
776
777                 log_legal($curtime, $user_cur, "STAT:DESTROY_GAME", $plist);
778
779                 $this->room_join_wakeup(&$user_cur, FALSE, 0); 
780                 $table_cur->table_token = "";
781                 $table_cur->wakeup_time = $curtime + WAKEUP_TIME;
782                 Briskin5::destroy_data($table_idx);
783               }
784               else {
785                 log_main("gm:: save_data");
786
787                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
788                   $this->user[$table_cur->player[$i]]->lacc = $bri->user[$i]->lacc;
789                 }
790               
791                 Briskin5::save_data(&$bri);
792               }
793             } // else if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
794             else if ($no_recovery == FALSE) {
795               log_crit("ERROR: table ".$table_idx." unrecoverable join");
796
797               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
798                 $user_cur = &$this->user[$table_cur->player[$i]];
799                 $user_cur->subst = "shutdowner";
800                 $user_cur->step_inc();
801                 
802                 $ret = sprintf('stat = "%s"; subst = "%s";',  $user_cur->stat, $user_cur->subst);
803                 $ret .= "gst.st = ".($user_cur->step+1)."; ";
804                 $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);
805                 $user_cur->comm[$user_cur->step % COMM_N] = $ret;
806                 $user_cur->step_inc();
807               }
808
809               $plist = "$table_cur->table_token|$user_cur->table|$table_cur->player_n";
810               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
811                 $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
812               }
813               log_legal($curtime, $user_cur, "STAT:DESTROY_GAME(RECOVERY)", $plist);
814               
815               $this->room_join_wakeup(&$user_cur, TRUE, -2); 
816               $table_cur->table_token = "";
817             }
818
819             Briskin5::unlock_data($sem);
820           } // bri::lock_data
821         } //  if ($table_cur->player_n == PLAYERS_N) {
822       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
823     
824       log_rd2("out new loop.");
825                 
826       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
827         $user_cur = &$this->user[$i];
828         
829         log_rd2("User: ".$user_cur->name."  stat: ".$user_cur->stat."  subst: ".$user_cur->subst);
830           
831         if ($user_cur->sess == "") 
832           continue;
833         
834         if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) {
835           // Auto logout dell'utente
836           log_rd2("AUTO LOGOUT.".($user_cur->lacc + EXPIRE_TIME_RD)." curtime ".$curtime);
837           
838           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
839             log_auth($user_cur->sess, "Autologout session.");
840             
841             $user_cur->reset();
842             
843             log_rd2("AUTO LOGOUT.");
844             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
845               $this->room_wakeup(&$user_cur);
846             else if ($user_cur->subst == 'standup')
847               $this->room_outstandup(&$user_cur);
848             else
849               log_rd2("LOGOUT FROM WHAT ???");
850           }
851         }
852
853         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < $curtime) { // lo rimettiamo in piedi
854           if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
855             $this->room_wakeup(&$user_cur);
856             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
857             /* 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" */
858             $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);
859             $user_cur->step_inc();
860           }
861         }
862       }
863       log_rd2("GARBAGE UPDATED!");
864       
865       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
866       $ismod = TRUE;
867     }
868
869     return ($ismod);
870   }
871
872   function show_room($user_step, &$user)
873   {
874     log_main("show_room: username: ".$user->name);
875     
876     $ret = sprintf('gst.st = %d; ',  $user_step);
877
878     if ($user->flags & USER_FLAG_LISTAUTH) {
879       $ret .= 'list_set(\'auth\', false, \'(solo aut.)\' ); ';
880     }
881     else {
882       $ret .= 'list_set(\'all\', false, \'\' ); ';
883     }
884
885     if ($user->subst == 'standup')
886       $ret .= "tra.show(); ";
887     else
888       $ret .= "tra.hide(); ";
889
890     $ret .= sprintf('stat = "%s";',  $user->stat);
891     
892     $ret .= root_wellcome($user);
893     $ret .= sprintf('subst = "%s";', $user->subst);
894     $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
895     $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
896     $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>";', $itin, xcape($user->name), $itou);
897     for ($i = 0 ; $i < TABLES_N ; $i++) {
898       $ret .= $this->table_content($user, $i);
899       // $ret .= table_act_content(($user->subst == 'standup'), $this->table[$i]->player_n, $i, $user->table, 
900       //                          ($this->table[$i]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
901       $ret .=  $this->table[$i]->act_content($user);
902       if ($this->table[$i]->wag_own != NULL) 
903         $ret .= sprintf('tra.add(%d, "%s: %s"); ', $i,  $this->table[$i]->wag_own->name, $this->table[$i]->wag_com);
904       else 
905         $ret .= sprintf('tra.rem(%d); ', $i);
906     }
907     $ret .= $this->standup_content($user);
908     
909     return ($ret);
910   }
911   
912
913   function room_wakeup(&$user)
914   {
915     $table_idx = $user->table;
916     $table = &$this->table[$table_idx];
917
918     log_main("WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
919
920     $curtime = time();
921
922     $from_table = ($user->stat == "table");
923     if ($from_table) {
924       log_main("WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
925
926       for ($i = 0 ; $i < $table->player_n ; $i++) {
927         $user_cur = &$this->user[$table->player[$i]];
928         log_main("PREIMPOST: INLOOP name: ".$user_cur->name);
929
930         if ($user_cur != $user) {
931           $user_cur->stat_set("room");
932           $user_cur->subst = "sitdown";
933           $user_cur->laccwr = $curtime;
934         }
935         else if ($user->sess != "") {
936           $user_cur->stat_set("room");
937           $user_cur->subst = "standup";
938           $user_cur->laccwr = $curtime;
939           $user_cur->table = -1;
940         }
941       }
942     }
943     else {
944       $user->stat_set("room");
945       $user->subst = "standup";
946       $user->laccwr = $curtime;
947     }
948     
949     $remove_wagon = false;
950     if($table->wag_own == $user) {
951       $remove_wagon = true;
952       $table->wag_reset($curtime);
953       
954     }
955     
956
957     /* aggiorna l'array dei giocatori al tavolo. */
958     $table->user_rem(&$this, &$user);
959
960     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
961       $user_cur = &$this->user[$i];
962       if ($user_cur->sess == '' || $user_cur->stat != 'room')
963         continue;
964       
965       log_main("VALORI: name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
966
967       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
968       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
969         $ret .= 'gst.st_loc++; the_end=true; window.onunload = null; window.onbeforeunload = null; document.location.assign("index.php");|';
970         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
971         log_main("DOCUMENT.index.php: from table");
972       }
973       else if ($user_cur->stat == "room") {
974         log_main("DOCUMENT.index.php: from table");
975
976         $ret .= $this->table_content($user_cur, $table_idx);
977         $ret .= $this->standup_content($user_cur);
978         
979         // $ret .= table_act_content(FALSE, 0, $table_idx, $user->table, FALSE);
980         $ret .= $table->act_content($user);
981
982         if ($user_cur == $user) {
983           // set the new status 
984           $ret .=  'subst = "standup"; tra.show(); ';
985           // clean the action buttons in other tables
986           for ($e = 0 ; $e < TABLES_N ; $e++) {
987             if ($this->table[$e]->player_n < PLAYERS_N) {
988               // $ret .= table_act_content(TRUE, 0, $e, $user->table, 
989               //                           ($this->table[$e]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
990               $ret .= $this->table[$e]->act_content($user);
991             }
992           }
993         }
994         else {
995           // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
996           //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
997           $ret .= $table->act_content($user_cur);
998         }
999       }
1000       log_wr("ROOM_WAKEUP: ".$ret);
1001       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1002       $user_cur->step_inc();
1003     }
1004   }
1005
1006   function room_join_wakeup(&$user, $update_lacc = FALSE, $trans_delta)
1007   {
1008     $table_idx = $user->table;
1009     $table = &$this->table[$table_idx];
1010     
1011     log_main("JOIN_WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1012
1013     $curtime = time();
1014     $user_wup = array();
1015     $user_wup_n = 0;
1016     $user_tab = array();
1017     $user_tab_n = 0;
1018     log_main("JOIN WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1019     
1020     for ($i = 0 ; $i < $table->player_n ; $i++) {
1021       $user_cur = &$this->user[$table->player[$i]];
1022       log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1023       if ($user_cur->sess != "") {
1024         if ($update_lacc == TRUE) {
1025           $user_cur->laccwr = $curtime;
1026         }
1027         log_main("cur: ".$user_cur->name."  subst: ".$user_cur->subst);
1028         if ($user_cur->subst == "shutdowned") {
1029           $user_cur->stat_set("room");
1030           $user_cur->subst = "sitdown";
1031         }
1032         else if ($user_cur->subst == "shutdowner") {
1033           $user_cur->stat_set("room");
1034           $user_cur->subst = "standup";
1035           $user_cur->table = -1;
1036           $user_wup[$user_wup_n++] = &$user_cur;
1037           
1038           $remove_wagon = false;
1039           if($table->wag_own == $user_cur) {
1040             $remove_wagon = true;
1041             $table->wag_reset($curtime);
1042           }
1043         }
1044         $user_tab[$user_tab_n++] = &$user_cur;
1045       }
1046     }
1047
1048     for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
1049       $table->user_rem(&$this, &$user_wup[$wup_idx]);
1050
1051     /* aggiorna l'array dei giocatori al tavolo. */
1052
1053     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1054       log_main("START LOOP");
1055       $user_cur = &$this->user[$i];
1056       if ($user_cur->sess == '' || $user_cur->stat != 'room') {
1057         log_main("name: ".$user_cur->name."skip   subst: ".$user_cur->subst);
1058         continue;
1059       }
1060
1061       log_main("___");
1062       log_main("VALORI name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
1063
1064       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1065       if ($user_cur->stat == "room") {
1066         log_main("DOCUMENT.index.php from table");
1067
1068         $ret .= $this->table_content($user_cur, $table_idx);
1069         $ret .= $this->standup_content($user_cur);
1070         
1071         // $ret .= table_act_content(FALSE, 0, $table_idx, $user_cur->table,
1072         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1073         $ret .= $table->act_content($user_cur);
1074
1075
1076         for ($tab_idx = 0 ; $tab_idx < $user_tab_n  ; $tab_idx++)
1077           if ($user_cur == $user_tab[$tab_idx]) 
1078             break;
1079
1080         // for users that wakeup the room will be reconstructed by index_rd.php
1081         if ($tab_idx < $user_tab_n) {
1082           log_main("PRE show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1083
1084 //        ARRAY_POP DISABLED
1085 //        if ($trans_delta == 0)
1086 //          while (array_pop($user_cur->comm) != NULL);
1087
1088           $user_cur->trans_step = $user_cur->step + 1 + $trans_delta;
1089           $user_cur->comm[$user_cur->step % COMM_N] = "";
1090           $user_cur->step_inc();
1091           $user_cur->comm[$user_cur->step % COMM_N] = $this->show_room(($user_cur->step + 1), &$user_cur);
1092           $user_cur->step_inc();
1093           log_main("POST show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1094
1095           continue;
1096         }
1097         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
1098
1099         log_main("JOIN_WAKEUP more");
1100         // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
1101         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1102         $ret .= $table->act_content($user_cur);
1103
1104         log_main("JOIN_WAKEUP end more");
1105       }
1106       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
1107       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1108       $user_cur->step_inc();
1109     }
1110   }
1111
1112   function room_outstandup(&$user)
1113   {
1114     $this->room_sitdown(&$user, -1);
1115   }
1116   
1117   function table_update(&$user)
1118   {
1119     log_main("table_update: pre - USER: ".$user->name);
1120
1121     $table_idx = $user->table;
1122
1123     if ($table_idx > -1) 
1124       $table = &$this->table[$table_idx];
1125     
1126     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1127       $ret = "";
1128       $user_cur = &$this->user[$i];
1129       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1130       continue;
1131       
1132       $ret = "gst.st = ".($user_cur->step+1)."; ";
1133       if ($table_idx > -1)
1134         $ret .= $this->table_content($user_cur, $table_idx);
1135       
1136       if ($user_cur == $user) {
1137         $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1138         $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1139         $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', $itin, xcape($user->name), $itou);
1140       }
1141       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1142       $user_cur->step_inc();
1143     }
1144
1145     log_main("table_update: post");
1146   }
1147
1148   function room_sitdown(&$user, $table_idx)
1149   {
1150     log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1151
1152     $train_app = "";
1153
1154     if ($table_idx > -1 && $table_idx < TABLES_N) { 
1155       $table = &$this->table[$table_idx];
1156
1157       // wagon shutdown 
1158       if ($table->wag_own != NULL && $table->player_n == PLAYERS_N) {        
1159         for ($i = 0 ; $i < TABLES_N ; $i++) {
1160           $user_cur =& $this->user[$table->player[$i]];
1161           if ($user_cur == $table->wag_own) {
1162             $train_app = sprintf("tra.rem(%d); ", $table_idx); 
1163             $table->wag_reset(time());
1164             break;
1165           }
1166         }
1167       }
1168     }
1169
1170     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1171       $ret = "";
1172       $user_cur = &$this->user[$i];
1173       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1174       continue;
1175       
1176       $ret = "gst.st = ".($user_cur->step+1)."; ".$train_app;
1177       if ($table_idx > -1)
1178       $ret .= $this->table_content($user_cur, $table_idx);
1179       $ret .= $this->standup_content($user_cur);
1180       
1181       if ($user_cur == $user) {
1182         $ret .=  'subst = "sitdown"; tra.hide(); ';
1183         // clean the action buttons in other tables
1184         for ($e = 0 ; $e < TABLES_N ; $e++) {
1185           // $ret .= table_act_content(FALSE, 0, $e, $user_cur->table, FALSE);
1186           $ret .= $this->table[$e]->act_content($user_cur);
1187         }
1188       }
1189       else if ($table_idx > -1) {
1190         if ($table->player_n == PLAYERS_N) {
1191           // $ret .= table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table,
1192           ///                      ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1193           $ret .= $table->act_content($user_cur);
1194         }
1195       }
1196       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1197       $user_cur->step_inc();
1198     }
1199   }
1200
1201   function chatt_send(&$user, $mesg)
1202   {
1203     GLOBAL $G_alarm_passwd;
1204     $only_you = FALSE;
1205     
1206     // common settings
1207     $msg = substr($mesg, 6, 128);
1208     $curtime = time();
1209     $dt = date("H:i ", $curtime);
1210
1211     //
1212     //  Compute actions
1213     //
1214
1215     $to_user     = FALSE;
1216     $to_all      = FALSE;
1217     $to_room     = FALSE;
1218     $to_tabl     = FALSE;
1219     $is_normchat = FALSE;
1220     $update_room = FALSE;
1221
1222     if (strcmp($msg,  "/tav") == 0 || 
1223         strncmp($msg, "/tav ", 5) == 0) {
1224       do {
1225         if ($user->stat != 'room' || $user->subst != 'sitdown') {
1226           /* 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>" */
1227           $msg = "<br>Per attivare il messaggio di segnalazione del tavolo occorre essere seduti.<br><br>";
1228           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1229
1230           break;
1231         }
1232
1233         $table = &$this->table[$user->table];
1234         
1235         if ($table->wag_own != NULL) {
1236           $msg = "<br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br>";
1237           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1238
1239           break;
1240         }
1241
1242         $dtime = $curtime - $table->wag_tout;
1243         if ($dtime  < EXPIRE_TIME_WAG) {
1244           $msg = sprintf("<br>Il messaggio di segnalazione del tavolo<br>&egrave; disattivato ancora per %d second%s.<br><br>",
1245                          EXPIRE_TIME_WAG - $dtime, (EXPIRE_TIME_WAG - $dtime == 1 ? "o" : "i"));
1246           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1247
1248           break;
1249         }
1250         
1251         $msg = substr($msg, 5);
1252         
1253         $table->wag_set($user, $msg);
1254         $to_user = sprintf('tra.add(%d, "%s");', $user->table, xcape(sprintf("%s: %s", $user->name, $msg)));
1255         $to_room = $to_user;
1256         
1257       } while (0);
1258     } // /tav chat command
1259
1260     else if (strncmp($msg, "/alarm ", 7) == 0) {
1261       if (strncmp($msg, "/alarm to ", 10) == 0) {
1262         $sp_pos = strpos($msg, " ", 10);
1263         $target = substr($msg, 10, $sp_pos - 10);
1264         $alarm_check = "/alarm to ".$target." ".$G_alarm_passwd." ";
1265       }
1266       else {
1267         $target = "";
1268         $alarm_check = "/alarm ".$G_alarm_passwd." ";
1269       }
1270       do {
1271         if (strncmp($msg, $alarm_check, strlen($alarm_check)) != 0) {
1272           /* MLANG: "<br>La password digitata non &egrave; corretta.<br><br>" */
1273           $msg = "<br>La password digitata non &egrave; corretta.<br><br>";
1274           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1275
1276           break;
1277         }
1278
1279         /* MLANG: "Alarm <b>%s</b> inviato a <b>%s</b>." */
1280         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Alarm <b>%s</b> inviato a <b>%s</b>.");', 
1281                            $dt, NICKSERV, xcape(substr($msg, strlen($alarm_check))), 
1282                            ($target == "" ? "tutti" : xcape($target)) );
1283
1284         $msg = sprintf("<br><b>%s<br><br>%s</b><br><br>",
1285                        $dt.NICKSERV, xcape(substr($msg, strlen($alarm_check))));
1286         /* MLANG: "chiudi" */
1287         $to_all = show_notify($msg, 0, "chiudi", 400, 120);
1288       } while (0);
1289     } // /alarm chat command
1290     else if (strncmp($msg, "/listen ", 8) == 0) {
1291       $arg = substr($msg, 8);
1292
1293       if (strcasecmp($arg, "auth") == 0) {
1294         $user->flags |= USER_FLAG_LISTAUTH;
1295         $to_user = 'list_set(\'auth\', true, \'(solo aut.)\'); ';
1296       }
1297       else {
1298         $user->flags &= ~USER_FLAG_LISTAUTH;
1299         $to_user = 'list_set(\'all\', true, \'\'); ';
1300       }
1301     }
1302     else if (strncmp($msg, "/garante", 8) == 0) {
1303       if ($user->flags & USER_FLAG_AUTH) {
1304         $to_user = sprintf('authbox(300,200);');
1305       }
1306       else {
1307         /* 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." */
1308         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Per autenticare qualcuno devi a tua volta essere autenticato.</b>");', $dt, NICKSERV);
1309       }
1310     }
1311     else if (strncmp($msg, "/mesgtoadm", 8) == 0) {
1312       if ($user->flags & USER_FLAG_AUTH) {
1313         $to_user = sprintf('mesgtoadmbox(500,300);');
1314       }
1315       else {
1316         /* MLANG: "<b>Per inviare un messaggio devi essere autenticato.</b>" */
1317         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Per inviare un messaggio devi essere autenticato.</b>");', $dt, NICKSERV);
1318       }
1319     }
1320     else if (strncmp($msg, "/nick ", 6) == 0) {
1321       log_main("chatt_send BEGIN");
1322
1323       do {
1324         if (($name_new = validate_name(substr($msg, 6))) == FALSE) {
1325           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Il nickname deve contenere almeno una lettera dell\'alfabeto o una cifra.");', $dt, NICKSERV);
1326           break;
1327         }
1328
1329         $msg = "COMMAND ".$msg;
1330         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1331           $user_cur = &$this->user[$i];
1332
1333           if ($user_cur->sess == '')
1334             continue;
1335           if ($user_cur->name == $name_new)
1336             break;
1337           }
1338         if ($i <  MAX_PLAYERS) {
1339           $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Nickname <b>%s</b> gi&agrave; in uso.");', $dt, NICKSERV, xcape($name_new));
1340           break;
1341         }
1342         
1343         /* 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>" */
1344         if ($user->flags & USER_FLAG_AUTH) {
1345           if (strcasecmp($user->name,$name_new) != 0) {
1346             if ($user->subst == 'standup' || ($user->subst != 'standup' && $this->table[$user->table]->auth_only == FALSE)) {
1347               $user->flags &= ~USER_FLAG_AUTH; // Remove auth if name changed
1348               for ($i = 0 ; $i < TABLES_N ; $i++) {
1349                 $to_user .= $this->table[$i]->act_content($user);
1350               }
1351             }
1352             else {
1353               $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Non puoi cambiare nick a un tavolo per soli autenticati.</b>");', $dt, NICKSERV);
1354               break;
1355             }
1356           }
1357         }
1358         $user->name = $name_new; // OK - nick changed
1359         /* se nome gia' in uso, segnala cosa potrebbe capitare */
1360         if (($user->flags & USER_FLAG_AUTH) == 0) {
1361           $userdb = new LoginDB();
1362           /* 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>" */
1363           if ($userdb->login_exists($name_new)) {
1364             $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));
1365           }
1366         }
1367
1368         log_main("chatt_send start set");
1369
1370         $update_room = TRUE;
1371       } while (0);
1372     } // nick chat command
1373
1374     else if (strncmp($msg, "/st ", 4) == 0) {
1375       log_main("chatt_send BEGIN");
1376
1377       do {
1378         $st_str = substr($msg, 4);
1379         
1380         if (strcasecmp($st_str, "normale") == 0) {
1381           $st = USER_FLAG_S_NORM;
1382         }
1383         else if (strcasecmp($st_str, "pausa") == 0) {
1384           $st = USER_FLAG_S_PAU;
1385         }
1386         else if (strcasecmp($st_str, "fuori") == 0) {
1387           $st = USER_FLAG_S_OUT;
1388         }
1389         else if (strcasecmp($st_str, "cane") == 0) {
1390           $st = USER_FLAG_S_DOG;
1391         }
1392         else if (strcasecmp($st_str, "cibo") == 0) {
1393           $st = USER_FLAG_S_EAT;
1394         }
1395         else if (strcasecmp($st_str, "lavoro") == 0) {
1396           $st = USER_FLAG_S_WRK;
1397         }
1398         else if (strcasecmp($st_str, "sigaretta") == 0) {
1399           $st = USER_FLAG_S_SMK;
1400         }
1401         else if (strcasecmp($st_str, "presente") == 0) {
1402           $st = USER_FLAG_S_EYE;
1403         }
1404         else {
1405           /* MLANG: "Questo stato non esiste." */
1406           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Questo stato non esiste.");', $dt, NICKSERV);
1407           break;
1408         }
1409
1410         log_main("chatt_send start set");
1411         if (($user->flags & USER_FLAG_S_ALL) != $st) {
1412           $update_room = TRUE;
1413           $user->flags = ($user->flags & ~USER_FLAG_S_ALL) | $st;
1414         }
1415       } while (0);
1416     } // nick chat command
1417
1418     else { // normal chat line
1419       $is_normchat = TRUE;
1420       if ($curtime < ($user->chat_ban + $user->chat_dlt)) {
1421         $only_you = TRUE;
1422         $user->chat_dlt = $user->chat_dlt * 2; 
1423         if ($user->chat_dlt > 120)
1424           $user->chat_dlt = 120; 
1425       }
1426       else if ($user->chat_lst == $msg)
1427         $only_you = TRUE;
1428       else if ($curtime - $user->chattime[($user->chat_cur + 1) % CHAT_N] < CHAT_ILL_TIME) {
1429         $user->chat_ban = $curtime;
1430         $user->chat_dlt = 5;
1431         $only_you = TRUE;
1432       }
1433       else {
1434         $user->chat_ban = 0;
1435         $user->chat_dlt = 0;
1436       }
1437
1438       if ($only_you) {
1439         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape("== chat ban =="));
1440       }
1441       else {
1442         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape($msg));
1443         // temporary silentiation for troll (will became array check)
1444         if (strcasecmp($user->name,'JackRokka') != 0 && $user->sess != '47ea653f602e8')
1445           $to_room = $to_user;
1446       }
1447
1448       log_legal($curtime, $user, 
1449                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$msg);
1450       
1451       $user->chat_lst = "$msg";
1452       $user->chattime[$user->chat_cur % CHAT_N] = $curtime;
1453       $user->chat_cur++;
1454     }
1455
1456     if ($to_all) {
1457       $to_room = $to_all;
1458       $to_tabl = $to_all;
1459     }
1460
1461     //
1462     //  Output to clients
1463     //
1464
1465     if ($to_user != FALSE) {
1466       $user->comm[$user->step % COMM_N] =  "gst.st = ".($user->step+1)."; ";
1467       $user->comm[$user->step % COMM_N] .= $to_user;
1468       $user->step_inc();
1469     }
1470
1471     if ($to_room != FALSE) {
1472       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1473         $user_cur = &$this->user[$i];
1474         if ($target != "" && $user_cur->name != $target)
1475           continue;
1476         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1477         if ($user_cur->sess == '' || $user_cur->stat == 'table' || $user_cur == $user)
1478           continue;
1479         
1480         if ($is_normchat == TRUE) {
1481           if ($user_cur->flags & USER_FLAG_LISTAUTH) {
1482             if (($user->flags & USER_FLAG_AUTH) == 0) {
1483               continue;
1484             }
1485           }
1486         }
1487   
1488         $user_cur->comm[$user_cur->step % COMM_N] =  "gst.st = ".($user_cur->step+1)."; ";
1489         $user_cur->comm[$user_cur->step % COMM_N] .= $to_room; 
1490         $user_cur->step_inc();
1491       }
1492     }
1493     
1494     if ($to_tabl) {
1495       // FIXME BRISK4: include for each kind of table
1496       require_once("briskin5/Obj/briskin5.phh");
1497       // Before all align times with table timeout
1498       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1499         $table_cur =& $this->table[$table_idx];
1500         // if the table is complete and exists its shared mem we get the info about users lacc
1501         
1502         if ($table_cur->player_n == PLAYERS_N) {
1503           log_main("PLAYERS == N TABLE ".$table_idx);
1504         
1505           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
1506             log_main("bin5 lock data success");
1507             
1508             $no_recovery = FALSE;
1509             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1510               if ($table_cur->table_token != $bri->table_token) {
1511                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
1512                 $bri = FALSE;
1513               }
1514             }
1515             
1516             if ($bri != FALSE) {
1517               $bri_table = &$bri->table[0];
1518               for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
1519                 // stat must be "table" by definition
1520                 $bri_user =& $bri->user[$i];
1521               
1522                 if ($target != "" && $bri_user->name != $target)
1523                   continue;
1524                 log_main("writa: ".$user_mesg);
1525                 $bri_user->comm[$bri_user->step % COMM_N] = "gst.st = ".($bri_user->step+1)."; ";
1526                 $bri_user->comm[$bri_user->step % COMM_N] .= $to_tabl;
1527                 $bri_user->step_inc();
1528               }
1529               Briskin5::save_data(&$bri);
1530             }
1531             Briskin5::unlock_data($sem);
1532           } // bri::lock_data
1533         } //  if ($table_cur->player_n == PLAYERS_N) {
1534       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1535     } // if ($to_tabl == true ...
1536
1537     if ($update_room) {
1538       if ($user->stat == 'room' && $user->subst == 'standup') {
1539         $this->standup_update(&$user);
1540       }
1541       else if ($user->stat == 'room' && $user->subst == 'sitdown') {
1542         log_main("chatt_send pre table update");
1543         $this->table_update(&$user);
1544         log_main("chatt_send post table update");
1545       }
1546     } // if ($update_room ...
1547
1548     return;
1549   } // function chatt_send( ...
1550
1551   function &get_user($sess, &$idx)
1552   {
1553     GLOBAL $PHP_SELF, $G_false;
1554
1555     if (validate_sess($sess)) {
1556       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1557         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1558           // find it
1559           $idx = $i;
1560           $ret = &$this->user[$i];
1561           return ($ret);
1562         }
1563       }
1564       log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1565       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1566       // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1567     }
1568     else {
1569       log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
1570     }
1571
1572     return ($G_false);
1573   }
1574
1575   
1576
1577   /*
1578    * function &add_user(&$room, &$sess, &$idx, $name, $pass, $ip)
1579    *
1580    * RETURN VALUE:
1581    *   if ($idx >  -1    && ret == FALSE)  =>  duplicated nick
1582    *   if ($idx == -2    && ret == FALSE)  =>  invalid name
1583    *   if ($idx == -3    && ret == FALSE)  =>  wrong password
1584    *   if ($idx == -1    && ret == FALSE)  =>  no space left
1585    *   if ($idx ==  0    && ret == user)   =>  SUCCESS
1586    *   if ($idx == -$idx && ret == user)   =>  SUCCESS (but the login exists in the auth db 
1587    */
1588
1589
1590
1591   function &add_user(&$sess, &$idx, $name, $pass, $ip)
1592   {
1593     GLOBAL $G_false, $CO_list;
1594
1595     $idx = 0;
1596
1597     $authenticate = FALSE;
1598     $login_exists = FALSE;
1599     $ghost = -1;
1600     $ghost_auth = FALSE;
1601     $idx = -1;
1602     $idfree = -1;
1603     
1604     if (($name_new = validate_name($name)) == FALSE) {
1605       $idx = -2;
1606       return ($G_false);
1607     }
1608
1609     log_auth("XXX", sprintf("ARRIVA: [%s] pass:[%s]", $sess, ($pass == FALSE ? "FALSE" : $pass)));
1610     if (validate_sess($sess) == FALSE) 
1611       $sess = "";
1612
1613     /* if pass != FALSE verify the login with pass */
1614     log_auth("XXX", "auth1");
1615     $userdb = new LoginDB();
1616     if ($pass != FALSE) {
1617       log_auth("XXX", "auth2");
1618       $authenticate = $userdb->login_verify($name_new, $pass);
1619       log_auth("XXX", "authenticate: ".($authenticate == TRUE ? "TRUE" : "FALSE"));
1620       
1621       if ($authenticate == FALSE) {
1622         $idx = -3;
1623         return ($G_false);
1624       }
1625     }
1626     else {
1627       $login_exists =  $userdb->login_exists($name_new);
1628     }
1629     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1630       /* free user ? */
1631       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1632         if ($idx == -1)
1633           $idx = $i;
1634       }
1635       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
1636         $idfree = $i;
1637         continue; // NOTE: CHECK IT !!
1638       }
1639       if (strcasecmp($this->user[$i]->name, $name_new) == 0) {
1640         if ($authenticate == FALSE) {
1641           $idx = $i;
1642           break;
1643         }
1644         else {
1645           $ghost = $i;
1646           $ghost_auth = ($this->user[$i]->flags & USER_FLAG_AUTH);
1647         }
1648       }
1649     }
1650     if ($idx == -1)
1651       $idx = $idfree;
1652
1653     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1654
1655     if ($ghost > -1 && $ghost_auth && $authenticate) {
1656       /* swap session */
1657
1658       $ghost_user =& $this->user[$ghost];
1659       $curtime = time();
1660       $ghost_user->step_inc();
1661       if ($sess == "") {
1662         $sess = uniqid(""); 
1663         $ghost_user->sess = $sess;
1664       }
1665       else {
1666         $ghost_user->sess = $sess;
1667       }
1668       
1669       // If user at the table we need to update the table data too
1670       $table_idx = $ghost_user->table;
1671       if ($ghost_user->stat == "table" && $this->table[$table_idx]->player_n == PLAYERS_N) {
1672         // FIXME BRISK4: include for each kind of table
1673         require_once("briskin5/Obj/briskin5.phh");
1674         if (($brisem = Briskin5::lock_data($table_idx)) != FALSE) { 
1675           if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1676             if ($bri->the_end != TRUE) {
1677               $bri->user[$ghost_user->table_pos]->step_inc();
1678               $bri->user[$ghost_user->table_pos]->sess = $sess;
1679               Briskin5::save_data(&$bri);
1680             }
1681           }
1682           Briskin5::unlock_data($brisem);
1683         }
1684       }
1685
1686       $idx = $ghost;
1687       return ($this->user[$ghost]);
1688     }
1689     else if ($idx != -1 && $i == MAX_PLAYERS) {
1690       /* SUCCESS */
1691       $curtime = time();
1692       if ($sess == "") {
1693         $sess = uniqid("");
1694         $this->user[$idx]->sess = $sess;
1695       }
1696       else {
1697         $this->user[$idx]->sess = $sess;
1698       }
1699       $this->user[$idx]->name = $name_new; // OK - add new user
1700       $this->user[$idx]->stat_set("room");
1701       $this->user[$idx]->step_set(0);
1702       while (array_pop($this->user[$idx]->comm) != NULL);
1703       $this->user[$idx]->subst = "standup";
1704       $this->user[$idx]->lacc =   $curtime;
1705       $this->user[$idx]->laccwr = $curtime;
1706       $this->user[$idx]->bantime = 0;
1707       $this->user[$idx]->ip = $ip;
1708
1709       $this->user[$idx]->flags = ($authenticate ? USER_FLAG_AUTH : 0x00);
1710       
1711       if ($authenticate) {
1712         $this->user[$idx]->flags |= USER_FLAG_LISTAUTH;
1713
1714         if (isset($CO_list) && strcmp($CO_list, "all") == 0) {
1715           $this->user[$idx]->flags &= ~USER_FLAG_LISTAUTH;
1716         }
1717       }
1718       
1719       if ($ghost > -1) {
1720         log_main("ghost: rename!");
1721         $ghost_user =& $this->user[$ghost];
1722
1723         if ($ghost_auth == FALSE) {
1724           for ($sfx = 1 ; $sfx <= MAX_PLAYERS ; $sfx++) {
1725             $ghostname = 'ghost'.$sfx;
1726             for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1727               if (strcmp("", $this->user[$i]->sess) == 0) 
1728                 continue;
1729               
1730               if (strcmp($this->user[$i]->name, $ghostname) == 0) {
1731                 $ghostname = '';
1732                 break;
1733               }
1734             }
1735             if ($ghostname != '')
1736               break;
1737           }
1738           
1739           $ghost_user->name = $ghostname;
1740           
1741           if ($ghost_user->stat == 'room' && $ghost_user->subst == 'standup') {
1742             $this->standup_update(&$ghost_user);
1743           }
1744           else {
1745             log_main("chatt_send pre table update");
1746             $this->table_update(&$ghost_user);
1747           log_main("chatt_send post table update");
1748           }
1749         } // if ($ghost_auth == FALSE
1750         else {
1751           // FIXME: cacciare il vecchio utente room && table (if needed)
1752           $ghost_user->the_end = TRUE;
1753           $ghost_user->lacc = 0;
1754           $this->garbage_manager(TRUE);
1755         }
1756       } //  if ($ghost > -1) {
1757
1758       log_main(sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1759       $real_idx = $idx;
1760       if ($login_exists)
1761         $idx = -($idx + 1);
1762       return ($this->user[$real_idx]);
1763     }
1764
1765     return ($G_false);
1766   }
1767   
1768   function standup_update(&$user)
1769   {
1770     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1771       $user_cur = &$this->user[$i];
1772       if ($user_cur->sess == '')
1773         continue;
1774
1775       log_main("STANDUP START: ".$user_cur->stat);
1776       
1777       if ($user_cur->stat == 'room') {
1778         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".$this->standup_content($user_cur);
1779         if ($user_cur == $user) {
1780           $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1781           $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1782
1783           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', 
1784                                                                $itin, xcape($user->name), $itou);
1785         }
1786         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1787         
1788         $user_cur->step_inc();
1789       }
1790     }
1791   }
1792
1793   // Static functions
1794   function &init_data()
1795   {
1796     $room =& new Room();
1797     
1798     return $room;
1799   }
1800   
1801
1802   function &load_data() 
1803   {
1804     GLOBAL $G_false, $sess;
1805     $doexit = FALSE;
1806     do {
1807       if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1808         log_main("ftok failed");
1809         $doexit = TRUE;
1810         break;
1811       }
1812     
1813       if (($shm_sz = sharedmem_sz($tok)) == -1) {
1814         log_main("shmop_open failed");
1815       }
1816         
1817       if ($shm_sz == -1)
1818         $shm_sz = SHM_DIMS_MIN;
1819
1820       if ($shm = shm_attach($tok, $shm_sz)) {
1821         $room = @shm_get_var($shm, $tok);
1822         
1823         log_only("bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
1824         if (isset($room)) 
1825           log_only("bri count ".count($room));
1826         
1827         if ($room == FALSE) {
1828           log_only("INIT MAIN DATA");
1829           
1830           $room =& Room::init_data();
1831           if (@shm_put_var($shm, $tok, $room) == FALSE) {
1832             log_only("PUT_VAR FALLITA ".strlen(serialize($room)));
1833             log_only(serialize($room));
1834           }
1835         }
1836         $room->shm_sz = $shm_sz;
1837         
1838         shm_detach($shm);
1839       }
1840       $ret = &$room;
1841       return ($ret);
1842     } while (0);
1843     
1844     if ($doexit)
1845       exit();
1846     
1847     return ($G_false);
1848   }
1849   
1850
1851   function save_data(&$room) 
1852   {
1853     GLOBAL $sess;
1854     
1855     $shm =   FALSE;
1856     
1857     // var_dump($room);
1858     
1859     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) 
1860       return (FALSE);
1861     
1862     while ($room->shm_sz < SHM_DIMS_MAX) {
1863       if (($shm = shm_attach($tok, $room->shm_sz)) == FALSE)
1864         break;
1865       
1866       // log_only("PUT_VAR DI ".strlen(serialize($room)));
1867       if (shm_put_var($shm, $tok, $room) != FALSE) {
1868         shm_detach($shm);
1869         return (TRUE);
1870       }
1871       if (shm_remove($shm) === FALSE) {
1872         log_only("REMOVE FALLITA");
1873         break;
1874       }
1875       shm_detach($shm);
1876       $room->shm_sz += SHM_DIMS_DLT;
1877     } 
1878
1879     if ($shm)
1880       shm_detach($shm);
1881     
1882     return (FALSE);
1883   }
1884
1885   function lock_data()
1886   {
1887     GLOBAL $sess; 
1888     
1889     //  echo "LOCK: ".FTOK_PATH."/main";
1890     //  exit;
1891     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1892       return (FALSE);
1893     }
1894     // echo "FTOK ".$tok."<br>";
1895     if (($res = sem_get($tok)) == FALSE) {
1896       return (FALSE);
1897     }
1898     if (sem_acquire($res)) {   
1899       log_lock("LOCK room");
1900       return ($res);
1901     }
1902     else
1903       return (FALSE);
1904   }
1905   
1906   function unlock_data($res)
1907   {
1908     GLOBAL $sess; 
1909     
1910     log_lock("UNLOCK room");
1911
1912     return (sem_release($res));
1913   }
1914
1915
1916   function standup_content($user)
1917   {
1918     $ret = "";
1919     $content = "";
1920     
1921     if ($user->stat != 'room')
1922       return;
1923     
1924     for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1925       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
1926         continue;
1927       $ct++;
1928     }
1929     
1930     // $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1931     
1932     $content = ' j_stand_cont( [ ';
1933
1934     for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1935       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
1936         continue;
1937       
1938       $flags = $this->user[$e]->flags;
1939       
1940       if ($this->user[$e]->subst == "standup") {
1941         if ($this->user[$e] == $user) 
1942           { 
1943             $flags |= 1;
1944           }
1945         
1946         $content .= sprintf('%s[ %d, "%s" ]',($ct > 0 ? ', ' : ''), $flags, xcape($this->user[$e]->name));
1947         $ct++;
1948       }
1949     }
1950     $content .= ' ]);';
1951     
1952     return ($content);
1953   }
1954   
1955   function table_content_old($user, $table_idx)
1956   {
1957     $content = "";
1958     $ret = "";
1959     // TODO
1960     //
1961     //   Si possono usare i dati nella classe table
1962     //
1963     
1964     $sess = $user->sess;
1965     $table = &$this->table[$table_idx];
1966     
1967     if ($user->stat != 'room')
1968       return;
1969     
1970     for ($i = 0 ; $i < $table->player_n ; $i++) {
1971       $user_cur = &$this->user[$table->player[$i]];
1972       
1973       if ($user_cur == $user) 
1974         { $hilion = "<b>"; $hilioff = "</b>"; }
1975       else
1976         { $hilion = ""; $hilioff = ""; }
1977       
1978       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
1979       
1980       $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1981     }
1982     /*
1983   for ( ; $i < PLAYERS_N ; $i++)
1984     $content .= "<br>";
1985     */
1986     
1987     $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1988     
1989     return ($ret);
1990   }
1991
1992
1993   function table_content($user, $table_idx)
1994   {
1995     $content = "";
1996     $ret = "";
1997     // TODO
1998     //
1999     //   Si possono usare i dati nella classe table
2000     //
2001     
2002     $sess = $user->sess;
2003     $table = &$this->table[$table_idx];
2004     
2005     if ($user->stat != 'room')
2006       return;
2007     
2008     $content = "[ ";
2009     for ($i = 0 ; $i < $table->player_n ; $i++) {
2010       $user_cur = &$this->user[$table->player[$i]];
2011
2012       $flags = $user_cur->flags;
2013
2014       if ($user_cur == $user) 
2015         $flags |= 1;
2016       
2017       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2018       
2019       $content .= sprintf('%s[ %d, "%s" ]',($i == 0 ? '' : ', '), $flags, xcape($user_cur->name));
2020     }
2021
2022     $content .= ' ]';
2023
2024     $ret .= sprintf('j_tab_cont(%d, %s);', $table_idx, $content);
2025     
2026     return ($ret);
2027   }
2028
2029 } // end class Room
2030
2031 function make_seed()
2032 {
2033   list($usec, $sec) = explode(' ', microtime());
2034   return (float) $sec + ((float) $usec * 100000);
2035 }
2036
2037
2038 function log_only2($log) {
2039   GLOBAL $sess;
2040
2041   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONL2) == 0)
2042     return;
2043
2044   if (isset($sess) == FALSE)
2045     $ssess = "XXXX";
2046   else
2047     $ssess = $sess;
2048
2049   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONL2) == 0)
2050     return;
2051
2052   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2053     fwrite($fp, sprintf("ONL2: [%s] [%s]\n", $ssess, $log));
2054     fclose($fp);
2055   }
2056 }
2057
2058 function log_crit($log) {
2059   GLOBAL $sess;
2060
2061   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CRIT) == 0)
2062     return;
2063
2064   if (isset($sess) == FALSE)
2065     $ssess = "XXXX";
2066   else
2067     $ssess = $sess;
2068
2069   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CRIT) == 0)
2070     return;
2071
2072   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2073     fwrite($fp, sprintf("CRIT: [%s] [%s]\n", $ssess, $log));
2074     fclose($fp);
2075   }
2076 }
2077
2078 function log_only($log) {
2079   GLOBAL $sess;
2080
2081   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONLY) == 0)
2082     return;
2083
2084   if (isset($sess) == FALSE)
2085     $ssess = "XXXX";
2086   else
2087     $ssess = $sess;
2088
2089   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONLY) == 0)
2090     return;
2091
2092   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2093     fwrite($fp, sprintf("ONLY: [%s] [%s]\n", $ssess, $log));
2094     fclose($fp);
2095   }
2096 }
2097
2098 function log_main($log) {
2099   GLOBAL $sess;
2100
2101   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_MAIN) == 0)
2102     return;
2103
2104   if (isset($sess) == FALSE)
2105     $ssess = "XXXX";
2106   else
2107     $ssess = $sess;
2108
2109   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_MAIN) == 0)
2110     return;
2111
2112   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2113     fwrite($fp, sprintf("MAIN: [%s] [%s]\n", $ssess, $log));
2114     fclose($fp);
2115   }
2116 }
2117
2118 function log_rd($log) {
2119   GLOBAL $sess;
2120
2121   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_READ) == 0)
2122     return;
2123
2124   if (isset($sess) == FALSE)
2125     $ssess = "XXXX";
2126   else
2127     $ssess = $sess;
2128
2129   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_READ) == 0)
2130     return;
2131
2132   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2133     fwrite($fp, sprintf("READ: [%s] [%s]\n", $ssess, $log));
2134     fclose($fp);
2135   }
2136 }
2137
2138 function log_rd2($log) {
2139   GLOBAL $sess;
2140
2141   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_REA2) == 0)
2142     return;
2143
2144   if (isset($sess) == FALSE)
2145     $ssess = "XXXX";
2146   else
2147     $ssess = $sess;
2148       
2149   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_REA2) == 0)
2150     return;
2151
2152   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2153     fwrite($fp, sprintf("REA2: [%s] [%s]\n", $ssess, $log));
2154     fclose($fp);
2155   }
2156 }
2157
2158 function log_send($log) {
2159   GLOBAL $sess;
2160
2161   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SEND) == 0)
2162     return;
2163
2164   if (isset($sess) == FALSE)
2165     $ssess = "XXXX";
2166   else
2167     $ssess = $sess;
2168       
2169   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SEND) == 0)
2170     return;
2171
2172   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2173     fwrite($fp, sprintf("SEND: [%s] [%s]\n", $ssess, $log));
2174     fclose($fp);
2175   }
2176 }
2177
2178 function log_lock($log) {
2179   GLOBAL $sess;
2180
2181   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOCK) == 0)
2182     return;
2183
2184   if (isset($sess) == FALSE)
2185     $ssess = "XXXX";
2186   else
2187     $ssess = $sess;
2188
2189   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOCK) == 0)
2190     return;
2191
2192   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2193     fwrite($fp, sprintf("LOCK: [%s] [%s]\n", $ssess, $log));
2194     fclose($fp);
2195   }
2196 }
2197
2198 function log_wr($log) {
2199   GLOBAL $sess;
2200
2201   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_WRIT) == 0)
2202     return;
2203
2204   if (isset($sess) == FALSE)
2205     $ssess = "XXXX";
2206   else
2207     $ssess = $sess;
2208       
2209   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_WRIT) == 0)
2210     return;
2211
2212   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2213     fwrite($fp, sprintf("WRIT: [%s] [%s]\n", $ssess, $log));
2214     fclose($fp);
2215   }
2216 }
2217
2218 function log_load($log) {
2219   GLOBAL $sess;
2220
2221   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOAD) == 0)
2222     return;
2223
2224   if (isset($sess) == FALSE)
2225     $ssess = "XXXX";
2226   else
2227     $ssess = $sess;
2228
2229   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOAD) == 0)
2230     return;
2231       
2232   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2233     fwrite($fp, sprintf("LOAD: [%s] [%s]\n", $ssess, $log));
2234     fclose($fp);
2235   }
2236 }
2237
2238 function log_auth($sess, $log) {
2239   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_AUTH) == 0)
2240     return;
2241
2242   if (( (BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_AUTH) == 0)
2243     return;
2244
2245   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2246     fwrite($fp, sprintf("AUTH: [%s] [%d] [%s]\n", $sess, time(), $log));
2247     fclose($fp);
2248   }
2249 }
2250
2251
2252 // function log_legal($curtime, $sess, $name, $where, $mesg) 
2253 function log_legal($curtime, &$user, $where, $mesg) 
2254 {
2255   GLOBAL $_SERVER;
2256
2257   if (($fp = @fopen(LEGAL_PATH."/legal.log", 'a')) != FALSE) {
2258     /* Unix time | session | nickname | IP | where was | mesg */
2259     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
2260                         ($user->flags & USER_FLAG_AUTH ? 'A' : 'N'),
2261                         $user->name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
2262     fclose($fp);
2263   }
2264 }
2265
2266
2267
2268
2269 function lock_banlist()
2270 {
2271   if (($tok = @ftok(FTOK_PATH."/main", "L")) == -1) {
2272     echo "FTOK FAILED";
2273     exit;
2274   }
2275   if (($res = sem_get($tok)) == FALSE) {
2276     echo "SEM_GET FAILED";
2277     exit;
2278   }
2279   if (sem_acquire($res)) 
2280     return ($res);
2281   else
2282     return (FALSE);
2283 }
2284
2285 function unlock_banlist($res)
2286 {
2287   return (sem_release($res));
2288 }
2289
2290 function table_act_content_old($isstanding, $sitted, $table, $cur_table)
2291 {
2292   $ret = "";
2293
2294   if ($isstanding) {
2295     if ($sitted < PLAYERS_N) {
2296       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
2297     }
2298   }
2299   else {
2300     if ($table == $cur_table)
2301       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
2302     else
2303       $ret = "";
2304   }
2305   return ($ret);
2306 }
2307
2308 function table_act_content($isstanding, $sitted, $table, $cur_table, $allowed)
2309 {
2310   $ret = "";
2311
2312   if ($isstanding) {
2313     if ($sitted < PLAYERS_N) {
2314       if ($allowed)
2315         $act = 'sit';
2316       else
2317         $act = 'reserved';
2318     }
2319   }
2320   else {
2321     if ($table == $cur_table)
2322       $act = 'wake';
2323     else
2324       $act = 'none';
2325   }
2326
2327   if ($act != '')
2328     $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
2329
2330   return ($ret);
2331 }
2332
2333 function show_notify($text, $tout, $butt, $w, $h)
2334 {
2335   log_main("SHOW_NOTIFY: ".$text);
2336   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
2337 }
2338
2339 function multoval($mult)
2340 {
2341   if ($mult == 2)
2342     return ("doppio");
2343   else if ($mult == 4)
2344     return ("quadruplo");
2345   else
2346     return (sprintf("%d-plo", $mult));
2347 }
2348
2349
2350 function root_wellcome($user)
2351 {
2352   GLOBAL $root_wellarr;
2353   $ret = "";
2354
2355   $curtime = time();
2356   $dt = date("H:i ", $curtime);
2357     
2358   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
2359     $ret .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, str_replace('"', '\"', $root_wellarr[$i]));
2360
2361   return ($ret);
2362 }
2363
2364
2365
2366 function validate_sess($sess) 
2367 {
2368   if (strlen($sess) == SESS_LEN) 
2369     return (TRUE);
2370   else
2371     return (FALSE);
2372 }
2373
2374 function validate_name($name) 
2375 {
2376   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
2377
2378   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2379     $c = $name_new[$i];
2380     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2381       return ($name_new);
2382   }
2383
2384   return (FALSE);
2385 }
2386
2387 function playsound($filename)
2388 {
2389   return (sprintf('playsound("flasou", "%s");', $filename));
2390 }
2391
2392 function secstoword($secs)
2393 {
2394   $mins = floor($secs / 60);
2395   $secs = $secs % 60;
2396   if ($mins > 0) 
2397     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
2398   
2399   if ($secs > 0)
2400     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
2401   
2402   return ($ret);
2403 }
2404
2405 function sharedmem_sz($tok)
2406 {
2407   if (($shm_id = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
2408     log_main("shmop_open failed");
2409     return (-1);
2410   }
2411   $shm_sz = shmop_size($shm_id);
2412   shmop_close($shm_id);
2413   
2414   log_main("shm_sz: ".$shm_sz."   SHM_DIMS: ".SHM_DIMS);
2415   return ($shm_sz);
2416 }    
2417
2418 class Warrant {
2419   function lock_data()
2420   {
2421     GLOBAL $sess; 
2422     
2423     if (($tok = @ftok(FTOK_PATH."/warrant", "B")) == -1) {
2424       return (FALSE);
2425     }
2426     // echo "FTOK ".$tok."<br>";
2427     if (($res = sem_get($tok)) == FALSE) {
2428       return (FALSE);
2429     }
2430     if (sem_acquire($res)) {   
2431       log_lock("LOCK room");
2432       return ($res);
2433     }
2434     else
2435       return (FALSE);
2436   }
2437   
2438   function unlock_data($res)
2439   {
2440     GLOBAL $sess; 
2441     
2442     log_lock("UNLOCK room");
2443     
2444     return (sem_release($res));
2445   }
2446
2447   
2448 }
2449 ?>