return bug fixed, sidebanner, bg updated
[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       // Before all align times with table timeout
721       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
722         $table_cur =& $this->table[$table_idx];
723         // if the table is complete and exists its shared mem we get the info about users lacc
724
725         if ($table_cur->player_n == PLAYERS_N) {
726           log_main("PLAYERS == N TABLE ".$table_idx);
727           
728           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
729             log_main("bin5 lock data success");
730             
731             $no_recovery = FALSE;
732             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
733               if ($table_cur->table_token != $bri->table_token) {
734                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
735                 log_main("ERROR: not matching table_start. Room: ".$table_cur->table_start."  Table: ".$bri->table_start);
736                 $no_recovery = TRUE;
737                 $bri = FALSE;
738               }
739             }
740             
741             if ($bri != FALSE) {
742               //
743               //  SPAWN: JOIN
744               //
745               log_main("garbage_manager: bri loaded successfully.");
746               $bri->garbage_manager(TRUE);
747               
748               $bri_table = &$bri->table[0];
749
750               // is the end of the table
751               if ($bri->the_end == TRUE) {
752                 /*
753                  *  DESTROY OF FINISHED TABLE && MOVE PLAYER TO ROOM AGAIN
754                  */
755                 log_main("garbage_manager: INSIDE THE END.");
756
757                 $plist = "$table_cur->table_token|$table_cur->idx|$table_cur->player_n";
758                 for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
759                   $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
760                 }
761
762                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
763                   // stat must be "table" by definition
764                   $user_cur =& $this->user[$table_cur->player[$i]];
765                   $bri_user =& $bri->user[$i];
766                   
767                   $user_cur->subst      = $bri_user->subst;
768                   $user_cur->step       = $bri_user->step;
769                   $user_cur->lacc       = $bri_user->lacc;
770                   $user_cur->laccwr     = $bri_user->lacc;
771                   $user_cur->bantime    = $bri_user->bantime;
772                 }
773
774                 log_legal($curtime, $user_cur, "STAT:DESTROY_GAME", $plist);
775
776                 $this->room_join_wakeup(&$user_cur, FALSE, 0); 
777                 $table_cur->table_token = "";
778                 $table_cur->wakeup_time = $curtime + WAKEUP_TIME;
779                 Briskin5::destroy_data($table_idx);
780               }
781               else {
782                 log_main("gm:: save_data");
783
784                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
785                   $this->user[$table_cur->player[$i]]->lacc = $bri->user[$i]->lacc;
786                 }
787               
788                 Briskin5::save_data(&$bri);
789               }
790             } // else if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
791             else if ($no_recovery == FALSE) {
792               log_crit("ERROR: table ".$table_idx." unrecoverable join");
793
794               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
795                 $user_cur = &$this->user[$table_cur->player[$i]];
796                 $user_cur->subst = "shutdowner";
797                 $user_cur->step_inc();
798                 
799                 $ret = sprintf('stat = "%s"; subst = "%s";',  $user_cur->stat, $user_cur->subst);
800                 $ret .= "gst.st = ".($user_cur->step+1)."; ";
801                 $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);
802                 $user_cur->comm[$user_cur->step % COMM_N] = $ret;
803                 $user_cur->step_inc();
804               }
805
806               $plist = "$table_cur->table_token|$user_cur->table|$table_cur->player_n";
807               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
808                 $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
809               }
810               log_legal($curtime, $user_cur, "STAT:DESTROY_GAME(RECOVERY)", $plist);
811               
812               $this->room_join_wakeup(&$user_cur, TRUE, -2); 
813               $table_cur->table_token = "";
814             }
815
816             Briskin5::unlock_data($sem);
817           } // bri::lock_data
818         } //  if ($table_cur->player_n == PLAYERS_N) {
819       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
820     
821       log_rd2("out new loop.");
822                 
823       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
824         $user_cur = &$this->user[$i];
825         
826         log_rd2("User: ".$user_cur->name."  stat: ".$user_cur->stat."  subst: ".$user_cur->subst);
827           
828         if ($user_cur->sess == "") 
829           continue;
830         
831         if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) {
832           // Auto logout dell'utente
833           log_rd2("AUTO LOGOUT.".($user_cur->lacc + EXPIRE_TIME_RD)." curtime ".$curtime);
834           
835           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
836             log_auth($user_cur->sess, "Autologout session.");
837             
838             $user_cur->reset();
839             
840             log_rd2("AUTO LOGOUT.");
841             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
842               $this->room_wakeup(&$user_cur);
843             else if ($user_cur->subst == 'standup')
844               $this->room_outstandup(&$user_cur);
845             else
846               log_rd2("LOGOUT FROM WHAT ???");
847           }
848         }
849
850         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < $curtime) { // lo rimettiamo in piedi
851           if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
852             $this->room_wakeup(&$user_cur);
853             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
854             /* 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" */
855             $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);
856             $user_cur->step_inc();
857           }
858         }
859       }
860       log_rd2("GARBAGE UPDATED!");
861       
862       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
863       $ismod = TRUE;
864     }
865
866     return ($ismod);
867   }
868
869   function show_room($user_step, &$user)
870   {
871     log_main("show_room: username: ".$user->name);
872     
873     $ret = sprintf('gst.st = %d; ',  $user_step);
874
875     if ($user->flags & USER_FLAG_LISTAUTH) {
876       $ret .= 'list_set(\'auth\', false, \'(solo aut.)\' ); ';
877     }
878     else {
879       $ret .= 'list_set(\'all\', false, \'\' ); ';
880     }
881
882     if ($user->subst == 'standup')
883       $ret .= "tra.show(); ";
884     else
885       $ret .= "tra.hide(); ";
886
887     $ret .= sprintf('stat = "%s";',  $user->stat);
888     
889     $ret .= root_wellcome($user);
890     $ret .= sprintf('subst = "%s";', $user->subst);
891     $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
892     $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
893     $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>";', $itin, xcape($user->name), $itou);
894     for ($i = 0 ; $i < TABLES_N ; $i++) {
895       $ret .= $this->table_content($user, $i);
896       // $ret .= table_act_content(($user->subst == 'standup'), $this->table[$i]->player_n, $i, $user->table, 
897       //                          ($this->table[$i]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
898       $ret .=  $this->table[$i]->act_content($user);
899       if ($this->table[$i]->wag_own != NULL) 
900         $ret .= sprintf('tra.add(%d, "%s: %s"); ', $i,  $this->table[$i]->wag_own->name, $this->table[$i]->wag_com);
901       else 
902         $ret .= sprintf('tra.rem(%d); ', $i);
903     }
904     $ret .= $this->standup_content($user);
905     
906     return ($ret);
907   }
908   
909
910   function room_wakeup(&$user)
911   {
912     $table_idx = $user->table;
913     $table = &$this->table[$table_idx];
914
915     log_main("WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
916
917     $curtime = time();
918
919     $from_table = ($user->stat == "table");
920     if ($from_table) {
921       log_main("WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
922
923       for ($i = 0 ; $i < $table->player_n ; $i++) {
924         $user_cur = &$this->user[$table->player[$i]];
925         log_main("PREIMPOST: INLOOP name: ".$user_cur->name);
926
927         if ($user_cur != $user) {
928           $user_cur->stat_set("room");
929           $user_cur->subst = "sitdown";
930           $user_cur->laccwr = $curtime;
931         }
932         else if ($user->sess != "") {
933           $user_cur->stat_set("room");
934           $user_cur->subst = "standup";
935           $user_cur->laccwr = $curtime;
936           $user_cur->table = -1;
937         }
938       }
939     }
940     else {
941       $user->stat_set("room");
942       $user->subst = "standup";
943       $user->laccwr = $curtime;
944     }
945     
946     $remove_wagon = false;
947     if($table->wag_own == $user) {
948       $remove_wagon = true;
949       $table->wag_reset($curtime);
950       
951     }
952     
953
954     /* aggiorna l'array dei giocatori al tavolo. */
955     $table->user_rem(&$this, &$user);
956
957     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
958       $user_cur = &$this->user[$i];
959       if ($user_cur->sess == '' || $user_cur->stat != 'room')
960         continue;
961       
962       log_main("VALORI: name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
963
964       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
965       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
966         $ret .= 'gst.st_loc++; the_end=true; window.onunload = null; window.onbeforeunload = null; document.location.assign("index.php");|';
967         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
968         log_main("DOCUMENT.index.php: from table");
969       }
970       else if ($user_cur->stat == "room") {
971         log_main("DOCUMENT.index.php: from table");
972
973         $ret .= $this->table_content($user_cur, $table_idx);
974         $ret .= $this->standup_content($user_cur);
975         
976         // $ret .= table_act_content(FALSE, 0, $table_idx, $user->table, FALSE);
977         $ret .= $table->act_content($user);
978
979         if ($user_cur == $user) {
980           // set the new status 
981           $ret .=  'subst = "standup"; tra.show(); ';
982           // clean the action buttons in other tables
983           for ($e = 0 ; $e < TABLES_N ; $e++) {
984             if ($this->table[$e]->player_n < PLAYERS_N) {
985               // $ret .= table_act_content(TRUE, 0, $e, $user->table, 
986               //                           ($this->table[$e]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
987               $ret .= $this->table[$e]->act_content($user);
988             }
989           }
990         }
991         else {
992           // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
993           //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
994           $ret .= $table->act_content($user_cur);
995         }
996       }
997       log_wr("ROOM_WAKEUP: ".$ret);
998       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
999       $user_cur->step_inc();
1000     }
1001   }
1002
1003   function room_join_wakeup(&$user, $update_lacc = FALSE, $trans_delta)
1004   {
1005     $table_idx = $user->table;
1006     $table = &$this->table[$table_idx];
1007     
1008     log_main("JOIN_WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1009
1010     $curtime = time();
1011     $user_wup = array();
1012     $user_wup_n = 0;
1013     $user_tab = array();
1014     $user_tab_n = 0;
1015     log_main("JOIN WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1016     
1017     for ($i = 0 ; $i < $table->player_n ; $i++) {
1018       $user_cur = &$this->user[$table->player[$i]];
1019       log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1020       if ($user_cur->sess != "") {
1021         if ($update_lacc == TRUE) {
1022           $user_cur->laccwr = $curtime;
1023         }
1024         log_main("cur: ".$user_cur->name."  subst: ".$user_cur->subst);
1025         if ($user_cur->subst == "shutdowned") {
1026           $user_cur->stat_set("room");
1027           $user_cur->subst = "sitdown";
1028         }
1029         else if ($user_cur->subst == "shutdowner") {
1030           $user_cur->stat_set("room");
1031           $user_cur->subst = "standup";
1032           $user_cur->table = -1;
1033           $user_wup[$user_wup_n++] = &$user_cur;
1034           
1035           $remove_wagon = false;
1036           if($table->wag_own == $user_cur) {
1037             $remove_wagon = true;
1038             $table->wag_reset($curtime);
1039           }
1040         }
1041         $user_tab[$user_tab_n++] = &$user_cur;
1042       }
1043     }
1044
1045     for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
1046       $table->user_rem(&$this, &$user_wup[$wup_idx]);
1047
1048     /* aggiorna l'array dei giocatori al tavolo. */
1049
1050     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1051       log_main("START LOOP");
1052       $user_cur = &$this->user[$i];
1053       if ($user_cur->sess == '' || $user_cur->stat != 'room') {
1054         log_main("name: ".$user_cur->name."skip   subst: ".$user_cur->subst);
1055         continue;
1056       }
1057
1058       log_main("___");
1059       log_main("VALORI name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
1060
1061       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1062       if ($user_cur->stat == "room") {
1063         log_main("DOCUMENT.index.php from table");
1064
1065         $ret .= $this->table_content($user_cur, $table_idx);
1066         $ret .= $this->standup_content($user_cur);
1067         
1068         // $ret .= table_act_content(FALSE, 0, $table_idx, $user_cur->table,
1069         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1070         $ret .= $table->act_content($user_cur);
1071
1072
1073         for ($tab_idx = 0 ; $tab_idx < $user_tab_n  ; $tab_idx++)
1074           if ($user_cur == $user_tab[$tab_idx]) 
1075             break;
1076
1077         // for users that wakeup the room will be reconstructed by index_rd.php
1078         if ($tab_idx < $user_tab_n) {
1079           log_main("PRE show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1080
1081 //        ARRAY_POP DISABLED
1082 //        if ($trans_delta == 0)
1083 //          while (array_pop($user_cur->comm) != NULL);
1084
1085           $user_cur->trans_step = $user_cur->step + 1 + $trans_delta;
1086           $user_cur->comm[$user_cur->step % COMM_N] = "";
1087           $user_cur->step_inc();
1088           $user_cur->comm[$user_cur->step % COMM_N] = $this->show_room(($user_cur->step + 1), &$user_cur);
1089           $user_cur->step_inc();
1090           log_main("POST show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1091
1092           continue;
1093         }
1094         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
1095
1096         log_main("JOIN_WAKEUP more");
1097         // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
1098         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1099         $ret .= $table->act_content($user_cur);
1100
1101         log_main("JOIN_WAKEUP end more");
1102       }
1103       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
1104       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1105       $user_cur->step_inc();
1106     }
1107   }
1108
1109   function room_outstandup(&$user)
1110   {
1111     $this->room_sitdown(&$user, -1);
1112   }
1113   
1114   function table_update(&$user)
1115   {
1116     log_main("table_update: pre - USER: ".$user->name);
1117
1118     $table_idx = $user->table;
1119
1120     if ($table_idx > -1) 
1121       $table = &$this->table[$table_idx];
1122     
1123     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1124       $ret = "";
1125       $user_cur = &$this->user[$i];
1126       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1127       continue;
1128       
1129       $ret = "gst.st = ".($user_cur->step+1)."; ";
1130       if ($table_idx > -1)
1131         $ret .= $this->table_content($user_cur, $table_idx);
1132       
1133       if ($user_cur == $user) {
1134         $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1135         $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1136         $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', $itin, xcape($user->name), $itou);
1137       }
1138       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1139       $user_cur->step_inc();
1140     }
1141
1142     log_main("table_update: post");
1143   }
1144
1145   function room_sitdown(&$user, $table_idx)
1146   {
1147     log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1148
1149     $train_app = "";
1150
1151     if ($table_idx > -1 && $table_idx < TABLES_N) { 
1152       $table = &$this->table[$table_idx];
1153
1154       // wagon shutdown 
1155       if ($table->wag_own != NULL && $table->player_n == PLAYERS_N) {        
1156         for ($i = 0 ; $i < TABLES_N ; $i++) {
1157           $user_cur =& $this->user[$table->player[$i]];
1158           if ($user_cur == $table->wag_own) {
1159             $train_app = sprintf("tra.rem(%d); ", $table_idx); 
1160             $table->wag_reset(time());
1161             break;
1162           }
1163         }
1164       }
1165     }
1166
1167     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1168       $ret = "";
1169       $user_cur = &$this->user[$i];
1170       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1171       continue;
1172       
1173       $ret = "gst.st = ".($user_cur->step+1)."; ".$train_app;
1174       if ($table_idx > -1)
1175       $ret .= $this->table_content($user_cur, $table_idx);
1176       $ret .= $this->standup_content($user_cur);
1177       
1178       if ($user_cur == $user) {
1179         $ret .=  'subst = "sitdown"; tra.hide(); ';
1180         // clean the action buttons in other tables
1181         for ($e = 0 ; $e < TABLES_N ; $e++) {
1182           // $ret .= table_act_content(FALSE, 0, $e, $user_cur->table, FALSE);
1183           $ret .= $this->table[$e]->act_content($user_cur);
1184         }
1185       }
1186       else if ($table_idx > -1) {
1187         if ($table->player_n == PLAYERS_N) {
1188           // $ret .= table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table,
1189           ///                      ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1190           $ret .= $table->act_content($user_cur);
1191         }
1192       }
1193       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1194       $user_cur->step_inc();
1195     }
1196   }
1197
1198   function chatt_send(&$user, $mesg)
1199   {
1200     GLOBAL $G_alarm_passwd;
1201     $only_you = FALSE;
1202     
1203     // common settings
1204     $msg = substr($mesg, 6, 128);
1205     $curtime = time();
1206     $dt = date("H:i ", $curtime);
1207
1208     //
1209     //  Compute actions
1210     //
1211
1212     $to_user     = FALSE;
1213     $to_all      = FALSE;
1214     $to_room     = FALSE;
1215     $to_tabl     = FALSE;
1216     $is_normchat = FALSE;
1217     $update_room = FALSE;
1218
1219     if (strcmp($msg,  "/tav") == 0 || 
1220         strncmp($msg, "/tav ", 5) == 0) {
1221       do {
1222         if ($user->stat != 'room' || $user->subst != 'sitdown') {
1223           /* 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>" */
1224           $msg = "<br>Per attivare il messaggio di segnalazione del tavolo occorre essere seduti.<br><br>";
1225           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1226
1227           break;
1228         }
1229
1230         $table = &$this->table[$user->table];
1231         
1232         if ($table->wag_own != NULL) {
1233           $msg = "<br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br>";
1234           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1235
1236           break;
1237         }
1238
1239         $dtime = $curtime - $table->wag_tout;
1240         if ($dtime  < EXPIRE_TIME_WAG) {
1241           $msg = sprintf("<br>Il messaggio di segnalazione del tavolo<br>&egrave; disattivato ancora per %d second%s.<br><br>",
1242                          EXPIRE_TIME_WAG - $dtime, (EXPIRE_TIME_WAG - $dtime == 1 ? "o" : "i"));
1243           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1244
1245           break;
1246         }
1247         
1248         $msg = substr($msg, 5);
1249         
1250         $table->wag_set($user, $msg);
1251         $to_user = sprintf('tra.add(%d, "%s");', $user->table, xcape(sprintf("%s: %s", $user->name, $msg)));
1252         $to_room = $to_user;
1253         
1254       } while (0);
1255     } // /tav chat command
1256
1257     else if (strncmp($msg, "/alarm ", 7) == 0) {
1258       if (strncmp($msg, "/alarm to ", 10) == 0) {
1259         $sp_pos = strpos($msg, " ", 10);
1260         $target = substr($msg, 10, $sp_pos - 10);
1261         $alarm_check = "/alarm to ".$target." ".$G_alarm_passwd." ";
1262       }
1263       else {
1264         $target = "";
1265         $alarm_check = "/alarm ".$G_alarm_passwd." ";
1266       }
1267       do {
1268         if (strncmp($msg, $alarm_check, strlen($alarm_check)) != 0) {
1269           /* MLANG: "<br>La password digitata non &egrave; corretta.<br><br>" */
1270           $msg = "<br>La password digitata non &egrave; corretta.<br><br>";
1271           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1272
1273           break;
1274         }
1275
1276         /* MLANG: "Alarm <b>%s</b> inviato a <b>%s</b>." */
1277         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Alarm <b>%s</b> inviato a <b>%s</b>.");', 
1278                            $dt, NICKSERV, xcape(substr($msg, strlen($alarm_check))), 
1279                            ($target == "" ? "tutti" : xcape($target)) );
1280
1281         $msg = sprintf("<br><b>%s<br><br>%s</b><br><br>",
1282                        $dt.NICKSERV, xcape(substr($msg, strlen($alarm_check))));
1283         /* MLANG: "chiudi" */
1284         $to_all = show_notify($msg, 0, "chiudi", 400, 120);
1285       } while (0);
1286     } // /alarm chat command
1287     else if (strncmp($msg, "/listen ", 8) == 0) {
1288       $arg = substr($msg, 8);
1289
1290       if (strcasecmp($arg, "auth") == 0) {
1291         $user->flags |= USER_FLAG_LISTAUTH;
1292         $to_user = 'list_set(\'auth\', true, \'(solo aut.)\'); ';
1293       }
1294       else {
1295         $user->flags &= ~USER_FLAG_LISTAUTH;
1296         $to_user = 'list_set(\'all\', true, \'\'); ';
1297       }
1298     }
1299     else if (strncmp($msg, "/garante", 8) == 0) {
1300       if ($user->flags & USER_FLAG_AUTH) {
1301         $to_user = sprintf('authbox(300,200);');
1302       }
1303       else {
1304         /* 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." */
1305         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Per autenticare qualcuno devi a tua volta essere autenticato.</b>");', $dt, NICKSERV);
1306       }
1307     }
1308     else if (strncmp($msg, "/mesgtoadm", 8) == 0) {
1309       if ($user->flags & USER_FLAG_AUTH) {
1310         $to_user = sprintf('mesgtoadmbox(500,300);');
1311       }
1312       else {
1313         /* MLANG: "<b>Per inviare un messaggio devi essere autenticato.</b>" */
1314         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Per inviare un messaggio devi essere autenticato.</b>");', $dt, NICKSERV);
1315       }
1316     }
1317     else if (strncmp($msg, "/nick ", 6) == 0) {
1318       log_main("chatt_send BEGIN");
1319
1320       do {
1321         if (($name_new = validate_name(substr($msg, 6))) == FALSE) {
1322           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Il nickname deve contenere almeno una lettera dell\'alfabeto o una cifra.");', $dt, NICKSERV);
1323           break;
1324         }
1325
1326         $msg = "COMMAND ".$msg;
1327         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1328           $user_cur = &$this->user[$i];
1329
1330           if ($user_cur->sess == '')
1331             continue;
1332           if ($user_cur->name == $name_new)
1333             break;
1334           }
1335         if ($i <  MAX_PLAYERS) {
1336           $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Nickname <b>%s</b> gi&agrave; in uso.");', $dt, NICKSERV, xcape($name_new));
1337           break;
1338         }
1339         
1340         /* 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>" */
1341         if ($user->flags & USER_FLAG_AUTH) {
1342           if (strcasecmp($user->name,$name_new) != 0) {
1343             if ($user->subst == 'standup' || ($user->subst != 'standup' && $this->table[$user->table]->auth_only == FALSE)) {
1344               $user->flags &= ~USER_FLAG_AUTH; // Remove auth if name changed
1345               for ($i = 0 ; $i < TABLES_N ; $i++) {
1346                 $to_user .= $this->table[$i]->act_content($user);
1347               }
1348             }
1349             else {
1350               $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Non puoi cambiare nick a un tavolo per soli autenticati.</b>");', $dt, NICKSERV);
1351               break;
1352             }
1353           }
1354         }
1355         $user->name = $name_new; // OK - nick changed
1356         /* se nome gia' in uso, segnala cosa potrebbe capitare */
1357         if (($user->flags & USER_FLAG_AUTH) == 0) {
1358           $userdb = new LoginDB();
1359           /* 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>" */
1360           if ($userdb->login_exists($name_new)) {
1361             $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));
1362           }
1363         }
1364
1365         log_main("chatt_send start set");
1366
1367         $update_room = TRUE;
1368       } while (0);
1369     } // nick chat command
1370
1371     else if (strncmp($msg, "/st ", 4) == 0) {
1372       log_main("chatt_send BEGIN");
1373
1374       do {
1375         $st_str = substr($msg, 4);
1376         
1377         if (strcasecmp($st_str, "normale") == 0) {
1378           $st = USER_FLAG_S_NORM;
1379         }
1380         else if (strcasecmp($st_str, "pausa") == 0) {
1381           $st = USER_FLAG_S_PAU;
1382         }
1383         else if (strcasecmp($st_str, "fuori") == 0) {
1384           $st = USER_FLAG_S_OUT;
1385         }
1386         else if (strcasecmp($st_str, "cane") == 0) {
1387           $st = USER_FLAG_S_DOG;
1388         }
1389         else if (strcasecmp($st_str, "cibo") == 0) {
1390           $st = USER_FLAG_S_EAT;
1391         }
1392         else if (strcasecmp($st_str, "lavoro") == 0) {
1393           $st = USER_FLAG_S_WRK;
1394         }
1395         else if (strcasecmp($st_str, "sigaretta") == 0) {
1396           $st = USER_FLAG_S_SMK;
1397         }
1398         else if (strcasecmp($st_str, "presente") == 0) {
1399           $st = USER_FLAG_S_EYE;
1400         }
1401         else {
1402           /* MLANG: "Questo stato non esiste." */
1403           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Questo stato non esiste.");', $dt, NICKSERV);
1404           break;
1405         }
1406
1407         log_main("chatt_send start set");
1408         if (($user->flags & USER_FLAG_S_ALL) != $st) {
1409           $update_room = TRUE;
1410           $user->flags = ($user->flags & ~USER_FLAG_S_ALL) | $st;
1411         }
1412       } while (0);
1413     } // nick chat command
1414
1415     else { // normal chat line
1416       $is_normchat = TRUE;
1417       if ($curtime < ($user->chat_ban + $user->chat_dlt)) {
1418         $only_you = TRUE;
1419         $user->chat_dlt = $user->chat_dlt * 2; 
1420         if ($user->chat_dlt > 120)
1421           $user->chat_dlt = 120; 
1422       }
1423       else if ($user->chat_lst == $msg)
1424         $only_you = TRUE;
1425       else if ($curtime - $user->chattime[($user->chat_cur + 1) % CHAT_N] < CHAT_ILL_TIME) {
1426         $user->chat_ban = $curtime;
1427         $user->chat_dlt = 5;
1428         $only_you = TRUE;
1429       }
1430       else {
1431         $user->chat_ban = 0;
1432         $user->chat_dlt = 0;
1433       }
1434
1435       if ($only_you) {
1436         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape("== chat ban =="));
1437       }
1438       else {
1439         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape($msg));
1440         // temporary silentiation for troll (will became array check)
1441         if (strcasecmp($user->name,'JackRokka') != 0 && $user->sess != '47ea653f602e8')
1442           $to_room = $to_user;
1443       }
1444
1445       log_legal($curtime, $user, 
1446                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$msg);
1447       
1448       $user->chat_lst = "$msg";
1449       $user->chattime[$user->chat_cur % CHAT_N] = $curtime;
1450       $user->chat_cur++;
1451     }
1452
1453     if ($to_all) {
1454       $to_room = $to_all;
1455       $to_tabl = $to_all;
1456     }
1457
1458     //
1459     //  Output to clients
1460     //
1461
1462     if ($to_user != FALSE) {
1463       $user->comm[$user->step % COMM_N] =  "gst.st = ".($user->step+1)."; ";
1464       $user->comm[$user->step % COMM_N] .= $to_user;
1465       $user->step_inc();
1466     }
1467
1468     if ($to_room != FALSE) {
1469       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1470         $user_cur = &$this->user[$i];
1471         if ($target != "" && $user_cur->name != $target)
1472           continue;
1473         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1474         if ($user_cur->sess == '' || $user_cur->stat == 'table' || $user_cur == $user)
1475           continue;
1476         
1477         if ($is_normchat == TRUE) {
1478           if ($user_cur->flags & USER_FLAG_LISTAUTH) {
1479             if (($user->flags & USER_FLAG_AUTH) == 0) {
1480               continue;
1481             }
1482           }
1483         }
1484   
1485         $user_cur->comm[$user_cur->step % COMM_N] =  "gst.st = ".($user_cur->step+1)."; ";
1486         $user_cur->comm[$user_cur->step % COMM_N] .= $to_room; 
1487         $user_cur->step_inc();
1488       }
1489     }
1490     
1491     if ($to_tabl) {
1492       // Before all align times with table timeout
1493       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1494         $table_cur =& $this->table[$table_idx];
1495         // if the table is complete and exists its shared mem we get the info about users lacc
1496         
1497         if ($table_cur->player_n == PLAYERS_N) {
1498           log_main("PLAYERS == N TABLE ".$table_idx);
1499         
1500           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
1501             log_main("bin5 lock data success");
1502             
1503             $no_recovery = FALSE;
1504             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1505               if ($table_cur->table_token != $bri->table_token) {
1506                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
1507                 $bri = FALSE;
1508               }
1509             }
1510             
1511             if ($bri != FALSE) {
1512               $bri_table = &$bri->table[0];
1513               for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
1514                 // stat must be "table" by definition
1515                 $bri_user =& $bri->user[$i];
1516               
1517                 if ($target != "" && $bri_user->name != $target)
1518                   continue;
1519                 log_main("writa: ".$user_mesg);
1520                 $bri_user->comm[$bri_user->step % COMM_N] = "gst.st = ".($bri_user->step+1)."; ";
1521                 $bri_user->comm[$bri_user->step % COMM_N] .= $to_tabl;
1522                 $bri_user->step_inc();
1523               }
1524               Briskin5::save_data(&$bri);
1525             }
1526             Briskin5::unlock_data($sem);
1527           } // bri::lock_data
1528         } //  if ($table_cur->player_n == PLAYERS_N) {
1529       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1530     } // if ($to_tabl == true ...
1531
1532     if ($update_room) {
1533       if ($user->stat == 'room' && $user->subst == 'standup') {
1534         $this->standup_update(&$user);
1535       }
1536       else if ($user->stat == 'room' && $user->subst == 'sitdown') {
1537         log_main("chatt_send pre table update");
1538         $this->table_update(&$user);
1539         log_main("chatt_send post table update");
1540       }
1541     } // if ($update_room ...
1542
1543     return;
1544   } // function chatt_send( ...
1545
1546   function &get_user($sess, &$idx)
1547   {
1548     GLOBAL $PHP_SELF, $G_false;
1549
1550     if (validate_sess($sess)) {
1551       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1552         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1553           // find it
1554           $idx = $i;
1555           $ret = &$this->user[$i];
1556           return ($ret);
1557         }
1558       }
1559       log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1560       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1561       // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1562     }
1563     else {
1564       log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
1565     }
1566
1567     return ($G_false);
1568   }
1569
1570   
1571
1572   /*
1573    * function &add_user(&$room, &$sess, &$idx, $name, $pass, $ip)
1574    *
1575    * RETURN VALUE:
1576    *   if ($idx >  -1    && ret == FALSE)  =>  duplicated nick
1577    *   if ($idx == -2    && ret == FALSE)  =>  invalid name
1578    *   if ($idx == -3    && ret == FALSE)  =>  wrong password
1579    *   if ($idx == -1    && ret == FALSE)  =>  no space left
1580    *   if ($idx ==  0    && ret == user)   =>  SUCCESS
1581    *   if ($idx == -$idx && ret == user)   =>  SUCCESS (but the login exists in the auth db 
1582    */
1583
1584
1585
1586   function &add_user(&$sess, &$idx, $name, $pass, $ip)
1587   {
1588     GLOBAL $G_false, $CO_list;
1589
1590     $idx = 0;
1591
1592     $authenticate = FALSE;
1593     $login_exists = FALSE;
1594     $ghost = -1;
1595     $ghost_auth = FALSE;
1596     $idx = -1;
1597     $idfree = -1;
1598     
1599     if (($name_new = validate_name($name)) == FALSE) {
1600       $idx = -2;
1601       return ($G_false);
1602     }
1603
1604     log_auth("XXX", sprintf("ARRIVA: [%s] pass:[%s]", $sess, ($pass == FALSE ? "FALSE" : $pass)));
1605     if (validate_sess($sess) == FALSE) 
1606       $sess = "";
1607
1608     /* if pass != FALSE verify the login with pass */
1609     log_auth("XXX", "auth1");
1610     $userdb = new LoginDB();
1611     if ($pass != FALSE) {
1612       log_auth("XXX", "auth2");
1613       $authenticate = $userdb->login_verify($name_new, $pass);
1614       log_auth("XXX", "authenticate: ".($authenticate == TRUE ? "TRUE" : "FALSE"));
1615       
1616       if ($authenticate == FALSE) {
1617         $idx = -3;
1618         return ($G_false);
1619       }
1620     }
1621     else {
1622       $login_exists =  $userdb->login_exists($name_new);
1623     }
1624     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1625       /* free user ? */
1626       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1627         if ($idx == -1)
1628           $idx = $i;
1629       }
1630       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
1631         $idfree = $i;
1632         continue; // NOTE: CHECK IT !!
1633       }
1634       if (strcasecmp($this->user[$i]->name, $name_new) == 0) {
1635         if ($authenticate == FALSE) {
1636           $idx = $i;
1637           break;
1638         }
1639         else {
1640           $ghost = $i;
1641           $ghost_auth = ($this->user[$i]->flags & USER_FLAG_AUTH);
1642         }
1643       }
1644     }
1645     if ($idx == -1)
1646       $idx = $idfree;
1647
1648     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1649
1650     if ($ghost > -1 && $ghost_auth && $authenticate) {
1651       /* swap session */
1652
1653       $ghost_user =& $this->user[$ghost];
1654       $curtime = time();
1655       $ghost_user->step_inc();
1656       if ($sess == "") {
1657         $sess = uniqid(""); 
1658         $ghost_user->sess = $sess;
1659       }
1660       else {
1661         $ghost_user->sess = $sess;
1662       }
1663       
1664       // If user at the table we need to update the table data too
1665       $table_idx = $ghost_user->table;
1666       if ($ghost_user->stat == "table" && $this->table[$table_idx]->player_n == PLAYERS_N) {
1667         if (($brisem = Briskin5::lock_data($table_idx)) != FALSE) { 
1668           if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1669             if ($bri->the_end != TRUE) {
1670               $bri->user[$ghost_user->table_pos]->step_inc();
1671               $bri->user[$ghost_user->table_pos]->sess = $sess;
1672               Briskin5::save_data(&$bri);
1673             }
1674           }
1675           Briskin5::unlock_data($brisem);
1676         }
1677       }
1678
1679       $idx = $ghost;
1680       return ($this->user[$ghost]);
1681     }
1682     else if ($idx != -1 && $i == MAX_PLAYERS) {
1683       /* SUCCESS */
1684       $curtime = time();
1685       if ($sess == "") {
1686         $sess = uniqid("");
1687         $this->user[$idx]->sess = $sess;
1688       }
1689       else {
1690         $this->user[$idx]->sess = $sess;
1691       }
1692       $this->user[$idx]->name = $name_new; // OK - add new user
1693       $this->user[$idx]->stat_set("room");
1694       $this->user[$idx]->step_set(0);
1695       while (array_pop($this->user[$idx]->comm) != NULL);
1696       $this->user[$idx]->subst = "standup";
1697       $this->user[$idx]->lacc =   $curtime;
1698       $this->user[$idx]->laccwr = $curtime;
1699       $this->user[$idx]->bantime = 0;
1700       $this->user[$idx]->ip = $ip;
1701
1702       $this->user[$idx]->flags = ($authenticate ? USER_FLAG_AUTH : 0x00);
1703       
1704       if ($authenticate) {
1705         $this->user[$idx]->flags |= USER_FLAG_LISTAUTH;
1706
1707         if (isset($CO_list) && strcmp($CO_list, "all") == 0) {
1708           $this->user[$idx]->flags &= ~USER_FLAG_LISTAUTH;
1709         }
1710       }
1711       
1712       if ($ghost > -1) {
1713         log_main("ghost: rename!");
1714         $ghost_user =& $this->user[$ghost];
1715
1716         if ($ghost_auth == FALSE) {
1717           for ($sfx = 1 ; $sfx <= MAX_PLAYERS ; $sfx++) {
1718             $ghostname = 'ghost'.$sfx;
1719             for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1720               if (strcmp("", $this->user[$i]->sess) == 0) 
1721                 continue;
1722               
1723               if (strcmp($this->user[$i]->name, $ghostname) == 0) {
1724                 $ghostname = '';
1725                 break;
1726               }
1727             }
1728             if ($ghostname != '')
1729               break;
1730           }
1731           
1732           $ghost_user->name = $ghostname;
1733           
1734           if ($ghost_user->stat == 'room' && $ghost_user->subst == 'standup') {
1735             $this->standup_update(&$ghost_user);
1736           }
1737           else {
1738             log_main("chatt_send pre table update");
1739             $this->table_update(&$ghost_user);
1740           log_main("chatt_send post table update");
1741           }
1742         } // if ($ghost_auth == FALSE
1743         else {
1744           // FIXME: cacciare il vecchio utente room && table (if needed)
1745           $ghost_user->the_end = TRUE;
1746           $ghost_user->lacc = 0;
1747           $this->garbage_manager(TRUE);
1748         }
1749       } //  if ($ghost > -1) {
1750
1751       log_main(sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1752       $real_idx = $idx;
1753       if ($login_exists)
1754         $idx = -($idx + 1);
1755       return ($this->user[$real_idx]);
1756     }
1757
1758     return ($G_false);
1759   }
1760   
1761   function standup_update(&$user)
1762   {
1763     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1764       $user_cur = &$this->user[$i];
1765       if ($user_cur->sess == '')
1766         continue;
1767
1768       log_main("STANDUP START: ".$user_cur->stat);
1769       
1770       if ($user_cur->stat == 'room') {
1771         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".$this->standup_content($user_cur);
1772         if ($user_cur == $user) {
1773           $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1774           $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1775
1776           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', 
1777                                                                $itin, xcape($user->name), $itou);
1778         }
1779         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1780         
1781         $user_cur->step_inc();
1782       }
1783     }
1784   }
1785
1786   // Static functions
1787   function &init_data()
1788   {
1789     $room =& new Room();
1790     
1791     return $room;
1792   }
1793   
1794
1795   function &load_data() 
1796   {
1797     GLOBAL $G_false, $sess;
1798     $doexit = FALSE;
1799     do {
1800       if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1801         log_main("ftok failed");
1802         $doexit = TRUE;
1803         break;
1804       }
1805     
1806       if (($shm_sz = sharedmem_sz($tok)) == -1) {
1807         log_main("shmop_open failed");
1808       }
1809         
1810       if ($shm_sz == -1)
1811         $shm_sz = SHM_DIMS_MIN;
1812
1813       if ($shm = shm_attach($tok, $shm_sz)) {
1814         $room = @shm_get_var($shm, $tok);
1815         
1816         log_only("bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
1817         if (isset($room)) 
1818           log_only("bri count ".count($room));
1819         
1820         if ($room == FALSE) {
1821           log_only("INIT MAIN DATA");
1822           
1823           $room =& Room::init_data();
1824           if (@shm_put_var($shm, $tok, $room) == FALSE) {
1825             log_only("PUT_VAR FALLITA ".strlen(serialize($room)));
1826             log_only(serialize($room));
1827           }
1828         }
1829         $room->shm_sz = $shm_sz;
1830         
1831         shm_detach($shm);
1832       }
1833       $ret = &$room;
1834       return ($ret);
1835     } while (0);
1836     
1837     if ($doexit)
1838       exit();
1839     
1840     return ($G_false);
1841   }
1842   
1843
1844   function save_data(&$room) 
1845   {
1846     GLOBAL $sess;
1847     
1848     $shm =   FALSE;
1849     
1850     // var_dump($room);
1851     
1852     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) 
1853       return (FALSE);
1854     
1855     while ($room->shm_sz < SHM_DIMS_MAX) {
1856       if (($shm = shm_attach($tok, $room->shm_sz)) == FALSE)
1857         break;
1858       
1859       // log_only("PUT_VAR DI ".strlen(serialize($room)));
1860       if (shm_put_var($shm, $tok, $room) != FALSE) {
1861         shm_detach($shm);
1862         return (TRUE);
1863       }
1864       if (shm_remove($shm) === FALSE) {
1865         log_only("REMOVE FALLITA");
1866         break;
1867       }
1868       shm_detach($shm);
1869       $room->shm_sz += SHM_DIMS_DLT;
1870     } 
1871
1872     if ($shm)
1873       shm_detach($shm);
1874     
1875     return (FALSE);
1876   }
1877
1878   function lock_data()
1879   {
1880     GLOBAL $sess; 
1881     
1882     //  echo "LOCK: ".FTOK_PATH."/main";
1883     //  exit;
1884     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1885       return (FALSE);
1886     }
1887     // echo "FTOK ".$tok."<br>";
1888     if (($res = sem_get($tok)) == FALSE) {
1889       return (FALSE);
1890     }
1891     if (sem_acquire($res)) {   
1892       log_lock("LOCK room");
1893       return ($res);
1894     }
1895     else
1896       return (FALSE);
1897   }
1898   
1899   function unlock_data($res)
1900   {
1901     GLOBAL $sess; 
1902     
1903     log_lock("UNLOCK room");
1904
1905     return (sem_release($res));
1906   }
1907
1908
1909   function standup_content($user)
1910   {
1911     $ret = "";
1912     $content = "";
1913     
1914     if ($user->stat != 'room')
1915       return;
1916     
1917     for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1918       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
1919         continue;
1920       $ct++;
1921     }
1922     
1923     // $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1924     
1925     $content = ' j_stand_cont( [ ';
1926
1927     for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1928       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
1929         continue;
1930       
1931       $flags = $this->user[$e]->flags;
1932       
1933       if ($this->user[$e]->subst == "standup") {
1934         if ($this->user[$e] == $user) 
1935           { 
1936             $flags |= 1;
1937           }
1938         
1939         $content .= sprintf('%s[ %d, "%s" ]',($ct > 0 ? ', ' : ''), $flags, xcape($this->user[$e]->name));
1940         $ct++;
1941       }
1942     }
1943     $content .= ' ]);';
1944     
1945     return ($content);
1946   }
1947   
1948   function table_content_old($user, $table_idx)
1949   {
1950     $content = "";
1951     $ret = "";
1952     // TODO
1953     //
1954     //   Si possono usare i dati nella classe table
1955     //
1956     
1957     $sess = $user->sess;
1958     $table = &$this->table[$table_idx];
1959     
1960     if ($user->stat != 'room')
1961       return;
1962     
1963     for ($i = 0 ; $i < $table->player_n ; $i++) {
1964       $user_cur = &$this->user[$table->player[$i]];
1965       
1966       if ($user_cur == $user) 
1967         { $hilion = "<b>"; $hilioff = "</b>"; }
1968       else
1969         { $hilion = ""; $hilioff = ""; }
1970       
1971       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
1972       
1973       $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1974     }
1975     /*
1976   for ( ; $i < PLAYERS_N ; $i++)
1977     $content .= "<br>";
1978     */
1979     
1980     $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1981     
1982     return ($ret);
1983   }
1984
1985
1986   function table_content($user, $table_idx)
1987   {
1988     $content = "";
1989     $ret = "";
1990     // TODO
1991     //
1992     //   Si possono usare i dati nella classe table
1993     //
1994     
1995     $sess = $user->sess;
1996     $table = &$this->table[$table_idx];
1997     
1998     if ($user->stat != 'room')
1999       return;
2000     
2001     $content = "[ ";
2002     for ($i = 0 ; $i < $table->player_n ; $i++) {
2003       $user_cur = &$this->user[$table->player[$i]];
2004
2005       $flags = $user_cur->flags;
2006
2007       if ($user_cur == $user) 
2008         $flags |= 1;
2009       
2010       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2011       
2012       $content .= sprintf('%s[ %d, "%s" ]',($i == 0 ? '' : ', '), $flags, xcape($user_cur->name));
2013     }
2014
2015     $content .= ' ]';
2016
2017     $ret .= sprintf('j_tab_cont(%d, %s);', $table_idx, $content);
2018     
2019     return ($ret);
2020   }
2021
2022 } // end class Room
2023
2024 function make_seed()
2025 {
2026   list($usec, $sec) = explode(' ', microtime());
2027   return (float) $sec + ((float) $usec * 100000);
2028 }
2029
2030
2031 function log_only2($log) {
2032   GLOBAL $sess;
2033
2034   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONL2) == 0)
2035     return;
2036
2037   if (isset($sess) == FALSE)
2038     $ssess = "XXXX";
2039   else
2040     $ssess = $sess;
2041
2042   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONL2) == 0)
2043     return;
2044
2045   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2046     fwrite($fp, sprintf("ONL2: [%s] [%s]\n", $ssess, $log));
2047     fclose($fp);
2048   }
2049 }
2050
2051 function log_crit($log) {
2052   GLOBAL $sess;
2053
2054   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CRIT) == 0)
2055     return;
2056
2057   if (isset($sess) == FALSE)
2058     $ssess = "XXXX";
2059   else
2060     $ssess = $sess;
2061
2062   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CRIT) == 0)
2063     return;
2064
2065   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2066     fwrite($fp, sprintf("CRIT: [%s] [%s]\n", $ssess, $log));
2067     fclose($fp);
2068   }
2069 }
2070
2071 function log_only($log) {
2072   GLOBAL $sess;
2073
2074   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONLY) == 0)
2075     return;
2076
2077   if (isset($sess) == FALSE)
2078     $ssess = "XXXX";
2079   else
2080     $ssess = $sess;
2081
2082   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONLY) == 0)
2083     return;
2084
2085   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2086     fwrite($fp, sprintf("ONLY: [%s] [%s]\n", $ssess, $log));
2087     fclose($fp);
2088   }
2089 }
2090
2091 function log_main($log) {
2092   GLOBAL $sess;
2093
2094   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_MAIN) == 0)
2095     return;
2096
2097   if (isset($sess) == FALSE)
2098     $ssess = "XXXX";
2099   else
2100     $ssess = $sess;
2101
2102   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_MAIN) == 0)
2103     return;
2104
2105   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2106     fwrite($fp, sprintf("MAIN: [%s] [%s]\n", $ssess, $log));
2107     fclose($fp);
2108   }
2109 }
2110
2111 function log_rd($log) {
2112   GLOBAL $sess;
2113
2114   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_READ) == 0)
2115     return;
2116
2117   if (isset($sess) == FALSE)
2118     $ssess = "XXXX";
2119   else
2120     $ssess = $sess;
2121
2122   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_READ) == 0)
2123     return;
2124
2125   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2126     fwrite($fp, sprintf("READ: [%s] [%s]\n", $ssess, $log));
2127     fclose($fp);
2128   }
2129 }
2130
2131 function log_rd2($log) {
2132   GLOBAL $sess;
2133
2134   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_REA2) == 0)
2135     return;
2136
2137   if (isset($sess) == FALSE)
2138     $ssess = "XXXX";
2139   else
2140     $ssess = $sess;
2141       
2142   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_REA2) == 0)
2143     return;
2144
2145   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2146     fwrite($fp, sprintf("REA2: [%s] [%s]\n", $ssess, $log));
2147     fclose($fp);
2148   }
2149 }
2150
2151 function log_send($log) {
2152   GLOBAL $sess;
2153
2154   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SEND) == 0)
2155     return;
2156
2157   if (isset($sess) == FALSE)
2158     $ssess = "XXXX";
2159   else
2160     $ssess = $sess;
2161       
2162   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SEND) == 0)
2163     return;
2164
2165   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2166     fwrite($fp, sprintf("SEND: [%s] [%s]\n", $ssess, $log));
2167     fclose($fp);
2168   }
2169 }
2170
2171 function log_lock($log) {
2172   GLOBAL $sess;
2173
2174   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOCK) == 0)
2175     return;
2176
2177   if (isset($sess) == FALSE)
2178     $ssess = "XXXX";
2179   else
2180     $ssess = $sess;
2181
2182   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOCK) == 0)
2183     return;
2184
2185   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2186     fwrite($fp, sprintf("LOCK: [%s] [%s]\n", $ssess, $log));
2187     fclose($fp);
2188   }
2189 }
2190
2191 function log_wr($log) {
2192   GLOBAL $sess;
2193
2194   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_WRIT) == 0)
2195     return;
2196
2197   if (isset($sess) == FALSE)
2198     $ssess = "XXXX";
2199   else
2200     $ssess = $sess;
2201       
2202   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_WRIT) == 0)
2203     return;
2204
2205   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2206     fwrite($fp, sprintf("WRIT: [%s] [%s]\n", $ssess, $log));
2207     fclose($fp);
2208   }
2209 }
2210
2211 function log_load($log) {
2212   GLOBAL $sess;
2213
2214   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOAD) == 0)
2215     return;
2216
2217   if (isset($sess) == FALSE)
2218     $ssess = "XXXX";
2219   else
2220     $ssess = $sess;
2221
2222   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOAD) == 0)
2223     return;
2224       
2225   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2226     fwrite($fp, sprintf("LOAD: [%s] [%s]\n", $ssess, $log));
2227     fclose($fp);
2228   }
2229 }
2230
2231 function log_auth($sess, $log) {
2232   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_AUTH) == 0)
2233     return;
2234
2235   if (( (BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_AUTH) == 0)
2236     return;
2237
2238   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2239     fwrite($fp, sprintf("AUTH: [%s] [%d] [%s]\n", $sess, time(), $log));
2240     fclose($fp);
2241   }
2242 }
2243
2244
2245 // function log_legal($curtime, $sess, $name, $where, $mesg) 
2246 function log_legal($curtime, &$user, $where, $mesg) 
2247 {
2248   GLOBAL $_SERVER;
2249
2250   if (($fp = @fopen(LEGAL_PATH."/legal.log", 'a')) != FALSE) {
2251     /* Unix time | session | nickname | IP | where was | mesg */
2252     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
2253                         ($user->flags & USER_FLAG_AUTH ? 'A' : 'N'),
2254                         $user->name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
2255     fclose($fp);
2256   }
2257 }
2258
2259
2260
2261
2262 function lock_banlist()
2263 {
2264   if (($tok = @ftok(FTOK_PATH."/main", "L")) == -1) {
2265     echo "FTOK FAILED";
2266     exit;
2267   }
2268   if (($res = sem_get($tok)) == FALSE) {
2269     echo "SEM_GET FAILED";
2270     exit;
2271   }
2272   if (sem_acquire($res)) 
2273     return ($res);
2274   else
2275     return (FALSE);
2276 }
2277
2278 function unlock_banlist($res)
2279 {
2280   return (sem_release($res));
2281 }
2282
2283 function table_act_content_old($isstanding, $sitted, $table, $cur_table)
2284 {
2285   $ret = "";
2286
2287   if ($isstanding) {
2288     if ($sitted < PLAYERS_N) {
2289       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
2290     }
2291   }
2292   else {
2293     if ($table == $cur_table)
2294       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
2295     else
2296       $ret = "";
2297   }
2298   return ($ret);
2299 }
2300
2301 function table_act_content($isstanding, $sitted, $table, $cur_table, $allowed)
2302 {
2303   $ret = "";
2304
2305   if ($isstanding) {
2306     if ($sitted < PLAYERS_N) {
2307       if ($allowed)
2308         $act = 'sit';
2309       else
2310         $act = 'reserved';
2311     }
2312   }
2313   else {
2314     if ($table == $cur_table)
2315       $act = 'wake';
2316     else
2317       $act = 'none';
2318   }
2319
2320   if ($act != '')
2321     $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
2322
2323   return ($ret);
2324 }
2325
2326 function show_notify($text, $tout, $butt, $w, $h)
2327 {
2328   log_main("SHOW_NOTIFY: ".$text);
2329   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
2330 }
2331
2332 function multoval($mult)
2333 {
2334   if ($mult == 2)
2335     return ("doppio");
2336   else if ($mult == 4)
2337     return ("quadruplo");
2338   else
2339     return (sprintf("%d-plo", $mult));
2340 }
2341
2342
2343 function root_wellcome($user)
2344 {
2345   GLOBAL $root_wellarr;
2346   $ret = "";
2347
2348   $curtime = time();
2349   $dt = date("H:i ", $curtime);
2350     
2351   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
2352     $ret .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, str_replace('"', '\"', $root_wellarr[$i]));
2353
2354   return ($ret);
2355 }
2356
2357
2358
2359 function validate_sess($sess) 
2360 {
2361   if (strlen($sess) == SESS_LEN) 
2362     return (TRUE);
2363   else
2364     return (FALSE);
2365 }
2366
2367 function validate_name($name) 
2368 {
2369   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
2370
2371   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2372     $c = $name_new[$i];
2373     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2374       return ($name_new);
2375   }
2376
2377   return (FALSE);
2378 }
2379
2380 function playsound($filename)
2381 {
2382   return (sprintf('playsound("flasou", "%s");', $filename));
2383 }
2384
2385 function secstoword($secs)
2386 {
2387   $mins = floor($secs / 60);
2388   $secs = $secs % 60;
2389   if ($mins > 0) 
2390     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
2391   
2392   if ($secs > 0)
2393     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
2394   
2395   return ($ret);
2396 }
2397
2398 function sharedmem_sz($tok)
2399 {
2400   if (($shm_id = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
2401     log_main("shmop_open failed");
2402     return (-1);
2403   }
2404   $shm_sz = shmop_size($shm_id);
2405   shmop_close($shm_id);
2406   
2407   log_main("shm_sz: ".$shm_sz."   SHM_DIMS: ".SHM_DIMS);
2408   return ($shm_sz);
2409 }    
2410
2411 class Warrant {
2412   function lock_data()
2413   {
2414     GLOBAL $sess; 
2415     
2416     if (($tok = @ftok(FTOK_PATH."/warrant", "B")) == -1) {
2417       return (FALSE);
2418     }
2419     // echo "FTOK ".$tok."<br>";
2420     if (($res = sem_get($tok)) == FALSE) {
2421       return (FALSE);
2422     }
2423     if (sem_acquire($res)) {   
2424       log_lock("LOCK room");
2425       return ($res);
2426     }
2427     else
2428       return (FALSE);
2429   }
2430   
2431   function unlock_data($res)
2432   {
2433     GLOBAL $sess; 
2434     
2435     log_lock("UNLOCK room");
2436     
2437     return (sem_release($res));
2438   }
2439
2440   
2441 }
2442 ?>