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