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