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