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