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