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