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