flags_vlt attribute added to user class to manage volatile attributes (icon status...
[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.8.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>: prova il nuovo azioni->preferenze.',
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>: server-side infrastructure to manage user preferences added and S customization added.',
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   // function act_content($isstanding, $sitted, $table, $cur_table, $allowed)
605   function act_content($user)
606   {
607     $ret = "";
608     $isstanding = ($user->subst == 'standup');
609     $sitted = $this->player_n;
610     $table = $this->idx;
611     $cur_table = $user->table;
612     $allowed = TRUE;
613
614     if ($isstanding) {
615       if ($sitted < PLAYERS_N) {
616         if ($this->auth_only) {
617           if ($user->flags & USER_FLAG_AUTH) 
618             $act = "sitreser";
619           else
620             $act = 'reserved';
621         }
622         else {
623           $act = 'sit';
624         }
625       }
626       else {
627         $act = 'none';
628       }
629     }
630     else {
631       if ($table == $cur_table)
632         $act = 'wake';
633       else
634         $act = 'none';
635     }
636     
637     if ($act != '')
638       $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
639     
640     return ($ret);
641   }
642 } // end class Table
643
644
645 class Delay_Manager
646 {
647     var $delta;
648     var $lastckeck;
649     var $triglevel;
650
651     function Delay_Manager($triglevel)
652     {
653         $this->triglevel = $triglevel;
654         $this->delta = array();
655         $this->lastcheck = 0;
656     }
657
658     function delta_get($curtime)
659     {
660         // clean too old delta items
661         for ($i = 0 ; $i < count($this->delta) ; $i++) {
662             if ($this->delta[$i][0] < $curtime) {
663                 array_splice($this->delta, $i, 1);
664                 $i--;
665             }
666         }
667
668         // add new delta items if delay exceeded $this->triglevel sec
669         if ($curtime > $this->lastcheck + $this->triglevel && $curtime < $this->lastcheck + 1200.0) {
670             $delta = $curtime - $this->lastcheck - $this->triglevel;
671             array_push($this->delta, array($curtime + $delta , $delta));
672             // fprintf(STDERR, "DELTA: add new delta [%f] [%f] [%f]\n", $this->triglevel, $curtime + $delta, $delta);
673         }
674
675         // extract the maximum valid delta
676         $delta_max = 0.0;
677         for ($i = 0 ; $i < count($this->delta) ; $i++) {
678             $delta_cur = $this->delta[$i][1];
679             if ($delta_max < $delta_cur)
680                 $delta_max = $delta_cur;
681         }
682
683         // fprintf(STDERR, "DELTA: status %d, delta_max: %f\n", count($this->delta), $delta_max);
684
685         return ($delta_max);
686     }
687
688     function lastcheck_set($curtime)
689     {
690         $this->lastcheck = $curtime;
691     }
692 }
693
694 class Client_prefs {
695     var $listen;
696     var $supp_comp;
697
698     function Client_prefs()
699     {
700     }
701
702     static function from_user($user)
703     {
704         $thiz = new Client_prefs();
705         $thiz->user_load($user);
706
707         return ($thiz);
708     }
709
710     static function from_json($json)
711     {
712         $thiz = new Client_prefs();
713         if ($thiz->json_load($json) == FALSE) {
714             unset($thiz);
715             return (FALSE);
716         }
717
718         return ($thiz);
719     }
720
721     function user_load($user)
722     {
723         fprintf(STDERR, "QQ %s: %x\n", __FUNCTION__, $user->flags);
724         $this->listen = ($user->flags & USER_FLAG_MAP_AUTH) >> 2;
725         if ($user->rec != FALSE) {
726             $this->supp_comp = $user->rec->supp_comp;
727         }
728         else {
729             $this->supp_comp = "000000000000";
730         }
731
732         fprintf(STDERR, "QQ %s: LISTEN: %d\n", __FUNCTION__, $this->listen);
733     }
734
735     function json_load($json_s)
736     {
737         $ret = FALSE;
738
739         do {
740             if (gettype($json_s) == "string") {
741                 if (($json = json_decode($json_s)) == FALSE)
742                     break;
743             }
744             else {
745                 $json = $json_s;
746             }
747             if ($this->listen < 0 || $this->listen > 2)
748                 break;
749             $this->listen = $json->listen;
750
751             if (mb_strlen($json->supp_comp, "ASCII") != 12)
752                 break;
753
754             for ($i = 0, $idx = 0 ; $i < 12 ; $i++) {
755                 if (($json->supp_comp[$i] >= '0' && $json->supp_comp[$i] <= '9') ||
756                     ($json->supp_comp[$i] >= 'a' && $json->supp_comp[$i] <= 'f'))
757                     continue;
758                 break;
759             }
760             if ($i < 12)
761                 break;
762             $this->supp_comp = $json->supp_comp;
763             $ret = TRUE;
764         } while (FALSE);
765
766         return ($ret);
767     }
768
769     function store($user, $is_save)
770     {
771         // save into DB
772         fprintf(STDERR, "QQ %s::%s PRE: %x\n", __CLASS__, __FUNCTION__,
773                 $user->flags & (~USER_FLAG_AUTH));
774         $user->flags_set(($this->listen << 2), USER_FLAG_MAP_AUTH);
775         fprintf(STDERR, "QQ %s::%s %x\n", __CLASS__, __FUNCTION__,
776                 $user->flags);
777         if ($user->is_supp_custom()) {
778             $user->rec->supp_comp = $this->supp_comp;
779         }
780         if ($is_save)
781             $user->store_set();
782     }
783 }
784
785
786 class Room
787 {
788     static $delta_t;
789     
790     var $crystal_filename;
791     var $user;
792     var $table;
793     var $match;
794     var $comm; // commands for many people
795     var $step; // current step of the comm array
796     var $garbage_timeout;
797     var $shm_sz;
798     
799     var $delay_mgr;
800
801     function Room ($crystal_filename) {
802         $this->crystal_filename = $crystal_filename;
803         $this->user  = array();
804         $this->table = array();
805         $this->match = array();
806         
807         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
808             $this->user[$i] = User::create($this, $i, "", "");
809         }
810         
811         for ($i = 0 ; $i < TABLES_N ; $i++) {
812             $this->table[$i] = Table::create($i);
813             /* OLD METHOD
814                if ($i < 12) {
815                $row = ( (((int)($i / 4)) % 2) == 0 );
816                $col = ($i % 2 == 0);
817                $this->table[$i]->auth_only = (($row && $col) || (!$row && !$col));
818                }
819                else {
820                $this->table[$i]->auth_only = FALSE;
821                }
822             */
823             if ($i < TABLES_AUTH_N) 
824                 $this->table[$i]->auth_only = TRUE;
825             else
826                 $this->table[$i]->auth_only = FALSE;
827         }
828         $this->garbage_timeout = 0;
829         $this->shm_sz = SHM_DIMS_MIN;
830
831         $this->delay_mgr = new Delay_Manager(1.5);
832     }
833
834   function garbage_manager($force)
835   {
836     GLOBAL $G_lang, $mlang_brisk, $G_base;
837
838     $ismod = FALSE;
839
840     log_rd2("garbage_manager START");
841
842     /* Garbage collector degli utenti in timeout */
843     $curtime = microtime(TRUE);
844
845     $delta = $this->delay_mgr->delta_get($curtime);
846
847     if (!$force && !($this->garbage_timeout < $curtime)) {
848         $this->delay_mgr->lastcheck_set($curtime);
849         return ($ismod);
850     }
851       
852     // Before all align times with table timeout
853     for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
854         $table_cur = $this->table[$table_idx];
855         // if the table is complete and exists its shared mem we get the info about users lacc
856         
857         if ($table_cur->player_n == PLAYERS_N) {
858             log_main("PLAYERS == N TABLE ".$table_idx);
859             
860             
861             $no_recovery = FALSE;
862             if (isset($this->match[$table_idx])) {
863                 $bri = $this->match[$table_idx];
864
865                 if ($table_cur->table_token != $bri->table_token) {
866                     log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
867                     log_main("ERROR: not matching table_start. Room: ".$table_cur->table_start."  Table: ".$bri->table_start);
868                     $no_recovery = TRUE;
869                     $bri = FALSE;
870                 }
871
872                 if ($bri != FALSE) {
873                     //
874                     //  SPAWN: JOIN
875                     //
876                     log_main("garbage_manager: bri loaded successfully.");
877                     $bri->garbage_manager(TRUE);
878                     
879                     $bri_table = $bri->table[0];
880                     
881                     // is the end of the table
882                     
883                     if ($bri->the_end == TRUE) {
884                         /*
885                          *  DESTROY OF FINISHED TABLE && MOVE PLAYER TO ROOM AGAIN
886                          */
887                         log_main("garbage_manager: INSIDE THE END.");
888                         
889                         $plist = "$table_cur->table_token|$table_cur->idx|$table_cur->player_n";
890                         for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
891                             $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
892                         }
893                         
894                         for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
895                             // stat must be "table" by definition
896                             $user_cur = $this->user[$table_cur->player[$i]];
897                             $bri_user = $bri->user[$i];
898                             
899                             $user_cur->subst      = $bri_user->subst;
900                             $user_cur->step       = $bri_user->step;
901                             $user_cur->lacc       = $bri_user->lacc;
902                             $user_cur->laccwr     = $bri_user->lacc;
903                             $user_cur->bantime    = $bri_user->bantime;
904                         }
905                         
906                         log_legal($curtime, $user_cur->ip, $user_cur, "STAT:DESTROY_GAME", $plist);
907                         
908                         $this->room_join_wakeup($user_cur, FALSE, 0); 
909                         $table_cur->table_token = "";
910                         $table_cur->wakeup_time = $curtime + WAKEUP_TIME;
911                         
912                         $this->match_del($table_idx);
913                     }
914                     else {
915                         log_main("gm:: save_data");
916                         
917                         for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
918                             $this->user[$table_cur->player[$i]]->lacc = $bri->user[$i]->lacc;
919                         }
920                     }
921                 } // if ($bri == FALSE
922                 else if ($no_recovery == FALSE) {
923                     log_crit("ERROR: table ".$table_idx." unrecoverable join");
924                     
925                     for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
926                         $user_cur = $this->user[$table_cur->player[$i]];
927                         $user_cur->subst = "shutdowner";
928                         $user_cur->step_inc();
929                         
930                         $ret = sprintf('stat = "%s"; subst = "%s";',  $user_cur->stat, $user_cur->subst);
931                         $ret .= "gst.st = ".($user_cur->step+1)."; ";
932                         // MLANG <br>I dati del tavolo n&deg; ".$user_cur->table." sono inconsistenti, verranno resettati.<br><br>Torni in piedi.<br><br>
933                         $prestr = sprintf($mlang_brisk['tabincon'][$G_lang], $user_cur->table);
934                         $ret .= show_notify($prestr, 2000, $mlang_brisk['btn_close'][$G_lang], 400, 110);
935                         $user_cur->comm[$user_cur->step % COMM_N] = $ret;
936                         $user_cur->step_inc();
937                     }
938                     
939                     $plist = "$table_cur->table_token|$user_cur->table|$table_cur->player_n";
940                     for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
941                         $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
942                     }
943                     log_legal($curtime, $user_cur->ip, $user_cur, "STAT:DESTROY_GAME(RECOVERY)", $plist);
944                     
945                     $this->room_join_wakeup($user_cur, TRUE, -2); 
946                     $table_cur->table_token = "";
947                 }
948             }
949         } //  if ($table_cur->player_n == PLAYERS_N) {
950     } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
951     
952     log_rd2("out new loop.");
953     
954     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
955         $user_cur = $this->user[$i];
956         
957         log_rd2("User: ".$user_cur->name."  stat: ".$user_cur->stat."  subst: ".$user_cur->subst);
958         
959         if ($user_cur->sess == "") 
960             continue;
961
962         if ($user_cur->lacc + EXPIRE_TIME_RD < ($curtime - $delta)) {
963             // Auto logout dell'utente
964             log_rd2("AUTO LOGOUT.".($user_cur->lacc + EXPIRE_TIME_RD)." curtime - delta ".($curtime - $delta));
965             
966             if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
967                 log_auth($user_cur->sess, "Autologout session.");
968                 
969                 $user_cur->reset();
970             
971                 log_rd2("AUTO LOGOUT.");
972                 if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
973                     $this->room_wakeup($user_cur);
974                 else if ($user_cur->subst == 'standup')
975                     $this->room_outstandup($user_cur);
976                 else
977                     log_rd2("LOGOUT FROM WHAT ???");
978             }
979         }
980
981         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < ($curtime - $delta)) { // lo rimettiamo in piedi
982             if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
983                 $this->room_wakeup($user_cur);
984                 $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
985                 /* 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" */
986                 $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);
987                 $user_cur->step_inc();
988             }
989         }
990     }
991     log_rd2("GARBAGE UPDATED!");
992     
993     $this->garbage_timeout = $curtime + GARBAGE_TIMEOUT;
994     $ismod = TRUE;
995
996     $this->delay_mgr->lastcheck_set($curtime);
997     return ($ismod);
998   }
999
1000   function show_room($user_step, $user)
1001   {
1002     GLOBAL $G_lang, $mlang_brisk;
1003     log_main("show_room: username: ".$user->name);
1004     
1005     $ret = sprintf('gst.st = %d; ',  $user_step);
1006
1007     $prefs = Client_prefs::from_user($user);
1008     $ret .= sprintf('prefs_load(\'%s\', false, false);', json_encode($prefs));
1009
1010     if(false) {
1011         if ($user->flags & USER_FLAG_ISOLAUTH) {
1012             $ret .= 'list_set(\'isolation\', false, \''.$mlang_brisk['tit_onisol'][$G_lang].'\' ); ';
1013         }
1014         else if ($user->flags & USER_FLAG_LISTAUTH) {
1015             $ret .= 'list_set(\'auth\', false, \''.$mlang_brisk['tit_onauth'][$G_lang].'\' ); ';
1016         }
1017         else {
1018             $ret .= 'list_set(\'all\', false, \'\' ); ';
1019         }
1020     }
1021
1022     if ($user->subst == 'standup')
1023       $ret .= "tra.show(); ";
1024     else
1025       $ret .= "tra.hide(); ";
1026
1027     $ret .= sprintf('stat = "%s";',  $user->stat);
1028     
1029     $ret .= root_welcome($user);
1030     if ($user->flags & USER_FLAG_DBFAILED) {
1031         $ret .= "gst.st = ".($user->step+1)."; ";
1032         $ret .= show_notify($mlang_brisk['db_failed'][$G_lang], 0, $mlang_brisk['btn_close'][$G_lang], 400, 140);
1033     }
1034
1035     $ret .= sprintf('subst = "%s";', $user->subst);
1036     $ret .= $user->myname_innerHTML();
1037
1038     for ($i = 0 ; $i < TABLES_N ; $i++) {
1039
1040       $ret .= $this->table_content($user, $i);
1041       $ret .=  $this->table[$i]->act_content($user);
1042       if ($this->table[$i]->wag_own != -1) 
1043         $ret .= sprintf('tra.add(%d, "%s: %s"); ', $i,  $this->user[$this->table[$i]->wag_own]->name, $this->table[$i]->wag_com);
1044       else 
1045         $ret .= sprintf('tra.rem(%d); ', $i);
1046     }
1047     $ret .= $this->standup_content($user);
1048     $ret .= "setTimeout(preload_images, 0, g_preload_img_arr, g_imgct); ";
1049
1050     return ($ret);
1051   }
1052   
1053
1054   function room_wakeup($user)
1055   {
1056     $table_idx = $user->table;
1057     $table = $this->table[$table_idx];
1058
1059     log_main("WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1060
1061     $curtime = time();
1062
1063     $from_table = ($user->stat == "table");
1064     if ($from_table) {
1065       log_main("WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1066
1067       for ($i = 0 ; $i < $table->player_n ; $i++) {
1068         $user_cur = $this->user[$table->player[$i]];
1069         log_main("PREIMPOST: INLOOP name: ".$user_cur->name);
1070
1071         if ($user->idx_get() != $table->player[$i]) {
1072           $user_cur->stat_set("room");
1073           $user_cur->subst = "sitdown";
1074           $user_cur->laccwr = $curtime;
1075         }
1076         else if ($user->sess != "") {
1077           $user_cur->stat_set("room");
1078           $user_cur->subst = "standup";
1079           $user_cur->laccwr = $curtime;
1080           $user_cur->table = -1;
1081         }
1082       }
1083     }
1084     else {
1085       $user->stat_set("room");
1086       $user->subst = "standup";
1087       $user->laccwr = $curtime;
1088     }
1089     
1090     $remove_wagon = FALSE;
1091     if($table->wag_own == $user->idx_get()) {
1092       $table->wag_reset($curtime);
1093       $remove_wagon = TRUE;
1094     }
1095     
1096
1097     /* aggiorna l'array dei giocatori al tavolo. */
1098     $table->user_rem($this, $user);
1099
1100     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1101       $user_cur = $this->user[$i];
1102       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1103         continue;
1104
1105       // log_main("VALORI: name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
1106
1107       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1108       if ($from_table && ($user_cur->table == $table_idx || $user->idx_get() == $i)) {
1109         $ret .= 'gst.st_loc++; xstm.stop(); window.onunload = null; window.onbeforeunload = null; document.location.assign("index.php");|';
1110         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
1111         log_main("DOCUMENT.index.php: from table");
1112       }
1113       else if ($user_cur->stat == "room") {
1114         log_main("DOCUMENT.index.php: from table");
1115
1116         $ret .= $this->table_content($user_cur, $table_idx);
1117         $ret .= $this->standup_content($user_cur);
1118         
1119         // $ret .= table_act_content(FALSE, 0, $table_idx, $user->table, FALSE);
1120         $ret .= $table->act_content($user);
1121
1122         if ($user->idx_get() == $i) {
1123           // set the new status 
1124           $ret .=  'subst = "standup"; tra.show(); ';
1125           // clean the action buttons in other tables
1126           for ($e = 0 ; $e < TABLES_N ; $e++) {
1127             if ($this->table[$e]->player_n < PLAYERS_N) {
1128               $ret .= $this->table[$e]->act_content($user);
1129             }
1130           }
1131         }
1132         else {
1133           $ret .= $table->act_content($user_cur);
1134         }
1135       }
1136       log_wr("ROOM_WAKEUP: ".$ret);
1137       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1138       $user_cur->step_inc();
1139     }
1140   }
1141
1142   function room_join_wakeup($user, $update_lacc = FALSE, $trans_delta)
1143   {
1144     $table_idx = $user->table;
1145     $table = $this->table[$table_idx];
1146     
1147     log_main("JOIN_WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1148
1149     $curtime = time();
1150     $user_wup = array();
1151     $user_wup_n = 0;
1152     $user_tab = array();
1153     $user_tab_n = 0;
1154     log_main("JOIN WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1155     
1156     for ($i = 0 ; $i < $table->player_n ; $i++) {
1157       $user_cur = $this->user[$table->player[$i]];
1158       log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1159       if ($user_cur->sess != "") {
1160         if ($update_lacc == TRUE) {
1161           $user_cur->laccwr = $curtime;
1162         }
1163         log_main("cur: ".$user_cur->name."  subst: ".$user_cur->subst);
1164         if ($user_cur->subst == "shutdowned") {
1165           $user_cur->stat_set("room");
1166           $user_cur->subst = "sitdown";
1167         }
1168         else if ($user_cur->subst == "shutdowner") {
1169           $user_cur->stat_set("room");
1170           $user_cur->subst = "standup";
1171           $user_cur->table = -1;
1172           $user_wup[$user_wup_n++] = $user_cur;
1173           
1174           $remove_wagon = FALSE;
1175           if($table->wag_own == $table->player[$i]) {
1176             $remove_wagon = TRUE;
1177             $table->wag_reset($curtime);
1178           }
1179         }
1180         $user_tab[$user_tab_n++] = $table->player[$i];
1181       }
1182     }
1183
1184     for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
1185       $table->user_rem($this, $user_wup[$wup_idx]);
1186
1187     /* aggiorna l'array dei giocatori al tavolo. */
1188
1189     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1190       log_main("START LOOP");
1191       $user_cur = $this->user[$i];
1192       if ($user_cur->sess == '' || $user_cur->stat != 'room') {
1193         log_main("name: ".$user_cur->name."skip   subst: ".$user_cur->subst);
1194         continue;
1195       }
1196
1197       log_main("___");
1198       log_main("VALORI name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx);
1199
1200       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1201       if ($user_cur->stat == "room") {
1202         log_main("DOCUMENT.index.php from table");
1203
1204         $ret .= $this->table_content($user_cur, $table_idx);
1205         $ret .= $this->standup_content($user_cur);
1206         
1207         $ret .= $table->act_content($user_cur);
1208
1209
1210         for ($tab_idx = 0 ; $tab_idx < $user_tab_n  ; $tab_idx++)
1211             if ($user_tab[$tab_idx] == $i) 
1212                 break;
1213
1214         // for users that wakeup the room will be reconstructed by index_rd.php
1215         if ($tab_idx < $user_tab_n) {
1216           log_main("PRE show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1217
1218 //        ARRAY_POP DISABLED
1219 //        if ($trans_delta == 0)
1220 //          while (array_pop($user_cur->comm) != NULL);
1221
1222           $user_cur->trans_step = $user_cur->step + 1 + $trans_delta;
1223           $user_cur->comm[$user_cur->step % COMM_N] = "";
1224           $user_cur->step_inc();
1225           $user_cur->comm[$user_cur->step % COMM_N] = $this->show_room(($user_cur->step + 1), $user_cur);
1226           $user_cur->step_inc();
1227           log_main("POST show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1228
1229           continue;
1230         }
1231         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
1232
1233         log_main("JOIN_WAKEUP more");
1234         $ret .= $table->act_content($user_cur);
1235
1236         log_main("JOIN_WAKEUP end more");
1237       }
1238       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
1239       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1240       $user_cur->step_inc();
1241     }
1242   }
1243
1244   function room_outstandup($user)
1245   {
1246     $this->room_sitdown($user, -1);
1247   }
1248   
1249   function table_update($user)
1250   {
1251     log_main("table_update: pre - USER: ".$user->name);
1252
1253     $table_idx = $user->table;
1254
1255     if ($table_idx > -1) 
1256       $table = $this->table[$table_idx];
1257     
1258     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1259       $ret = "";
1260       $user_cur = $this->user[$i];
1261       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1262       continue;
1263
1264       $ret = "gst.st = ".($user_cur->step+1)."; ";
1265       if ($table_idx > -1)
1266         $ret .= $this->table_content($user_cur, $table_idx);
1267       
1268       if ($user->idx_get() == $i) {
1269           $ret .= $user->myname_innerHTML();
1270       }
1271       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1272       $user_cur->step_inc();
1273     }
1274
1275     log_main("table_update: post");
1276   }
1277
1278   function room_sitdown($user, $table_idx)
1279   {
1280     log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1281
1282     $train_app = "";
1283
1284     if ($table_idx > -1 && $table_idx < TABLES_N) { 
1285       $table = $this->table[$table_idx];
1286
1287       // wagon shutdown 
1288       if ($table->wag_own != -1 && $table->player_n == PLAYERS_N) {        
1289         for ($i = 0 ; $i < TABLES_N ; $i++) {
1290             if ($table->wag_own == $table->player[$i]) {
1291                 $train_app = sprintf("tra.rem(%d); ", $table_idx); 
1292                 $table->wag_reset(time());
1293                 break;
1294             }
1295         }
1296       }
1297     }
1298
1299     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1300       $ret = "";
1301       $user_cur = $this->user[$i];
1302       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1303       continue;
1304       
1305       $ret = "gst.st = ".($user_cur->step+1)."; ".$train_app;
1306       if ($table_idx > -1)
1307       $ret .= $this->table_content($user_cur, $table_idx);
1308       $ret .= $this->standup_content($user_cur);
1309       
1310       if ($user->idx_get() == $i) {
1311         $ret .=  'subst = "sitdown"; tra.hide(); ';
1312         // clean the action buttons in other tables
1313         for ($e = 0 ; $e < TABLES_N ; $e++) {
1314           // $ret .= table_act_content(FALSE, 0, $e, $user_cur->table, FALSE);
1315           $ret .= $this->table[$e]->act_content($user_cur);
1316         }
1317       }
1318       else if ($table_idx > -1) {
1319         if ($table->player_n == PLAYERS_N) {
1320           $ret .= $table->act_content($user_cur);
1321         }
1322       }
1323       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1324       $user_cur->step_inc();
1325     }
1326   }
1327
1328   function chatt_send($user, $mesg)
1329   {
1330     GLOBAL $G_base, $G_alarm_passwd, $mlang_brisk, $G_lang;
1331     $only_you = FALSE;
1332     
1333     // common settings
1334     $msg = mb_substr($mesg, 6, 128, "UTF-8");
1335     $curtime = time();
1336     $dt = date("H:i ", $curtime);
1337     $target = "";
1338
1339     //
1340     //  Compute actions
1341     //
1342
1343     $to_user     = FALSE;
1344     $to_all      = FALSE;
1345     $to_room     = FALSE;
1346     $to_tabl     = FALSE;
1347     $is_normchat = FALSE;
1348     /* for old isolation management $is_ticker   = FALSE; */
1349     $update_room = FALSE;
1350
1351     if (strcmp($msg,  "/tav") == 0 || 
1352         strncmp($msg, "/tav ", 5) == 0) {
1353       do {
1354         if ($user->stat != 'room' || $user->subst != 'sitdown') {
1355           /* 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>" */
1356           $msg = $mlang_brisk['tickmust'][$G_lang];
1357           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1358
1359           break;
1360         }
1361
1362         $table = $this->table[$user->table];
1363         
1364         if ($table->wag_own != -1) {
1365           // MLANG <br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br> 
1366           $msg = $mlang_brisk['tickjust'][$G_lang];
1367           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1368
1369           break;
1370         }
1371
1372         $dtime = $curtime - $table->wag_tout;
1373         if ($dtime  < EXPIRE_TIME_WAG) {
1374           // MLANG - <br>Il messaggio di segnalazione del tavolo<br>&egrave; disattivato ancora per %d second%s.<br><br>
1375           $msg = sprintf($mlang_brisk['tickwait'][$G_lang],
1376                          EXPIRE_TIME_WAG - $dtime, (EXPIRE_TIME_WAG - $dtime == 1 ? ($G_lang == 'en' ? "" : "o") : ($G_lang == 'en' ? "s" : "i")));
1377           $to_user = show_notify($msg, 0, $mlang_brisk['btn_close'][$G_lang] , 400, 100);
1378
1379           break;
1380         }
1381         
1382         $msg = substr($msg, 5);
1383         
1384         $table->wag_set($user->idx_get(), $msg);
1385         $to_user = sprintf('tra.add(%d, "%s");', $user->table, xcape(sprintf("%s: %s", $user->name, $msg)));
1386         $to_room = $to_user;
1387         /* for old isolation management $is_ticker = TRUE; */
1388       } while (0);
1389     } // /tav chat command
1390
1391     else if (strncmp($msg, "/alarm ", 7) == 0) {
1392       if (strncmp($msg, "/alarm to ", 10) == 0) {
1393         $sp_pos = strpos($msg, " ", 10);
1394         $target = substr($msg, 10, $sp_pos - 10);
1395         $alarm_check = "/alarm to ".$target." ".$G_alarm_passwd." ";
1396       }
1397       else {
1398         $target = "";
1399         $alarm_check = "/alarm ".$G_alarm_passwd." ";
1400       }
1401       do {
1402         if (strncmp($msg, $alarm_check, strlen($alarm_check)) != 0) {
1403           /* MLANG: "<br>La password digitata non &egrave; corretta.<br><br>" */
1404           $msg = $mlang_brisk['alarpass'][$G_lang];
1405           $to_user = show_notify($msg, 0, $mlang_brisk['btn_close'][$G_lang], 400, 100);
1406
1407           break;
1408         }
1409
1410         /* MLANG: "Alarm <b>%s</b> inviato a <b>%s</b>." */
1411         $prestr = sprintf($mlang_brisk['alarret'][$G_lang], xcape(substr($msg, strlen($alarm_check))), 
1412                            ($target == "" ? $mlang_brisk['tit_all'][$G_lang] : xcape($target)) );
1413         $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],%s);', $dt, NICKSERV, $prestr);
1414
1415         $msg = sprintf("<br><b>%s<br><br>%s</b><br><br>",
1416                        $dt.NICKSERV, xcape(substr($msg, strlen($alarm_check))));
1417         /* MLANG: "chiudi" */
1418         $to_all = show_notify($msg, 0, $mlang_brisk['btn_close'][$G_lang], 400, 120);
1419       } while (0);
1420     } // /alarm chat command
1421     else if (strncmp($msg, "/listen ", 8) == 0) {
1422       $arg = substr($msg, 8);
1423
1424       if (strcasecmp($arg, "isolation") == 0) {
1425         $flags_old = 0;
1426         if ($user->stat == 'room' && $user->subst == 'sitdown' &&
1427             $user->table >= TABLES_AUTH_N) {
1428           $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['listmust'][$G_lang]);
1429           
1430         }
1431         else {
1432           $user->flags &= ~USER_FLAG_MAP_AUTH;
1433           $user->flags |= USER_FLAG_ISOLAUTH;
1434           $to_user = 'list_set(\'isolation\', true, \''.$mlang_brisk['tit_onisol'][$G_lang].'\'); ';
1435         }
1436       }
1437       else if (strcasecmp($arg, "auth") == 0) {
1438         $flags_old = $user->flags;
1439         $user->flags &= ~USER_FLAG_MAP_AUTH;
1440         $user->flags |= USER_FLAG_LISTAUTH;
1441         $to_user = 'list_set(\'auth\', true, \''.$mlang_brisk['tit_onauth'][$G_lang].'\'); ';
1442       }
1443       else {
1444         $flags_old = $user->flags;
1445         $user->flags &= ~USER_FLAG_MAP_AUTH;
1446         $to_user = 'list_set(\'all\', true, \'\'); ';
1447         
1448       }
1449       // if from isolation redraw standup area
1450       if (($flags_old ^ $user->flags) & USER_FLAG_ISOLAUTH) {
1451         $to_user .= 'standup_data_old = null; '.$this->standup_content($user);
1452         
1453       }
1454     }
1455     else if (strcmp($msg, "/authreq") == 0) {
1456       if ($user->flags & USER_FLAG_AUTH) {
1457         $to_user = sprintf('authbox(300,200);');
1458       }
1459       else {
1460         /* 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." */
1461         $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['authmust'][$G_lang]);
1462       }
1463     }
1464     else if (strncmp($msg, "/mesgtoadm", 8) == 0) {
1465       if ($user->flags & USER_FLAG_AUTH) {
1466         $to_user = sprintf('mesgtoadmbox(500,300);');
1467       }
1468       else {
1469         /* MLANG: "<b>Per inviare un messaggio devi essere autenticato.</b>" */
1470         $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['mesgmust'][$G_lang]);
1471       }
1472     }
1473     else if (strncmp($msg, "/nick ", 6) == 0) {
1474       log_main("chatt_send BEGIN");
1475
1476       do {
1477         if (($name_new = validate_name(substr($msg, 6))) == FALSE) {
1478           $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['nickmust'][$G_lang]);
1479           break;
1480         }
1481
1482         $msg = "COMMAND ".$msg;
1483         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1484           $user_cur = $this->user[$i];
1485
1486           if ($user_cur->sess == '')
1487             continue;
1488           if (strcasecmp($user_cur->name,$name_new) == 0)
1489             break;
1490           }
1491         if ($i <  MAX_PLAYERS) {
1492           $prestr = sprintf($mlang_brisk['nickdupl'][$G_lang], xcape($name_new));
1493           $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $prestr);
1494           break;
1495         }
1496         
1497         /* 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>" */
1498         if ($user->flags & USER_FLAG_AUTH) {
1499           if (strcasecmp($user->name,$name_new) != 0) {
1500              if (( ($user->flags & USER_FLAG_MAP_AUTH) != USER_FLAG_ISOLAUTH) &&
1501                 ($user->subst == 'standup' || 
1502                  ($user->subst != 'standup' && $this->table[$user->table]->auth_only == FALSE)
1503                  )
1504                 ) {
1505               $user->flags &= ~(USER_FLAG_AUTH | USER_FLAG_TY_ALL); // Remove auth if name changed
1506               for ($i = 0 ; $i < TABLES_N ; $i++) {
1507                 $to_user .= $this->table[$i]->act_content($user);
1508               }
1509             }
1510             else {
1511               $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['authchan'][$G_lang]);
1512               break;
1513             }
1514           }
1515         }
1516         $user->name = $name_new; // OK - nick changed
1517         /* se nome gia' in uso, segnala cosa potrebbe capitare */
1518         if (($user->flags & USER_FLAG_AUTH) == 0) {
1519             if (($bdb = BriskDB::create()) != FALSE) {
1520                 $bdb->users_load();
1521                 /* 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>" */
1522                 if ($bdb->login_exists($name_new)) {
1523                     $prestr = sprintf($mlang_brisk['nickjust'][$G_lang], xcape($name_new));
1524                     $to_user .= sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $prestr);
1525                 }
1526             }
1527         }
1528
1529         log_main("chatt_send start set");
1530
1531         $update_room = TRUE;
1532       } while (0);
1533     } // nick chat command
1534
1535     else if (strncmp($msg, "/st ", 4) == 0) {
1536       log_main("chatt_send BEGIN");
1537
1538       do {
1539         $st_str = substr($msg, 4);
1540         
1541         if (strcasecmp($st_str, "normale") == 0) {
1542           $st = USER_FLAG_S_NORM;
1543         }
1544         else if (strcasecmp($st_str, "pausa") == 0) {
1545           $st = USER_FLAG_S_PAU;
1546         }
1547         else if (strcasecmp($st_str, "fuori") == 0) {
1548           $st = USER_FLAG_S_OUT;
1549         }
1550         else if (strcasecmp($st_str, "cane") == 0) {
1551           $st = USER_FLAG_S_DOG;
1552         }
1553         else if (strcasecmp($st_str, "cibo") == 0) {
1554           $st = USER_FLAG_S_EAT;
1555         }
1556         else if (strcasecmp($st_str, "lavoro") == 0) {
1557           $st = USER_FLAG_S_WRK;
1558         }
1559         else if (strcasecmp($st_str, "sigaretta") == 0) {
1560           $st = USER_FLAG_S_SMK;
1561         }
1562         else if (strcasecmp($st_str, "presente") == 0) {
1563           $st = USER_FLAG_S_EYE;
1564         }
1565         else if (strcasecmp($st_str, "coniglio") == 0) {
1566           $st = USER_FLAG_S_RABB;
1567         }
1568         else if (strcasecmp($st_str, "calcio") == 0) {
1569           $st = USER_FLAG_S_SOCC;
1570         }
1571         else if (strcasecmp($st_str, "pupo") == 0) {
1572           $st = USER_FLAG_S_BABY;
1573         }
1574         else if (strcasecmp($st_str, "pulizie") == 0) {
1575           $st = USER_FLAG_S_MOP;
1576         }
1577         else if (strcasecmp($st_str, "babbo") == 0) {
1578           $st = USER_FLAG_S_BABBO;
1579         }
1580         else if (strcasecmp($st_str, "renna") == 0) {
1581           $st = USER_FLAG_S_RENNA;
1582         }
1583         else if (strcasecmp($st_str, "pupazzo") == 0) {
1584           $st = USER_FLAG_S_PUPAZ;
1585         }
1586         else if (strcasecmp($st_str, "vischio") == 0) {
1587           $st = USER_FLAG_S_VISCH;
1588         }
1589         else {
1590           /* MLANG: "Questo stato non esiste." */
1591           $to_user = sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['statunkn'][$G_lang]);
1592           break;
1593         }
1594
1595         log_main("chatt_send start set");
1596         if ($user->flags_vlt_set($st, USER_FLAG_S_ALL)) {
1597             $update_room = TRUE;
1598         }
1599       } while (0);
1600     } // nick chat command
1601
1602     else { // normal chat line
1603       $is_normchat = TRUE;
1604       if (CHAT_ENABLED && $curtime < ($user->chat_ban + $user->chat_dlt)) {
1605         $only_you = TRUE;
1606         $user->chat_dlt = $user->chat_dlt * 2; 
1607         if ($user->chat_dlt > 120)
1608           $user->chat_dlt = 120; 
1609       }
1610       else if ($user->chat_lst == $msg)
1611         $only_you = TRUE;
1612       else if (CHAT_ENABLED && $curtime - $user->chattime[($user->chat_cur + 1) % CHAT_N] < CHAT_ILL_TIME) {
1613         $user->chat_ban = $curtime;
1614         $user->chat_dlt = 5;
1615         $only_you = TRUE;
1616       }
1617       else {
1618         $user->chat_ban = 0;
1619         $user->chat_dlt = 0;
1620       }
1621
1622       if ($only_you) {
1623           $to_user = sprintf('chatt_sub("%s", [%d, %d, "%s"],"%s");', $dt, $user->flags, $user->flags_vlt, xcape($user->name), xcape("== chat ban =="));
1624       }
1625       else {
1626           $to_user = sprintf('chatt_sub("%s", [%d, %d, "%s"],"%s");', $dt, $user->flags, $user->flags_vlt, xcape($user->name), xcape($msg));
1627         // temporary silentiation for troll (will became array check)
1628         // if (strcasecmp($user->name,'JackRokka') != 0 && $user->sess != '47ea653f602e8')
1629         $to_room = $to_user;
1630       }
1631
1632       log_legal($curtime, $user->ip, $user,
1633                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$msg);
1634       
1635       $user->chat_lst = "$msg";
1636       $user->chattime[$user->chat_cur % CHAT_N] = $curtime;
1637       $user->chat_cur++;
1638     }
1639
1640     if ($to_all) {
1641       $to_room = $to_all;
1642       $to_tabl = $to_all;
1643     }
1644
1645     //
1646     //  Output to clients
1647     //
1648
1649     if ($to_user != FALSE) {
1650       $user->comm[$user->step % COMM_N] =  "gst.st = ".($user->step+1)."; ";
1651       $user->comm[$user->step % COMM_N] .= $to_user;
1652       $user->step_inc();
1653     }
1654
1655     if ($to_room != FALSE) {
1656       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1657         $user_cur = $this->user[$i];
1658         if ($target != "" && $user_cur->name != $target)
1659           continue;
1660         if ($user_cur->sess == '' || $user_cur->stat == 'table' || $user->idx_get() == $i)
1661           continue;
1662         
1663         if ($is_normchat == TRUE) {
1664           // use MAP_AUTH to check if auth or isolation
1665           if ($user_cur->flags & USER_FLAG_MAP_AUTH) {
1666             if (($user->flags & USER_FLAG_AUTH) == 0) {
1667               continue;
1668             }
1669           }
1670         }
1671         /*
1672         else if ($is_ticker) {
1673           if (($user_cur->flags & USER_FLAG_MAP_AUTH) == USER_FLAG_ISOLAUTH) {
1674             if ($user->table >= TABLES_AUTH_N)
1675               continue;
1676           }
1677         }
1678         */
1679         $user_cur->comm[$user_cur->step % COMM_N] =  "gst.st = ".($user_cur->step+1)."; ";
1680         $user_cur->comm[$user_cur->step % COMM_N] .= $to_room; 
1681         $user_cur->step_inc();
1682       }
1683     }
1684     
1685     if ($to_tabl) {
1686         // FIXME BRISK4: include for each kind of table
1687         require_once("${G_base}briskin5/Obj/briskin5.phh");
1688         // Before all align times with table timeout
1689         for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1690             if (isset($this->match[$table_idx])) {
1691                 $bri = $this->match[$table_idx];
1692
1693                 $bri_table = $bri->table[0];
1694                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
1695                     // stat must be "table" by definition
1696                     $bri_user = $bri->user[$i];
1697               
1698                     if ($target != "" && $bri_user->name != $target)
1699                         continue;
1700                     log_main("writa: ".$user_mesg);
1701                     $bri_user->comm[$bri_user->step % COMM_N] = "gst.st = ".($bri_user->step+1)."; ";
1702                     $bri_user->comm[$bri_user->step % COMM_N] .= $to_tabl;
1703                     $bri_user->step_inc();
1704                 }
1705             } // if (isset($this->match
1706         } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1707     } // if ($to_tabl == true ...
1708
1709     if ($update_room) {
1710       if ($user->stat == 'room' && $user->subst == 'standup') {
1711         $this->standup_update($user);
1712       }
1713       else if ($user->stat == 'room' && $user->subst == 'sitdown') {
1714         log_main("chatt_send pre table update");
1715         $this->table_update($user);
1716         log_main("chatt_send post table update");
1717       }
1718     } // if ($update_room ...
1719
1720     return;
1721   } // function chatt_send( ...
1722
1723   function get_user($sess, &$idx)
1724   {
1725     GLOBAL $PHP_SELF;
1726
1727     if (validate_sess($sess)) {
1728       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1729         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1730           // find it
1731           $idx = $i;
1732           $ret = $this->user[$i];
1733           return ($ret);
1734         }
1735       }
1736       log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1737       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1738       // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1739     }
1740     else {
1741       log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
1742     }
1743
1744     return (FALSE);
1745   }
1746
1747   /*
1748    * function add_user(&$room, &$sess, &$idx, $name, $pass, $ip)
1749    *
1750    * RETURN VALUE:
1751    *   if ($idx >  -1    && ret == FALSE)  =>  duplicated nick
1752    *   if ($idx == -2    && ret == FALSE)  =>  invalid name
1753    *   if ($idx == -3    && ret == FALSE)  =>  wrong password
1754    *   if ($idx == -1    && ret == FALSE)  =>  no space left
1755    *   if ($idx ==  0    && ret == user)   =>  SUCCESS
1756    *   if ($idx == -$idx && ret == user)   =>  SUCCESS (but the login exists in the auth db)
1757    */
1758
1759   function add_user(&$sess, &$idx, $name, $pass, $ip, $cookie)
1760   {
1761     GLOBAL $G_base;
1762
1763     $idx = 0;
1764
1765     $authenticate = FALSE;
1766     $user_type    = 0;
1767     $login_exists = FALSE;
1768     $ghost = -1;
1769     $ghost_auth = FALSE;
1770     $idx = -1;
1771     $idfree = -1;
1772     $code = FALSE;
1773
1774     if (($name_new = validate_name($name)) == FALSE) {
1775       $idx = -2;
1776       return (FALSE);
1777     }
1778
1779     log_auth("XXX", sprintf("ARRIVA: [%s] pass:[%s]", $sess, ($pass == FALSE ? "FALSE" : $pass)));
1780     if (validate_sess($sess) == FALSE) 
1781       $sess = "";
1782
1783     /* if pass != FALSE verify the login with pass */
1784     log_auth("XXX", "auth1");
1785
1786     if (($bdb = BriskDB::create()) != FALSE) {
1787         $bdb->users_load();
1788         if ($pass != FALSE) { // TODO: here add a method to $bdb to check if the db is available.
1789             log_auth("XXX", "auth2");
1790             $authenticate = $bdb->login_verify($name_new, $pass, $code);
1791             log_auth("XXX", "authenticate: ".($authenticate != FALSE ? "TRUE" : "FALSE"));
1792             
1793             if ($authenticate != FALSE) {
1794                 $user_type = $authenticate->type_get();
1795             }
1796             else {
1797                 $idx = -3;
1798                 return (FALSE);
1799             }
1800         }
1801         else {
1802             $login_exists =  $bdb->login_exists($name_new);
1803         }
1804     }
1805     else {
1806         // if db is down, send a warning and verify only current users
1807         // no actions at this moment
1808     }
1809     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1810       /* free user ? */
1811       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1812         if ($idx == -1)
1813           $idx = $i;
1814       }
1815       if ($idfree == -1 && strcmp($this->user[$i]->sess, "") == 0) {
1816         $idfree = $i;
1817         continue; // NOTE: CHECK IT !!
1818       }
1819       if (strcasecmp($this->user[$i]->name, $name_new) == 0) {
1820           if ($authenticate != FALSE) {
1821               $ghost = $i;
1822               $ghost_auth = ($this->user[$i]->flags & USER_FLAG_AUTH);
1823           }
1824           else {
1825               $idx = $i;
1826               break;
1827           }
1828       }
1829     }
1830     if ($idx == -1)
1831       $idx = $idfree;
1832
1833     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1834
1835     /* there is another user logged with your account and you and him have authenticated => new user
1836        get the session of the old user */
1837     if ($ghost > -1 && $ghost_auth && ($authenticate != FALSE)) {
1838       /* swap session */
1839
1840       $ghost_user = $this->user[$ghost];
1841       $curtime = time();
1842       $ghost_user->comm[$ghost_user->step % COMM_N] = "";
1843       $ghost_user->step_inc();
1844       if ($sess == "") {
1845         $sess = uniqid(""); 
1846         $ghost_user->sess = $sess;
1847       }
1848       else {
1849         $ghost_user->sess = $sess;
1850       }
1851       
1852       // If user at the table we need to update the table data too
1853       $table_idx = $ghost_user->table;
1854       if ($ghost_user->stat == "table" && $this->table[$table_idx]->player_n == PLAYERS_N) {
1855           require_once("${G_base}briskin5/Obj/briskin5.phh");
1856           if (isset($this->match[$table_idx])) {
1857               $bri = $this->match[$table_idx];
1858
1859               if ($bri->the_end != TRUE) {
1860                   $bri->user[$ghost_user->table_pos]->comm[$bri->user[$ghost_user->table_pos]->step % COMM_N] = "";
1861                   $bri->user[$ghost_user->table_pos]->step_inc();
1862                   $bri->user[$ghost_user->table_pos]->sess = $sess;
1863               }
1864           }
1865       }
1866
1867       $idx = $ghost;
1868       return ($this->user[$ghost]);
1869     }
1870     else if ($idx != -1 && $i == MAX_PLAYERS) {
1871       /* SUCCESS */
1872       $curtime = time();
1873       if ($sess == "") {
1874         $sess = uniqid("");
1875         $this->user[$idx]->sess = $sess;
1876       }
1877       else {
1878         $this->user[$idx]->sess = $sess;
1879       }
1880       $this->user[$idx]->name = $name_new; // OK - add new user
1881       $this->user[$idx]->stat_set("room");
1882       $this->user[$idx]->step_set(0);
1883       while (array_pop($this->user[$idx]->comm) != NULL);
1884       $this->user[$idx]->subst = "standup";
1885       $this->user[$idx]->lacc =   $curtime;
1886       $this->user[$idx]->laccwr = $curtime;
1887       $this->user[$idx]->bantime = 0;
1888       $this->user[$idx]->ip = $ip;
1889
1890       $this->user[$idx]->rec = $authenticate;
1891       fprintf(STDERR, "MOP: [%s]\n", $authenticate->supp_comp);
1892       $this->user[$idx]->flags = $user_type;
1893       $this->user[$idx]->flags |= ($authenticate != FALSE ? USER_FLAG_AUTH : 0x00);
1894       $this->user[$idx]->flags |= ( ($pass != FALSE && $bdb == FALSE) ? USER_FLAG_DBFAILED : 0x00);
1895       log_auth("XXX", sprintf("FLAGS: [%x]", $this->user[$idx]->flags));
1896       
1897       if ($authenticate != FALSE) {
1898           $this->user[$idx]->code = $authenticate->code_get();
1899           if (0 == 1) {
1900               // all this part is included in the db server
1901               $this->user[$idx]->flags |= USER_FLAG_LISTAUTH;
1902
1903               if (isset($cookie['CO_list'])) {
1904                   fprintf(STDERR, "QQ: %s CO_list: [%s]\n", __FUNCTION__, $cookie['CO_list']);
1905                   if (strcmp($cookie['CO_list'], "auth") == 0) {
1906                       $this->user[$idx]->flags &= ~USER_FLAG_MAP_AUTH;
1907                       $this->user[$idx]->flags |= USER_FLAG_LISTAUTH;
1908                   }
1909                   if (strcmp($cookie['CO_list'], "isolation") == 0) {
1910                       $this->user[$idx]->flags &= ~USER_FLAG_MAP_AUTH;
1911                       $this->user[$idx]->flags |= USER_FLAG_ISOLAUTH;
1912                   }
1913                   else {
1914                       $this->user[$idx]->flags &= ~USER_FLAG_MAP_AUTH;
1915                   }
1916               }
1917           }
1918           else {
1919               fprintf(STDERR, "QQ: CO_list not set flags: %x\n", __FUNCTION__, $this->user[$idx]->flags);
1920           }
1921       }
1922       fprintf(STDERR, "QQ %s: flag %x\n", __FUNCTION__, $this->user[$idx]->flags);
1923       if ($ghost > -1) {
1924         log_main("ghost: rename!");
1925         $ghost_user = $this->user[$ghost];
1926
1927         if ($ghost_auth == FALSE) {
1928           for ($sfx = 1 ; $sfx <= MAX_PLAYERS ; $sfx++) {
1929             $ghostname = 'ghost'.$sfx;
1930             for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1931               if (strcmp("", $this->user[$i]->sess) == 0) 
1932                 continue;
1933               
1934               if (strcasecmp($this->user[$i]->name, $ghostname) == 0) {
1935                 $ghostname = '';
1936                 break;
1937               }
1938             }
1939             if ($ghostname != '')
1940               break;
1941           }
1942           
1943           $ghost_user->name = $ghostname;
1944           
1945           if ($ghost_user->stat == 'room' && $ghost_user->subst == 'standup') {
1946             $this->standup_update($ghost_user);
1947           }
1948           else {
1949             log_main("chatt_send pre table update");
1950             $this->table_update($ghost_user);
1951           log_main("chatt_send post table update");
1952           }
1953         } // if ($ghost_auth == FALSE
1954         else {
1955           // FIXME: cacciare il vecchio utente room && table (if needed)
1956           $ghost_user->the_end = TRUE;
1957           $ghost_user->lacc = 0;
1958           $this->garbage_manager(TRUE);
1959         }
1960       } //  if ($ghost > -1) {
1961
1962       $real_idx = $idx;
1963       if ($login_exists)
1964         $idx = -($idx + 1);
1965       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));
1966
1967       $ret = $this->user[$real_idx];
1968       return ($ret);
1969     }
1970
1971     return (FALSE);
1972   }
1973   
1974   function standup_update($user)
1975   {
1976     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1977       $user_cur = $this->user[$i];
1978       if ($user_cur->sess == '')
1979         continue;
1980
1981       log_main("STANDUP START: ".$user_cur->stat);
1982       
1983       if ($user_cur->stat == 'room') {
1984         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".$this->standup_content($user_cur);
1985         if ($user->idx_get() == $i) {
1986           $user_cur->comm[$user_cur->step % COMM_N] .= $user->myname_innerHTML();
1987         }
1988         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1989         
1990         $user_cur->step_inc();
1991       }
1992     }
1993   }
1994
1995   // Static functions
1996   static function create($crystal_filename)
1997   {
1998       if (($room_ser = @file_get_contents($crystal_filename)) == FALSE ||
1999           ($room = unserialize($room_ser)) == FALSE) {
2000           fprintf(STDERR, "NEW ROOM\n");
2001           $room = new Room($crystal_filename);
2002       }
2003       else {
2004           fprintf(STDERR, "ROOM FROM FILE\n");
2005           rename($crystal_filename, $crystal_filename.".old");
2006       }
2007
2008     return $room;
2009   }
2010   
2011   
2012   function load_data() 
2013   {
2014     GLOBAL $sess;
2015
2016     do {
2017       if (($tok = @ftok(FTOK_PATH."/main", "C")) == -1) {
2018         log_main("ftok failed");
2019         break;
2020       }
2021     
2022       if (($shm_sz = sharedmem_sz($tok)) == -1) {
2023         log_main("shmop_open failed");
2024       }
2025         
2026       if ($shm_sz == -1)
2027         $shm_sz = SHM_DIMS_MIN;
2028
2029       if ($shm = shm_attach($tok, $shm_sz)) {
2030           $room = @shm_get_var($shm, $tok); // CHECKED BELOW
2031           
2032           log_only("bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
2033           if (isset($room)) 
2034               log_only("bri count ".count($room));
2035           
2036           if ($room == FALSE) {
2037               log_only("INIT MAIN DATA");
2038               shm_detach($shm);
2039               
2040               $room = Room::create();
2041               
2042               log_shme("Room::create");
2043
2044               if (Room::save_data($room) == FALSE)
2045                   return FALSE;
2046
2047               return $room;
2048           }
2049           $room->shm_sz = $shm_sz;
2050           
2051           shm_detach($shm);
2052
2053           for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2054               if (($room->user[$i] = User::load_data($i, FALSE)) == FALSE) {
2055                   log_crit("User::load_data failed");
2056                   break;
2057               }
2058           }
2059           if ($i < MAX_PLAYERS) {
2060               break;
2061           }
2062       }
2063       
2064       //  
2065       // SHSPLIT: load users from the shared memory
2066       //
2067       return ($room);
2068     } while (0);
2069     
2070     return (FALSE);
2071   }
2072   
2073
2074   function save_data_orig($room) 
2075   {
2076     GLOBAL $sess;
2077     
2078     $shm =   FALSE;
2079     
2080     // var_dump($room);
2081     
2082     if (($tok = @ftok(FTOK_PATH."/main", "C")) == -1) 
2083       return (FALSE);
2084     
2085     while ($room->shm_sz < SHM_DIMS_MAX) {
2086       if (($shm = shm_attach($tok, $room->shm_sz)) == FALSE)
2087         break;
2088       
2089       // log_only("PUT_VAR DI ".strlen(serialize($room)));
2090       if (@shm_put_var($shm, $tok, $room) != FALSE) {
2091         shm_detach($shm);
2092         return (TRUE);
2093       }
2094       if (shm_remove($shm) === FALSE) {
2095         log_only("REMOVE FALLITA");
2096         break;
2097       }
2098       shm_detach($shm);
2099       $room->shm_sz += SHM_DIMS_DLT;
2100     } 
2101
2102     if ($shm)
2103       shm_detach($shm);
2104     
2105     return (FALSE);
2106   }
2107   function dump_data()
2108   {
2109       $room_ser = serialize($this);
2110       $room_ser_len = mb_strlen($room_ser, "ASCII");
2111       if (file_put_contents($this->crystal_filename, $room_ser) == $room_ser_len) {
2112           return (TRUE);
2113       }
2114       
2115       return (FALSE);
2116   }
2117
2118   function save_data($room) 
2119   {
2120       GLOBAL $sess;
2121     
2122       $ret =   FALSE;
2123       $shm =   FALSE;
2124     
2125       if (($tok = @ftok(FTOK_PATH."/main", "C")) == -1) 
2126           return (FALSE);
2127     
2128       // SHSPLIT: before save the $room you must save users, 
2129       //          detach from main struct and (then) reattach
2130       $user_park = array();
2131       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2132           $user_park[$i]  = $room->user[$i];
2133           $room->user[$i] = FALSE;
2134       }
2135
2136       while ($room->shm_sz < SHM_DIMS_MAX) {
2137           if (($shm = shm_attach($tok, $room->shm_sz)) == FALSE)
2138               break;
2139       
2140           // log_only("PUT_VAR DI ".strlen(serialize($room)));
2141           if (@shm_put_var($shm, $tok, $room) != FALSE) {
2142               log_shme("Room::save_data");
2143               $ret = TRUE;
2144               break;
2145           }
2146           if (shm_remove($shm) === FALSE) {
2147               log_only("REMOVE FALLITA");
2148               break;
2149           }
2150           shm_detach($shm);
2151           $room->shm_sz += SHM_DIMS_DLT;
2152       } 
2153
2154       if ($shm)
2155           shm_detach($shm);
2156     
2157       // SHSPLIT: reattach users to the room class
2158       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2159           User::save_data($user_park[$i], $i);
2160           $room->user[$i] = $user_park[$i];
2161       }
2162       log_load("FINISH: ".($ret == TRUE ? "TRUE" : "FALSE"));
2163
2164       return ($ret);
2165   }
2166
2167   static function lock_data($is_exclusive)
2168   {
2169       if (($res = file_lock(FTOK_PATH."/main", $is_exclusive)) != FALSE) {
2170           self::$delta_t = microtime(TRUE);
2171           log_lock("LOCK   room         [".self::$delta_t."]");
2172           
2173           return ($res);
2174       }
2175
2176       return (FALSE);
2177   }
2178   
2179   static function unlock_data($res)
2180   {
2181     GLOBAL $sess; 
2182     
2183     log_lock("UNLOCK room         [".(microtime(TRUE) - (self::$delta_t))."]");
2184
2185     file_unlock($res);
2186   }
2187
2188
2189   function standup_content($user)
2190   {
2191     $ret = "";
2192     $content = "";
2193     
2194     if ($user->stat != 'room')
2195       return;
2196     
2197     for ($i = 0 , $ct = 0 ; $ct < 4 && $i < MAX_PLAYERS ; $i++) {
2198       if ($this->user[$i]->sess == "" || $this->user[$i]->stat != "room" || $this->user[$i]->name == "")
2199         continue;
2200       $ct++;
2201     }
2202     
2203     // $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
2204     
2205     $content = ' j_stand_cont( [ ';
2206
2207     $user_cur_id = $user->idx_get();
2208     for ($i = 0 , $ct = 0 ; $i < MAX_PLAYERS ; $i++) {
2209         if ($this->user[$i]->sess == "" || $this->user[$i]->stat != "room" || $this->user[$i]->name == "")
2210             continue;
2211
2212         $flags = $this->user[$i]->flags;
2213         $flags_vlt = $this->user[$i]->flags_vlt;
2214
2215         // sql record exists AND last donate > 2013-01-01
2216         if ($this->user[$i]->is_supp_custom()) {
2217             $supp_comp_s = sprintf(', "%s"', $this->user[$i]->rec->supp_comp);
2218         }
2219         else {
2220             $supp_comp_s = '';
2221         }
2222
2223         if ($this->user[$i]->subst == "standup") {
2224             if ($user_cur_id == $i) {
2225                 $flags |= 1;
2226             }
2227             $content .= sprintf('%s[ %d, %d, "%s"%s ]',($ct > 0 ? ', ' : ''),
2228                                 $flags, $flags_vlt,
2229                                 xcape($this->user[$i]->name), $supp_comp_s);
2230             $ct++;
2231         }
2232     }
2233     $content .= ' ]);';
2234     
2235     return ($content);
2236   }
2237   
2238   function table_content($user, $table_idx)
2239   {
2240     $content = "";
2241     $ret = "";
2242     // TODO
2243     //
2244     //   Si possono usare i dati nella classe table
2245     //
2246     
2247     $sess = $user->sess;
2248     $table = $this->table[$table_idx];
2249     
2250     if ($user->stat != 'room')
2251       return;
2252     
2253     $user_cur_id = $user->idx_get();
2254     $content = "[ ";
2255     for ($i = 0 ; $i < $table->player_n ; $i++) {
2256         $user_cur = $this->user[$table->player[$i]];
2257         
2258         $flags = $user_cur->flags;
2259         $flags_vlt = $user_cur->flags_vlt;
2260
2261         if ($user_cur_id == $table->player[$i])
2262             $flags |= 1;
2263         
2264         log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2265         if ($user_cur->is_supp_custom())
2266             $supp_comp_s = sprintf(', "%s"', $user_cur->rec->supp_comp);
2267         else
2268             $supp_comp_s = '';
2269
2270         $content .= sprintf('%s[ %d, %d, "%s"%s ]',($i == 0 ? '' : ', '),
2271                             $flags, $flags_vlt,
2272                             xcape($user_cur->name), $supp_comp_s);
2273     }
2274
2275     $content .= ' ]';
2276
2277     $ret .= sprintf('j_tab_cont(%d, %s);', $table_idx, $content);
2278     
2279     return ($ret);
2280   }
2281
2282   function request_mgr(&$s_a_p, $header, &$header_out, &$new_socket, $path, $addr, $get, $post, $cookie)
2283   {
2284       GLOBAL $G_black_list;
2285
2286       printf("NEW_SOCKET (root): %d PATH [%s]\n", intval($new_socket), $path);
2287
2288       $enc = get_encoding($header);
2289       if (isset($header['User-Agent'])) {
2290           if (strstr($header['User-Agent'], "MSIE")) {
2291               $transp_type = "htmlfile";
2292           }
2293           else {
2294               $transp_type = "xhr";
2295           }
2296       }
2297       else {
2298           $transp_type = "iframe";
2299       }
2300       force_no_cache($header_out);
2301
2302       switch ($path) {
2303       case "":
2304       case "index.php":
2305           ob_start();
2306           index_main($this, $transp_type, $header_out, $addr, $get, $post, $cookie);
2307           $content = ob_get_contents();
2308           ob_end_clean();
2309
2310           // fprintf(STDERR, "\n\nCONTENT [%s]\n\n", $content);
2311           $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2312           return TRUE;
2313
2314           break;
2315       case "index_wr.php":
2316           //
2317           // Enhance required: in the POST case, after the header you must get content
2318           //                   from the socket, waiting if necessary
2319           //
2320
2321           fprintf(STDERR, "\n\nDENTRO QUI\n\n");
2322           ob_start();
2323           index_wr_main($this, $addr, $get, $post, $cookie);
2324           $content = ob_get_contents();
2325           ob_end_clean();
2326           
2327           $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2328           return TRUE;
2329
2330           break;
2331       case "index_rd_ifra.php":
2332           do {
2333               if (!isset($cookie['sess'])
2334                   || (($user = $this->get_user($cookie['sess'], $idx)) == FALSE)) {
2335                   if (($transp  = gpcs_var('transp', $get, $post, $cookie)) === FALSE)
2336                       $transp = "iframe";
2337                   
2338                   $content = User::stream_fini($transp, $s_a_p->rndstr, TRUE);
2339
2340                   $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2341                   return TRUE;
2342
2343                   break;
2344               }
2345               // close a previous opened index_read_ifra socket, if exists
2346               if (($prev = $user->rd_socket_get()) != NULL) {
2347                   $s_a_p->socks_unset($user->rd_socket_get());
2348                   fclose($user->rd_socket_get());
2349                   printf("CLOSE AND OPEN AGAIN ON IFRA2\n");
2350                   $user->rd_socket_set(NULL);
2351               }
2352
2353               $content = "";
2354               $user->stream_init($s_a_p->rndstr, $enc, $header_out, $content, $get, $post, $cookie);
2355               
2356               $response = headers_render($header_out, -1).chunked_content($user->rd_zls_get(), $content);
2357               $response_l = mb_strlen($response, "ASCII");
2358               
2359               $wret = @fwrite($new_socket, $response, $response_l);
2360               if ($wret < $response_l) {
2361                   printf("TROUBLES WITH FWRITE: %d\n", $wret);
2362                   $user->rd_cache_set(mb_substr($content, $wret, $response_l - $wret, "ASCII"));
2363               }
2364               else {
2365                   $user->rd_cache_set("");
2366               }
2367               fflush($new_socket);
2368               
2369               
2370               $s_a_p->socks_set($new_socket, $user, NULL);
2371               $user->rd_socket_set($new_socket);
2372               printf(" - qui ci siamo - ");
2373               return TRUE;
2374           } while (FALSE);
2375           
2376           return FALSE;
2377           break;
2378       case 'test.php':
2379           if (!(BRISK_DEBUG & DBG_ENGI))
2380               return (FALSE);
2381           fprintf(STDERR, "TEST.PHP running\n");
2382           if (isset($post['data'])) {
2383               $content = $post['data'];
2384           }
2385           else {
2386               $content = "NO DATA AVAILABLE";
2387           }
2388           $header_out['Content-Type'] = 'text/plain';
2389           $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2390           return TRUE;
2391           break;
2392       default:
2393           /* FAR TODO: move all into an array of registered sub-apps */
2394           $subs = "briskin5/";
2395           $subs_l = strlen($subs);
2396           if (!strncmp($path, $subs, $subs_l)) {
2397               $ret = Bin5::request_mgr(&$s_a_p, $header, &$header_out, &$new_socket, substr($path, $subs_l) , $addr, $get, $post, $cookie);
2398               return ($ret);
2399           }
2400           break;
2401       }
2402
2403       return (FALSE);
2404   }
2405
2406   function match_add($idx, $match)
2407   {
2408       $this->match[$idx] = $match;
2409   }
2410
2411   function match_del($idx)
2412   {
2413       unset($this->match[$idx]);
2414   }
2415
2416   function match_get($idx, $token)
2417   {
2418       if (isset($this->match[$idx])) {
2419           if (   $token == NULL 
2420               || $token == $this->match[$idx]->table_token) {
2421               return ($this->match[$idx]);
2422           }
2423       }
2424       return NULL;
2425   }
2426
2427 } // end class Room
2428
2429 function make_seed()
2430 {
2431   list($usec, $sec) = explode(' ', microtime());
2432   return (float) $sec + ((float) $usec * 100000);
2433 }
2434
2435 function btrace_line($ar)
2436 {
2437     GLOBAL $G_btrace_pref_sub;
2438
2439     $ret = "";
2440     for ($i = 0 ; $i < count($ar) ; $i++) {
2441         $with_class = isset($ar[$i]['class']);
2442         $with_file  = isset($ar[$i]['file']);
2443         $ret .= sprintf("%s%s%s (%s:%d)", ($i == 0 ? "" : ", "), 
2444                         ($with_class ?  $ar[$i]['class'].$ar[$i]['type'] : ""), 
2445                         $ar[$i]['function'], ($with_file ? str_replace($G_btrace_pref_sub, "", $ar[$i]['file']) : ""), 
2446                         ($with_file ? $ar[$i]['line'] : ""));
2447     }
2448     
2449     return ($ret);
2450 }
2451
2452 function trace_ftok($id, $add)
2453 {
2454     // NOTE: without space to use sed to substitute "= @ftok("  with "= @ftok("
2455     $tok=@ftok($id, $add);
2456
2457     log_shme($tok.": ".$id." + ".$add);
2458
2459     return ($tok);
2460 }
2461
2462 function log_mop($step, $log)
2463 {
2464     GLOBAL $sess, $PHP_SELF;
2465     
2466     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LMOP) == 0)
2467         return;
2468     
2469     if (isset($sess) == FALSE)
2470         $ssess = "XXXX";
2471     else
2472         $ssess = $sess;
2473     
2474     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LMOP) == 0)
2475         return;
2476     
2477     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2478         $btrace = btrace_line(debug_backtrace());
2479     else
2480         $btrace = "";
2481     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2482         fwrite($fp, sprintf("LMOP: [%f] [%05d] [%s] [%s]\n", gettimeofday(TRUE), $step, $log, $btrace));
2483         fclose($fp);
2484     }
2485 }
2486
2487
2488 function log_only2($log)
2489 {
2490     GLOBAL $sess, $PHP_SELF;
2491     
2492     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONL2) == 0)
2493         return;
2494     
2495     if (isset($sess) == FALSE)
2496         $ssess = "XXXX";
2497     else
2498         $ssess = $sess;
2499     
2500     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONL2) == 0)
2501         return;
2502     
2503     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2504         $btrace = btrace_line(debug_backtrace());
2505     else
2506         $btrace = "";
2507     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2508         fwrite($fp, sprintf("ONL2: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2509         fclose($fp);
2510     }
2511 }
2512
2513 function log_crit($log)
2514 {
2515     GLOBAL $sess, $PHP_SELF;
2516     
2517     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CRIT) == 0)
2518         return;
2519     
2520     if (isset($sess) == FALSE)
2521         $ssess = "XXXX";
2522     else
2523         $ssess = $sess;
2524     
2525     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CRIT) == 0)
2526         return;
2527     
2528     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2529         $btrace = btrace_line(debug_backtrace());
2530     else
2531         $btrace = "";
2532     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2533         fwrite($fp, sprintf("CRIT: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2534         fclose($fp);
2535     }
2536 }
2537
2538 function log_only($log)
2539 {
2540     GLOBAL $sess, $PHP_SELF;
2541     
2542     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONLY) == 0)
2543         return;
2544     
2545     if (isset($sess) == FALSE)
2546         $ssess = "XXXX";
2547     else
2548         $ssess = $sess;
2549     
2550     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONLY) == 0)
2551         return;
2552     
2553     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2554         $btrace = btrace_line(debug_backtrace());
2555     else
2556         $btrace = "";
2557     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2558         fwrite($fp, sprintf("ONLY: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2559         fclose($fp);
2560     }
2561 }
2562
2563 function log_main($log)
2564 {
2565     GLOBAL $sess, $PHP_SELF;
2566     
2567     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_MAIN) == 0)
2568         return;
2569     
2570     if (isset($sess) == FALSE)
2571         $ssess = "XXXX";
2572     else
2573         $ssess = $sess;
2574     
2575     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_MAIN) == 0)
2576         return;
2577     
2578     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2579         $btrace = btrace_line(debug_backtrace());
2580     else
2581         $btrace = "";
2582     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2583         fwrite($fp, sprintf("MAIN: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2584         fclose($fp);
2585     }
2586 }
2587
2588 function log_rd($log)
2589 {
2590     GLOBAL $sess, $PHP_SELF;
2591     
2592     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_READ) == 0)
2593         return;
2594     
2595     if (isset($sess) == FALSE)
2596         $ssess = "XXXX";
2597     else
2598         $ssess = $sess;
2599     
2600     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_READ) == 0)
2601         return;
2602
2603     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2604         $btrace = btrace_line(debug_backtrace());
2605     else
2606         $btrace = "";    
2607     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2608         fwrite($fp, sprintf("READ: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2609         fclose($fp);
2610     }
2611 }
2612
2613 function log_rd2($log)
2614 {
2615     GLOBAL $sess, $PHP_SELF;
2616     
2617     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_REA2) == 0)
2618         return;
2619     
2620     if (isset($sess) == FALSE)
2621         $ssess = "XXXX";
2622     else
2623         $ssess = $sess;
2624     
2625     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_REA2) == 0)
2626         return;
2627     
2628     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2629         $btrace = btrace_line(debug_backtrace());
2630     else
2631         $btrace = "";
2632     
2633     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2634         fwrite($fp, sprintf("REA2: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2635         fclose($fp);
2636     }
2637 }
2638
2639 function log_send($log)
2640 {
2641     GLOBAL $sess, $PHP_SELF;
2642     
2643     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SEND) == 0)
2644         return;
2645     
2646     if (isset($sess) == FALSE)
2647         $ssess = "XXXX";
2648     else
2649         $ssess = $sess;
2650     
2651     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SEND) == 0)
2652         return;
2653
2654     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)    
2655         $btrace = btrace_line(debug_backtrace());
2656     else
2657         $btrace = "";
2658     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2659         fwrite($fp, sprintf("SEND: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2660         fclose($fp);
2661     }
2662 }
2663
2664 function log_lock($log)
2665 {
2666     GLOBAL $sess, $PHP_SELF;
2667     
2668     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOCK) == 0)
2669         return;
2670     
2671     if (isset($sess) == FALSE)
2672         $ssess = "XXXX";
2673     else
2674         $ssess = $sess;
2675     
2676     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOCK) == 0)
2677         return;
2678     
2679     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2680         $btrace = btrace_line(debug_backtrace());
2681     else
2682         $btrace = "";
2683     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2684         fwrite($fp, sprintf("LOCK: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2685         fclose($fp);
2686     }
2687 }
2688
2689 function log_wr($log)
2690 {
2691     GLOBAL $sess, $PHP_SELF;
2692     
2693     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_WRIT) == 0)
2694         return;
2695     
2696     if (isset($sess) == FALSE)
2697         $ssess = "XXXX";
2698     else
2699         $ssess = $sess;
2700     
2701     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_WRIT) == 0)
2702         return;
2703     
2704     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2705         $btrace = btrace_line(debug_backtrace());
2706     else
2707         $btrace = "";
2708     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2709         fwrite($fp, sprintf("WRIT: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2710         fclose($fp);
2711     }
2712 }
2713
2714 function log_load($log)
2715 {
2716     GLOBAL $sess, $PHP_SELF;
2717     
2718     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOAD) == 0)
2719         return;
2720     
2721     if (isset($sess) == FALSE)
2722         $ssess = "XXXX";
2723     else
2724         $ssess = $sess;
2725     
2726     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOAD) == 0)
2727         return;
2728     
2729     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2730         $btrace = btrace_line(debug_backtrace());
2731     else
2732         $btrace = "";
2733     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2734         fwrite($fp, sprintf("LOAD: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2735         fclose($fp);
2736     }
2737 }
2738
2739 function log_auth($sess, $log)
2740 {
2741     GLOBAL $PHP_SELF;
2742
2743     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_AUTH) == 0)
2744         return;
2745     
2746     if (( (BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_AUTH) == 0)
2747         return;
2748     
2749     if ((BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2750         $btrace = btrace_line(debug_backtrace());
2751     else
2752         $btrace = "";
2753     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2754         fwrite($fp, sprintf("LOAD: [%s] [%d] [%s] [%s]\n", $sess, time(), $log, $btrace));
2755         fclose($fp);
2756     }
2757 }
2758
2759 function log_shme($log)
2760 {
2761     GLOBAL $sess, $PHP_SELF;
2762     
2763     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SHME) == 0)
2764         return;
2765     
2766     if (isset($sess) == FALSE)
2767         $ssess = "XXXX";
2768     else
2769         $ssess = $sess;
2770     
2771     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SHME) == 0)
2772         return;
2773     
2774     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2775         $btrace = btrace_line(debug_backtrace());
2776     else
2777         $btrace = "";
2778     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2779         fwrite($fp, sprintf("SHME: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2780         fclose($fp);
2781     }
2782 }
2783
2784
2785
2786 // function log_legal($curtime, $sess, $name, $where, $mesg)
2787 function log_legal($curtime, $addr, $user, $where, $mesg)
2788 {
2789
2790   if (($fp = @fopen(LEGAL_PATH."/legal.log", 'a')) != FALSE) {
2791     /* Unix time | session | nickname | IP | where was | mesg */
2792     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
2793                         ($user->flags & USER_FLAG_AUTH ? 'A' : 'N'),
2794                         $user->name, $addr, $where , $mesg));
2795     fclose($fp);
2796   }
2797 }
2798
2799 function table_act_content($isstanding, $sitted, $table, $cur_table, $allowed)
2800 {
2801   $ret = "";
2802
2803   if ($isstanding) {
2804     if ($sitted < PLAYERS_N) {
2805       if ($allowed)
2806         $act = 'sit';
2807       else
2808         $act = 'reserved';
2809     }
2810   }
2811   else {
2812     if ($table == $cur_table)
2813       $act = 'wake';
2814     else
2815       $act = 'none';
2816   }
2817
2818   if ($act != '')
2819     $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
2820
2821   return ($ret);
2822 }
2823
2824 function show_notify($text, $tout, $butt, $w, $h)
2825 {
2826   log_main("SHOW_NOTIFY: ".$text);
2827   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
2828 }
2829
2830 function show_notify_ex($text, $tout, $butt, $w, $h, $is_opaque, $block_time)
2831 {
2832   log_main("SHOW_NOTIFY OPAQUE: ".$text);
2833   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);
2834 }
2835
2836
2837 function root_welcome($user)
2838 {
2839   GLOBAL $root_wellarr, $G_lang;
2840   $ret = "";
2841
2842   $curtime = time();
2843   $dt = date("H:i ", $curtime);
2844     
2845   for ($i = 0 ; $i < count($root_wellarr[$G_lang]) ; $i++)
2846     $ret .= sprintf('chatt_sub("%s", [2, 0, "%s"],"%s");', $dt, NICKSERV, str_replace('"', '\"', $root_wellarr[$G_lang][$i]));
2847
2848   return ($ret);
2849 }
2850
2851
2852
2853 function validate_sess($sess) 
2854 {
2855   if (strlen($sess) == SESS_LEN) 
2856     return (TRUE);
2857   else
2858     return (FALSE);
2859 }
2860
2861 function validate_name($name) 
2862 {
2863     $name_new = str_replace(' ', '_', mb_substr(trim($name),0,12, "UTF-8"));
2864
2865   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2866     $c = $name_new[$i];
2867     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2868       return ($name_new);
2869   }
2870
2871   return (FALSE);
2872 }
2873
2874 function playsound($filename)
2875 {
2876   return (sprintf('playsound("flasou", "%s");', $filename));
2877 }
2878
2879 function secstoword($secs)
2880 {
2881   GLOBAL $G_lang;
2882
2883   $ret = "";
2884
2885   $mins = floor($secs / 60);
2886   $secs = $secs % 60;
2887   if ($G_lang == 'en') {
2888     if ($mins > 0) 
2889       $ret = sprintf("%d minute%s%s", $mins, ($mins > 1 ? "s" : ""), ($secs > 0 ? " and " : ""));
2890     
2891     if ($secs > 0)
2892       $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "s" : ""));
2893   }
2894   else {
2895     if ($mins > 0) 
2896       $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
2897     
2898     if ($secs > 0)
2899       $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
2900   }
2901   return ($ret);
2902 }
2903
2904 function sharedmem_sz($tok)
2905 {
2906   if (($shm_id = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
2907     log_main("shmop_open failed");
2908     return (-1);
2909   }
2910   $shm_sz = shmop_size($shm_id);
2911   shmop_close($shm_id);
2912   
2913   // log_main("shm_sz: ".$shm_sz."   SHM_DIMS: ".SHM_DIMS);
2914   return ($shm_sz);
2915 }    
2916
2917 class Warrant {
2918     static $delta_t;
2919
2920   static function lock_data($is_exclusive)
2921   {
2922       if (($res = file_lock(FTOK_PATH."/warrant", $is_exclusive)) != FALSE) {
2923           self::$delta_t = microtime(TRUE);
2924           log_lock("LOCK   warrant      [".self::$delta_t."]");
2925           
2926           return ($res);
2927       }
2928
2929       return (FALSE);
2930   }
2931   
2932   static function unlock_data($res)
2933   {
2934     GLOBAL $sess; 
2935     
2936     log_lock("UNLOCK warrant      [".(microtime(TRUE) - (self::$delta_t))."]");
2937
2938     file_unlock($res);
2939   }
2940 }
2941
2942 class Poll {
2943     static $delta_t;
2944
2945   static function lock_data($is_exclusive)
2946   {
2947       if (($res = file_lock(FTOK_PATH."/poll", $is_exclusive)) != FALSE) {
2948           self::$delta_t = microtime(TRUE);
2949           log_lock("LOCK   poll         [".self::$delta_t."]");
2950           
2951           return ($res);
2952       }
2953
2954       return (FALSE);
2955   }
2956   
2957   static function unlock_data($res)
2958   {
2959     GLOBAL $sess; 
2960     
2961     log_lock("UNLOCK poll         [".(microtime(TRUE) - (self::$delta_t))."]");
2962     
2963     file_unlock($res);
2964   }
2965 }
2966
2967 ?>