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