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