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