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