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