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