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