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