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