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