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