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