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