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