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