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