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