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