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