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