add ip2int and int2ip functions to be able to store on pg IPV4 ip addresses
[brisk.git] / web / Obj / brisk.phh
1 <?php
2 /*
3  *  brisk - brisk.phh
4  *
5  *  Copyright (C) 2006-2014 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', 8);
32 define('TABLES_CERT_N', 4);
33 define('PLAYERS_N', 3);
34 define('MAX_POINTS', 5);
35 define('MAX_PLAYERS', (20 + (PLAYERS_N * TABLES_N)));
36 define('SHM_DIMS_MIN', (50000 + 10000 * TABLES_N + 15000 * MAX_PLAYERS));
37 define('SHM_DIMS_MAX', SHM_DIMS_MIN + 1048576);
38 define('SHM_DIMS_DLT', 65536);
39
40 define('SHM_DIMS_U_MIN', 4096);
41 define('SHM_DIMS_U_MAX', 65536);
42 define('SHM_DIMS_U_DLT', 4096);
43
44 define('COMM_N', 18);
45 define('COMM_GEN_N', 50);
46
47 define('CHAT_N', 3);
48 define('CHAT_ILL_TIME', 6);
49 define('CHAT_ENABLED', TRUE);
50
51 define('SESS_LEN', 13);
52 define('STREAM_TIMEOUT', 60);
53 /* FIXME: move to sac-a-push .phh */
54 /* TIME_RD define the server-side timeout, after half of it a ping request
55    is sent to client, after this time the client is log out */
56 define('EXPIRE_TIME_RD', 180);
57 define('EXPIRE_TIME_SMAMMA', 360);
58 define('EXPIRE_TIME_WAG', 10);
59 define('WAKEUP_TIME', 12);
60 // BAN_TIME da allineare anche in commons.js
61 define('BAN_TIME', 3600);
62 define('GARBAGE_TIMEOUT', 5);
63 define('NICKSERV', "BriskServ");
64
65 define('LOCK_SHARE_MAX', 10000);
66
67 define('DBG_ONL2', 0x000001);
68 define('DBG_ONLY', 0x000002);
69 define('DBG_MAIN', 0x000004);
70 define('DBG_READ', 0x000008);
71 define('DBG_REA2', 0x000010);
72 define('DBG_SEND', 0x000020);
73 define('DBG_LOCK', 0x000040);
74 define('DBG_WRIT', 0x000080);
75 define('DBG_LOAD', 0x000100);
76 define('DBG_AUTH', 0x000200);
77 define('DBG_CRIT', 0x000400);
78 define('DBG_LMOP', 0x000800);
79 define('DBG_TRAC', 0x001000);
80 define('DBG_SHME', 0x002000);
81 define('DBG_ENGI', 0x004000);
82 define('DBG_CDS',  0x008000);
83 define('DBG_STEP', 0x010000);
84 // NOTE: BRISK DEBUG must be a numerical constant, not the result of operations on symbols
85 define('BRISK_DEBUG', 0x0800);
86
87 define('BRISK_SINGLE_DEBUG',0);
88 define('BRISK_SINGLE_SESS', "");
89 define('DEBUGGING', "no-debugging");
90
91 require_once("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
92 require_once("${G_base}Obj/ipclass.phh");
93
94 $mlang_brisk = array( 'btn_backstand'=> array( 'it' => 'torna in piedi',
95                                                'en' => 'back standing' ),
96                       'btn_close' => array( 'it' => 'chiudi',
97                                             'en' => 'close'),
98
99                       'tit_all' => array( 'it' => 'tutti',
100                                           'en' => 'all' ),
101
102                       'tabtout_a'=> array( 'it' => '<br>Sei stato inattivo per ',
103                                            'en' => '<br>You are being idle for ' ),
104                       'tabtout_b'=> array( 'it' => ' minuti. <br><br>Quindi ritorni tra i <b>Giocatori in piedi</b>.',
105                                            'en' => ' minutes. <br><br>Then you return with the <b>standing players</b>.'),
106                       'tickmust' => array( 'it' => '<br>Per attivare il messaggio di segnalazione del tavolo occorre essere seduti.<br><br>',
107                                            'en' => '<br>To activate the signalling message of the table it\'s necessary to be sitting<br><br>'),
108                       'tickjust' => array( 'it' => '<br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br> ',
109                                            'en' => 'EN<br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br> '),
110                       'tickwait' => array( 'it' => '<br>Il messaggio di segnalazione del tavolo<br>&egrave; disattivato ancora per %d second%s.<br><br>',
111                                            'en' => 'EN<br>The signalling message of the table<br>will be deactivated for %d second%s.<br><br>'),
112                       'alarpass' => array( 'it' => '<br>La password digitata non &egrave; corretta.<br><br>',
113                                            'en' => '<br>The entered password is not correct.<br><br>'),
114                       'alarret'  => array( 'it' => 'Alarm \\"<b>%s</b>\\" inviato a <b>%s</b>.',
115                                            'en' => 'Alarm \\"<b>%s</b>\\" sent to <b>%s</b>.'),
116                       'authmust' => array( 'it' => '<b>Per autenticare qualcuno devi a tua volta essere autenticato e certificato.</b>',
117                                            'en' => '<b>To authenticate someone you have to be authenticated and certified.</b>'), // on your turn
118                       'mesgmust' => array( 'it' => '<b>Per inviare un messaggio devi essere autenticato.</b>',
119                                            'en' => '<b>To send a message you have to be authenticated.</b>'),
120                       'nickmust' => array( 'it' => 'Il nickname deve contenere almeno una lettera dell\'alfabeto o una cifra.',
121                                            'en' => 'The nickname have to contain at least one letter or one number.'),
122                       'nickdupl' => array( 'it' => 'Nickname <b>%s</b> gi&agrave; in uso.',
123                                            'en' => 'The nickname <b>%s</b> is already in use.'),
124                       'authchan' => array( 'it' => '<b>Non puoi cambiare nick a un tavolo per soli autenticati o se sei in modalità isolata.</b>',
125                                            'en' => '<b>You can\'t change your nickname into a table for only authenticated or if you are in isolation mode.</b>'),
126                       '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>',
127                                            '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 ???
128                       'statunkn' => array( 'it' => 'Questo stato non esiste.',
129                                            'en' => 'This state don\'t exists.'),
130                       'tabincon' => array( 'it' => '<br>I dati del tavolo n&deg; %d sono inconsistenti, verranno resettati.<br><br>Torni in piedi.<br><br>',
131                                            'en' => 'EN <br>I dati del tavolo n&deg; %d sono inconsistenti, verranno resettati.<br><br>Torni in piedi.<br><br>'),
132                       'listmust' => array( 'it' => '<b>Per andare in isolamento non bisogna essere seduti a tavoli non riservati.</b>',
133                                            'en' => '<b>To go to isolation you must don\'t stay on not reserved tables</b>'),
134
135                       'tit_onauth'=>array( 'it' => '(solo aut.)',
136                                            'en' => '(only aut.)'),
137                       'tit_onisol'=>array( 'it' => '(isolam.to)',
138                                            'en' => '(isolation)'),
139                       '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.',
140                                           'en'  => 'Connection to the database failed<br>All authentications are suspended temporarly, you login as normal user.<br>We are about the limitation'),
141
142                       'tos_old'  => array( 'it' => '<b>%s</b> ha sottoscritto dei Termini del Servizio antecedenti a quelli necessari per poter richiedere questa funzionalità.',
143                                            'en' => 'EN <b>%s</b> ha sottoscritto dei Termini del Servizio antecedenti a quelli necessari per poter richiedere questa funzionalità.'),
144                       'gua_nfd'  => array( 'it' => 'Non è stato trovato un garante per <b>%s</b>.',
145                                            'en' => 'EN Non è stato trovato un garante per <b>%s</b>.'),
146                       'gua_self' => array( 'it' => '<b>%s</b> si è auto-garantito.',
147                                            'en' => 'EN <b>%s</b> si è auto-garantito.'),
148                       'gua_info' => array( 'it' => 'Il garante di <b>%s</b> è <b>%s</b>.',
149                                            'en' => 'EN Il garante di <b>%s</b> è <b>%s</b>.'),
150                       'gua_err'  => array( 'it' => 'Error %d. Utilizzo: <b>/guar <i>&lt;login&gt;</i></b>.',
151                                            'en' => 'Error %d. Usage: <b>/guar <i>&lt;login&gt;</i></b>.')
152 );
153
154 $G_lng = langtolng($G_lang);
155
156 $G_all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
157 $G_brisk_version = "4.18.5";
158
159 /* MLANG: ALL THE INFO STRINGS IN brisk.phh */
160 $root_wellarr = array( 'it' => array ( 'Brisk (Ver. '.$G_brisk_version.'), <b>NOVITA\'</b>: Puffin riattivato, accessi da cloud disattivati, corretto bug sulla gestione di puffin, riabilitato blocco dei proxy.',
161                                        'Se vuoi iscriverti alla <a target="_blank" href="mailto:ml-briscola+subscribe@milug.org">Mailing List</a>, cliccala!' ),
162                        'en' => array ( 'Brisk (Ver. '.$G_brisk_version.'), <b>NEWS</b>: Puffin re-enabled, cloud accesses disabled, fixed puffin mgmt bug, re-enabled proxy access block.',
163                                        'If you want to subscribe our <a target="_blank" href="ml-briscola+subscribe@milug.org">Mailing List</a>, click it!' ) );
164
165 $G_room_help = array( 'it' => '
166 <div style=\\"text-align: left; padding: 8px;\\">
167 <b>Descrizione</b><br>
168 Questa è un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
169 <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>
170 <b>Configurazione del browser.</b><br>
171 Occorre abilitare i cookies.<br>
172 <br>
173 <b>Uso del sito</b><br>
174 Potete sedervi a un tavolo o rimanere in piedi.<br>
175 Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la partita.<br>
176 <br>
177 <b>Partita</b><br>
178 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>
179 Chi vince l\'asta dovr&agrave; decidere il seme della carta scelta e inizier&agrave; la mano.<br>
180 Per giocare le carte dovrete trascinarle nel quadrato al centro del vostro schermo.<br><br>
181 Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno al quadrato al centro del vostro schermo.<br><br>
182 Durante la partita, se vorrete ricaricare la pagina, usate l\'apposito bottone \\"reload\\" in basso a destra.<br>
183 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.
184 <dl>
185 <dt><b>Comandi della chat</b>
186 <dd><b>/nick <i>&lt;nuovo_nickname&gt;</i></b> - cambio di nickname
187 <dd><b>/tav <i>&lt;frase di invito&gt;</i></b> - invito per gli altri giocatori al tavolo dove si &egrave; seduti
188 <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\\"
189 <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
190 <dd><b>/guar <i>&lt;login&gt;</i></b> - mostra il garante dell\'utente con il login passato come argomento
191 <dd><b>/authreq</b> - se si &egrave; autenticati permette di garantire per un utente fidato
192 <dd><b>/mesgtoadm</b> - se si &egrave; autenticati permette di lasciare un messaggio all\'amministratore del sito
193 <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)
194 </dl>
195 </div>
196 ',
197
198 'en' => '
199 <div style=\\"text-align: left; padding: 8px;\\">
200 <b>EN Descrizione</b><br>
201 EN Questa è un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
202 <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>
203 <b>Configurazione del browser.</b><br>
204 Occorre abilitare i cookies.<br>
205 <br>
206 <b>Uso del sito</b><br>
207 Potete sedervi a un tavolo o rimanere in piedi.<br>
208 Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la partita.<br>
209 <br>
210 <b>Partita</b><br>
211 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>
212 Chi vince l\'asta dovr&agrave; decidere il seme della carta scelta e inizier&agrave; la mano.<br>
213 Per giocare le carte dovrete trascinarle nel quadrato al centro del vostro schermo.<br><br>
214 Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno al quadrato al centro del vostro schermo.<br><br>
215 Durante la partita, se vorrete ricaricare la pagina, usate l\'apposito bottone \\"reload\\" in basso a destra.<br>
216 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.
217 <dl>
218 <dt><b>Comandi della chat</b>
219 <dd><b>/nick <i>&lt;nuovo_nickname&gt;</i></b> - cambio di nickname
220 <dd><b>/tav <i>&lt;frase di invito&gt;</i></b> - invito per gli altri giocatori al tavolo dove si &egrave; seduti
221 <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\\"
222 <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
223 <dd><b>/guar <i>&lt;login&gt;</i></b> - mostra il garante dell\'utente con il login passato come argomento
224 <dd><b>/authreq</b> - se si &egrave; autenticati permette di garantire per un utente fidato
225 <dd><b>/mesgtoadm</b> - se si &egrave; autenticati permette di lasciare un messaggio all\'amministratore del sito
226 <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)
227 </dl>
228 </div>
229 ');
230
231 //
232 $G_room_passwdhowto = array( 'it' => '<br><h2>Come registrarsi su Brisk</h2>
233 <div style=\\"text-align: left; padding: 8px;\\">
234 Attualmente ci sono due metodi per ottenere una password sul sito:<br><br>
235 <dir>
236 <li><b>Facendosi garantire da un utente di Brisk che sia certificato.</b><br><br>
237 <li><b>Auto-garantendosi utilizzando uno dei seguenti sistemi di identificazione digitale:</b><br><br>
238 <dir>
239 <li>Carta Regionale dei Servizi della Lombardia (la tessera sanitaria)
240 <li>Carta Regionale dei Servizi del Friuli Venezia Giulia (la tessera sanitaria)
241 <li>Smart card di InfoCamere
242 </dir>
243 <br>
244 <b>Per auto-garantisi occorre possedere:</b><br><br>
245 <dir>
246 <li>il codice PIN della propria carta
247 <li>il lettore di smart-card per collegare la carta al PC (acquistabile di solito presso le edicole)
248 </dir>
249 <br>
250 <b>Per effettuare la registrazione collegarsi al sito:</b> <a class=\\"flat\\"  target=\\"_blank\\" href=\\"https://brisk.mine.nu\\">https://brisk.mine.nu</a>
251 <br>
252 Se sei in possesso di una carta che permette l\'identificazione via internet che non è nell\'elenco qui sopra
253 <a class=\\"flat\\" href=\\"mailto:authadmbrisk@alternativeoutput.it\\">fai una segnalazione</a>.<br><br>
254 Le regole per ottenere la certificazione sono in via di definizione, l\' unica accettata è la conoscenza
255 diretta dell\' utente da parte dell\' amministratore.
256
257 </dir>
258 </div>
259 ',
260                              'en' => '<br><h2>EN Come registrarsi su Brisk</h2>
261 <div style=\\"text-align: left; padding: 8px;\\">
262 EN Attualmente ci sono due metodi per ottenere una password sul sito:<br><br>
263 <dir>
264 <li><b>Facendosi garantire da un utente di Brisk che gi&agrave; possidede una password</b><br><br>
265 <li><b>Auto-garantendosi utilizzando uno dei seguenti sistemi di identificazione digitale:</b><br><br>
266 <dir>
267 <li>Carta Regionale dei Servizi della Lombardia (la tessera sanitaria)
268 <li>Carta Regionale dei Servizi del Friuli Venezia Giulia (la tessera sanitaria)
269 </dir>
270 <br>
271 <b>Per auto-garantisi occorre possedere:</b><br><br>
272 <dir>
273 <li>il codice PIN della propria carta
274 <li>il lettore di smart-card per collegare la carta al PC (acquistabile di solito presso le edicole)
275 </dir>
276 <br>
277 <b>Per effettuare la registrazione collegarsi al sito:</b> <a class=\\"flat\\"  target=\\"_blank\\" href=\\"https://brisk.mine.nu\\">https://brisk.mine.nu</a>
278 <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>.<br><br>
281 Le regole per ottenere la certificazione sono in via di definizione, l\' unica accettata è la conoscenza
282 diretta dell\' utente da parte dell\' amministratore.
283
284
285 </dir>
286 </div>
287 ' );
288 /*
289 <dd>Seguendo la procedura di auto-garanzia all\'url: <a href="https://brisk.mine.nu">https://brisk.mine.nu</a>
290 ';
291 */
292
293 $G_room_about = array( 'it' => '<br>
294 <div id=\\"header\\" class=\\"header\\">
295   <img class=\\"nobo\\" src=\\"img/brisk_logo64.png\\">
296   briscola chiamata in salsa ajax
297 </div>
298 <br><b>version '.$G_brisk_version.'</b><br><br>
299 Copyright 2006-2012 <a href=\\"mailto:brisk@alternativeoutput.it\\">Matteo Nastasi</a> (aka mop)<br><br>',
300                       'en' => '<br>
301 <div id=\\"header\\" class=\\"header\\">
302   <img class=\\"nobo\\" src=\\"img/brisk_logo64.png\\">
303   declaration briscola in ajax sauce <b>(Beta)</b>
304 </div>
305 <br><b>version '.$G_brisk_version.'</b><br><br>
306 Copyright 2006-2012 <a href=\\"mailto:brisk@alternativeoutput.it\\">Matteo Nastasi</a> (aka mop)<br><br>');
307
308
309 $G_PG_vow = array("a", "e", "i", "o", "u", "y");
310 $G_PG_vow_n = 6;
311 $G_PG_cons = array(
312       "b", "bb", "bc", "bd", "bf", "bg", "bk", "bl", "bm", "bn", "bp",       "br", "bs", "bt", "bv", "bw",       "bz",
313       "c", "cb", "cc", "cd", "cf", "cg", "ck", "cl", "cm", "cn", "cp", "cq", "cr", "cs", "ct", "cv", "cw", "cx", "cz",
314       "d", "db", "dc", "dd", "df", "dg", "dk", "dl", "dm", "dn", "dp",       "dr", "ds", "dt", "dv", "dw", "dx", "dz",
315       "f", "fb", "fc", "fd", "ff", "fg", "fk", "fl", "fm", "fn", "fp",       "fr", "fs", "ft", "fv", "fw", "fx", "fz",
316       "g", "gb", "gc", "gd", "gf", "gg", "gk", "gl", "gm", "gn", "gp",       "gr", "gs", "gt", "gv", "gw", "gx", "gz",
317       "j", "jb", "jc", "jd", "jf", "jg", "jk", "jl", "jm", "jn", "jp", "jq", "jr", "js", "jt", "jv", "jw", "jx", "jz",
318       "k", "kb", "kc", "kd", "kf", "kg", "kk", "kl", "km", "kn", "kp",       "kr", "ks", "kt", "kv", "kw", "kx", "kz",
319       "l", "lb", "lc", "ld", "lf", "lg", "lk", "ll", "lm", "ln", "lp",       "lr", "ls", "lt", "lv", "lw", "lx", "lz",
320       "m", "mb", "mc", "md", "mf", "mg", "mk", "ml", "mm", "mn", "mp",       "mr", "ms", "mt", "mv", "mw", "mx", "mz",
321       "n", "nb", "nc", "nd", "nf", "ng", "nk", "nl", "nm", "nn", "np",       "nr", "ns", "nt", "nv", "nw", "nx", "nz",
322       "p", "pb", "pc", "pd", "pf", "pg", "pk", "pl", "pm", "pn", "pp",       "pr", "ps", "pt", "pv", "pw", "px", "pz",
323       "q", "qb", "qc", "qd", "qf", "qg", "qk", "ql", "qm", "qn", "qp", "qq", "qr", "qs", "qt", "qv", "qw", "qx", "qz",
324       "r", "rb", "rc", "rd", "rf", "rg", "rk", "rl", "rm", "rn", "rp",       "rr", "rs", "rt", "rv", "rw", "rx", "rz",
325       "s", "sb", "sc", "sd", "sf", "sg", "sk", "sl", "sm", "sn", "sp", "sq", "sr", "ss", "st", "sv", "sw", "sx", "sz",
326       "t", "tb", "tc", "td", "tf", "tg", "tk", "tl", "tm", "tn", "tp",       "tr", "ts", "tt", "tv", "tw", "tx", "tz",
327       "v", "vb", "vc", "vd", "vf", "vg", "vk", "vl", "vm", "vn", "vp",       "vr", "vs", "vt", "vv", "vw", "vx", "vz",
328       "w", "wb", "wc", "wd", "wf", "wg", "wk", "wl", "wm", "wn", "wp",       "wr", "ws", "wt", "wv", "ww", "wx", "wz",
329       "x", "xb", "xc", "xd", "xf", "xg", "xk", "xl", "xm", "xn", "xp",       "xr", "xs", "xt", "xv", "xw", "xx", "xz",
330       "z", "zb", "zc", "zd", "zf", "zg", "zk", "zl", "zm", "zn", "zp",       "zr", "zs", "zt", "zv", "zw", "zx", "zz",
331                   );
332 // $G_PG_cons_n = count($G_PG_cons);
333 // printf("N CONS: %d\n", $G_PG_cons_n);
334 $G_PG_cons_n = 345;
335     /*     printf("%d %d\n", count($voc), count($cons)); */
336     /* for ($i = 0 ; $i < 26 ; $i++) { */
337     /*     if (array_search(chr(ord('a') + $i), $voc) !== FALSE || $i == 7) */
338     /*         continue; */
339     /*     printf('      "%s", ', chr(ord('a') + $i)); */
340     /*     for ($e = 0 ; $e < 26 ; $e++) { */
341     /*         if (array_search(chr(ord('a') + $e), $voc) !== FALSE || $e == 7) */
342     /*             continue; */
343     /*         printf('"%s%s", ', chr(ord('a') + $i), chr(ord('a') + $e)); */
344     /*     } */
345     /*     printf("\n"); */
346     /* } */
347
348 function ip2int($s)
349 {
350     $v = ip2long($s);
351     if (PHP_INT_SIZE == 4)
352         return ($v);
353
354     return ( ($v & 0x80000000 ? 0xffffffff00000000 : 0x00) | $v );
355 }
356
357 function int2ip($i)
358 {
359     return long2ip($i & 0xffffffff);
360 }
361
362 function nickserv_msg($dt, $msg) {
363     return sprintf('chatt_sub("%s",[0x040003,"%s"],"%s");', $dt, NICKSERV, $msg);
364 }
365
366 function passwd_gen($seed = NULL)
367 {
368     GLOBAL $G_PG_vow, $G_PG_vow_n, $G_PG_cons, $G_PG_cons_n;
369
370     $pw = "";
371
372     if ($seed != NULL)
373         mt_srand($seed);
374     else
375         mt_srand();
376
377     for ($sil = 0 ; $sil < 7 ; $sil++) {
378         if (($sil % 2) == 0) {
379             // vowels
380             for ($n = 0 ; $n < mt_rand(1,2) ; $n++) {
381                 if ($n == 0) {
382                     $old = mt_rand(0, $G_PG_vow_n-1);
383                     $pw .= $G_PG_vow[$old];
384                 }
385                 else {
386                     $new = mt_rand(0, $G_PG_vow_n-1);
387                     if ($new == $old)
388                         $new = ($new + mt_rand(0, $G_PG_vow_n-2)) % $G_PG_vow_n;
389                     $pw .= $G_PG_vow[$new];
390                 }
391             }
392         }
393         else {
394             // consonants
395             $pw .= $G_PG_cons[mt_rand(0, $G_PG_cons_n-1)];
396         }
397     }
398
399     return $pw;
400 }
401
402 function cmd_return($val, $desc)
403 {
404     return array('val' => $val, 'desc' => $desc);
405 }
406
407 function cmd_serialize($attrs)
408 {
409     $ret = "";
410
411     $sep = "";
412     foreach ($attrs as $key => $value) {
413         $ret .= $sep . $key . '=' . urlencode($value);
414         $sep = "&";
415     }
416     return $ret;
417 }
418
419 function cmd_deserialize($cmd)
420 {
421     $ret = array();
422     $a = explode('&', $cmd);
423     $i = 0;
424     while ($i < count($a)) {
425         $b = split('=', $a[$i]);
426         $ret[urldecode($b[0])] = urldecode($b[1]);
427         $i++;
428     }
429
430     return $ret;
431 }
432
433 //  return values
434 // -1 v1 < v2
435 //  0 equal
436 //  1 v1 > v2
437 function versions_cmp($v1, $v2)
438 {
439     // printf("V1: [%s]\nV2: [%s]\n", $v1, $v2);
440     if ($v1 == $v2)
441         return 0;
442
443     $v1_ar = split('\.', $v1);
444     $v2_ar = split('\.', $v2);
445
446     $v2_ct = count($v2_ar);
447
448     for ($i = 0 ; $i < count($v1_ar) ; $i++) {
449         if (($v2_ct - 1) < $i) {
450             break;
451         }
452         // printf("here [%s] [%s]\n", $v1_ar[$i], $v2_ar[$i]);
453         if ($v1_ar[$i] != $v2_ar[$i]) {
454             if (strval($v1_ar[$i]) < strval($v2_ar[$i]))
455                 return -1;
456             else
457                 return  1;
458         }
459     }
460     return 0;
461 }
462
463 // return string with IPV4 address
464 function addrtoipv4($addr)
465 {
466     $ipv4addr_arr = explode(':' , $addr);
467     if (isset($ipv4addr_arr[3])) {
468         $ipv4addr = $ipv4addr_arr[3];
469     }
470     else {
471         $ipv4addr = $addr;
472     }
473     return $ipv4addr;
474 }
475
476 function mop_flush()
477 {
478     for ($i = 0; $i < ob_get_level(); $i++)
479         ob_end_flush();
480     ob_implicit_flush(1);
481     flush();
482 }
483
484 function force_no_cache(&$header_out)
485 {
486     $header_out['Pragma'] = 'no-cache, must-revalidate';
487     $header_out['Cache-Control'] = 'no-cache';
488     $header_out['Expires'] = '-1';
489 }
490
491 function file_lock($fname, $is_exclusive)
492 {
493     if (($res = @fopen($fname, "r+")) == FALSE) {
494         return (FALSE);
495     }
496
497     if (flock($res, ($is_exclusive ? LOCK_EX : LOCK_SH)) == FALSE) {
498         fclose($res);
499         return (FALSE);
500     }
501
502     return ($res);
503 }
504
505 function file_unlock($res)
506 {
507     if ($res != FALSE) {
508         flock($res, LOCK_UN);
509         fclose($res);
510     }
511 }
512
513 $escpush_from = array("\\", "\"");
514 $escpush_to   = array("\\\\", "\\\"");
515 function escpush($s)
516 {
517     GLOBAL $escpush_from, $escpush_to;
518
519     return str_replace($escpush_from, $escpush_to, $s);
520 }
521
522 $escinp_from = array( "\""     );
523 $escinp_to = array(   "&quot;" );
524
525 function escinput($s)
526 {
527     GLOBAL $escinp_from, $escinp_to;
528
529     return str_replace($escinp_from, $escinp_to, $s);
530 }
531
532 function eschtml($s)
533 {
534     return htmlentities($s, ENT_COMPAT, "UTF-8");
535 }
536
537 function esclfhtml($s)
538 {
539     return str_replace(" ", "&nbsp;", str_replace("\n", "<br>", htmlspecialchars($s)));
540 }
541
542 function langtolng($lang)
543 {
544   GLOBAL $G_lang;
545
546   return ($G_lang == 'en' ? '-en' : '');
547 }
548
549 function csplitter($in, $sep)
550 {
551   $st = 0;
552   $id = 0;
553   $out = array();
554   $out[$id] = "";
555   for ($i = 0 ; $i < strlen($in) ; $i++) {
556     $ini = substr($in, $i, 1);
557     if ($st == 0) {
558       if ($ini == '\\')
559         $st = 1;
560       else if ($ini == $sep) {
561         $id++;
562         $out[$id] = "";
563       }
564       else {
565         $out[$id] .= $ini;
566       }
567     }
568     else if ($st == 1) {
569       $out[$id] .= $ini;
570       $st = 0;
571     }
572   }
573
574   return ($out);
575 }
576
577 function xcape($s)
578 {
579   $from = array (   '\\',     '@',        '|' );
580   $to   = array ( '\\\\', '&#64;', '&brvbar;' );
581
582   return (str_replace($from, $to, htmlentities($s,ENT_COMPAT,"UTF-8")));
583 }
584
585 function xcapelt($s)
586 {
587   $from = array (   '\\',     '|',  "\t",  "\n");
588   $to   = array ( '\\\\',   '\\|', "\\t", "\\n");
589
590   return (str_replace($from, $to, $s));
591 }
592
593 function xcapemesg($s)
594 {
595   $from = array (  "\n");
596   $to   = array ( "\\n");
597
598   return (str_replace($from, $to, $s));
599 }
600
601
602 class Vect {
603     function Vect($a)
604     {
605         $this->el = $a;
606     }
607
608     function getbyid($idx)
609     {
610         return ($this->el[$idx]);
611     }
612
613     function setbyid($idx, $v)
614     {
615         $this->el[$idx] = $v;
616     }
617 }
618
619 define('TABLE_AUTH_TY_PUBL', 0);
620 define('TABLE_AUTH_TY_AUTH', 1);
621 define('TABLE_AUTH_TY_CERT', 2);
622
623
624 class Table {
625   var $idx;
626   var $player;
627   var $player_n;
628
629   var $auth_type;     // required authorization to sit down
630
631   var $wag_own;
632   var $wag_com;
633   var $wag_tout;
634
635   var $table_token;
636   var $table_start;   // information field
637
638   var $wakeup_time;
639
640   function Table()
641   {
642   }
643
644   function create($idx)
645   {
646     if (($thiz = new Table()) == FALSE)
647       return (FALSE);
648
649     $thiz->idx       =   $idx;
650     $thiz->player    =   array();
651     $thiz->player_n  =   0;
652
653     if ($idx < TABLES_CERT_N)
654         $thiz->auth_type =   TABLE_AUTH_TY_CERT;
655     else if ($idx < TABLES_AUTH_N)
656         $thiz->auth_type =   TABLE_AUTH_TY_AUTH;
657     else
658         $thiz->auth_type =   TABLE_AUTH_TY_PUBL;
659
660     $thiz->wag_own   =  -1;
661     $thiz->wag_com   =  "";
662     $thiz->wag_tout   =  0;
663
664     $thiz->table_token  = "";
665     $thiz->table_start  = 0;
666
667     $thiz->wakeup_time = 0;
668
669     return ($thiz);
670   }
671
672   function copy($from)
673   {
674     $this->idx = $from->idx;
675     $this->player = array();
676     for ($i = 0 ; $i < $from->player_n ; $i++)
677       $this->player[$i] = $from->player[$i];
678     $this->player_n = $from->player_n;
679
680     log_main("PLAYER_N - parent::copy.".$this->player_n);
681
682     $this->auth_type =  $from->auth_type;
683
684     $this->wag_own   =  $from->wag_own;
685     $this->wag_com   =  $from->wag_com;
686     $this->wag_tout  =  $from->wag_tout;
687
688     $this->table_token  = $from->table_token;
689     $this->table_start  = $from->table_start;
690
691     $this->wakeup_time = $from->wakeup_time;
692   }
693
694   function myclone($from)
695   {
696     if (($thiz = new Table()) == FALSE)
697       return (FALSE);
698
699     $this->copy($from);
700
701     return ($thiz);
702   }
703
704   function spawn($from)
705   {
706     if (($thiz = new Table()) == FALSE)
707       return (FALSE);
708
709     $thiz->idx = $from->idx;
710     $thiz->player = array();
711     for ($i = 0 ; $i < $from->player_n ; $i++)
712       $thiz->player[$i] = $i;
713     $thiz->player_n = $from->player_n;
714
715     $thiz->auth_type =  $from->auth_type;
716
717     $thiz->wag_own = $from->wag_own;
718     $thiz->wag_com = $from->wag_com;
719     $thiz->wag_tout  =  $from->wag_tout;
720
721     $thiz->table_token  = $from->table_token;
722     $thiz->table_start  = $from->table_start;
723
724     $thiz->wakeup_time = $from->wakeup_time;
725
726     return ($thiz);
727   }
728
729   function wag_set($user_idx, $mesg)
730   {
731     log_main("WAG_SET");
732
733     $this->wag_own  =  $user_idx;
734     $this->wag_com  =  $mesg;
735     $this->wag_tout =  0;
736   }
737
738   function wag_reset($timeout)
739   {
740     log_main("WAG_RESET");
741
742     unset($this->wag_own);
743     $this->wag_own  = -1;
744     $this->wag_com  = "";
745     $this->wag_tout = $timeout;
746   }
747
748   function player_get($idx)
749   {
750     return ($this->player[$idx]);
751   }
752
753   function player_set($idx, $player)
754   {
755     $this->player[$idx] = $player;
756   }
757
758   function user_add($idx)
759   {
760     $this->player[$this->player_n] = $idx;
761     $this->player_n++;
762
763     return ($this->player_n - 1);
764   }
765
766   function user_rem($brisk, $user)
767   {
768     $tabpos = $user->table_pos;
769
770     /* verifico la consistenza dei dati */
771     if ($brisk->user[$this->player[$tabpos]] == $user) {
772
773       /* aggiorna l'array dei giocatori al tavolo. */
774       for ($i = $tabpos ; $i < $this->player_n-1 ; $i++) {
775         $this->player[$i] = $this->player[$i+1];
776         $user_cur = $brisk->user[$this->player[$i]];
777         $user_cur->table_pos = $i;
778       }
779       $this->player_n--;
780     }
781     else {
782       log_main("INCONSISTENCY ON TABLE.");
783     }
784   }
785
786   // Table->act_content - return 'id' of type of output required for table button
787   function act_content($user)
788   {
789     $ret = "";
790     $isstanding = ($user->subst == 'standup');
791     $sitted = $this->player_n;
792     $table = $this->idx;
793     $cur_table = $user->table;
794     $allowed = TRUE;
795
796     if ($isstanding) {
797       if ($sitted < PLAYERS_N) {
798           switch ($this->auth_type) {
799           case TABLE_AUTH_TY_CERT:
800               if ($user->is_cert())
801                   $act = "sitcert";
802               else
803                   $act = 'resercert';
804               break;
805           case TABLE_AUTH_TY_AUTH:
806               if ($user->is_auth())
807                   $act = "sitreser";
808               else
809                   $act = 'reserved';
810               break;
811           default:
812               $act = 'sit';
813               break;
814           }
815       }
816       else {
817         $act = 'none';
818       }
819     }
820     else {
821       if ($table == $cur_table)
822         $act = 'wake';
823       else
824         $act = 'none';
825     }
826
827     if ($act != '')
828       $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
829
830     return ($ret);
831   }
832 } // end class Table
833
834
835 class Delay_Manager
836 {
837     var $delta;
838     var $lastckeck;
839     var $triglevel;
840
841     function Delay_Manager($triglevel)
842     {
843         $this->triglevel = $triglevel;
844         $this->delta = array();
845         $this->lastcheck = 0;
846     }
847
848     function delta_get($curtime)
849     {
850         // clean too old delta items
851         for ($i = 0 ; $i < count($this->delta) ; $i++) {
852             if ($this->delta[$i][0] < $curtime) {
853                 array_splice($this->delta, $i, 1);
854                 $i--;
855             }
856         }
857
858         // add new delta items if delay exceeded $this->triglevel sec
859         if ($curtime > $this->lastcheck + $this->triglevel && $curtime < $this->lastcheck + 1200.0) {
860             $delta = $curtime - $this->lastcheck - $this->triglevel;
861             array_push($this->delta, array($curtime + $delta , $delta));
862             // fprintf(STDERR, "DELTA: add new delta [%f] [%f] [%f]\n", $this->triglevel, $curtime + $delta, $delta);
863         }
864
865         // extract the maximum valid delta
866         $delta_max = 0.0;
867         for ($i = 0 ; $i < count($this->delta) ; $i++) {
868             $delta_cur = $this->delta[$i][1];
869             if ($delta_max < $delta_cur)
870                 $delta_max = $delta_cur;
871         }
872
873         // fprintf(STDERR, "DELTA: status %d, delta_max: %f\n", count($this->delta), $delta_max);
874
875         return ($delta_max);
876     }
877
878     function lastcheck_set($curtime)
879     {
880         $this->lastcheck = $curtime;
881     }
882 }
883
884 class Client_prefs {
885     var $listen;
886     var $supp_comp;
887
888     function Client_prefs()
889     {
890     }
891
892     static function from_user($user)
893     {
894         $thiz = new Client_prefs();
895         $thiz->user_load($user);
896
897         return ($thiz);
898     }
899
900     static function from_json($json)
901     {
902         $thiz = new Client_prefs();
903         if ($thiz->json_load($json) == FALSE) {
904             unset($thiz);
905             return (FALSE);
906         }
907
908         return ($thiz);
909     }
910
911     function user_load($user)
912     {
913         fprintf(STDERR, "QQ %s: %x\n", __FUNCTION__, $user->flags);
914         $this->listen = ($user->flags & USER_FLAG_MAP_AUTH) >> 2;
915         if ($user->rec != FALSE) {
916             $this->supp_comp = $user->rec->supp_comp_get();
917         }
918         else {
919             $this->supp_comp = "000000000000";
920         }
921
922         fprintf(STDERR, "QQ %s: LISTEN: %d\n", __FUNCTION__, $this->listen);
923     }
924
925     function json_load($json_s)
926     {
927         $ret = FALSE;
928
929         do {
930             if (gettype($json_s) == "string") {
931                 if (($json = json_decode($json_s)) == FALSE)
932                     break;
933             }
934             else {
935                 $json = $json_s;
936             }
937             if ($this->listen < 0 || $this->listen > 2)
938                 break;
939             $this->listen = $json->listen;
940
941             if (mb_strlen($json->supp_comp, "ASCII") != 12)
942                 break;
943
944             for ($i = 0, $idx = 0 ; $i < 12 ; $i++) {
945                 if (($json->supp_comp[$i] >= '0' && $json->supp_comp[$i] <= '9') ||
946                     ($json->supp_comp[$i] >= 'a' && $json->supp_comp[$i] <= 'f'))
947                     continue;
948                 break;
949             }
950             if ($i < 12)
951                 break;
952             $this->supp_comp = $json->supp_comp;
953             $ret = TRUE;
954         } while (FALSE);
955
956         return ($ret);
957     }
958
959     function store($user, $is_save)
960     {
961         // save into DB
962         fprintf(STDERR, "QQ %s::%s PRE: %x\n", __CLASS__, __FUNCTION__,
963                 $user->flags & (~USER_FLAG_S_ALL & ~USER_FLAG_AUTH));
964         $user->flags_set(($this->listen << 2), USER_FLAG_MAP_AUTH);
965         fprintf(STDERR, "QQ %s::%s %x\n", __CLASS__, __FUNCTION__,
966                 $user->flags);
967         if ($user->is_supp_custom()) {
968             $user->rec->supp_comp_set($this->supp_comp);
969         }
970         if ($is_save)
971             $user->prefs_store();
972     }
973 }
974
975 define('GHOST_SESS_TOUT', 1800);
976 define('GHOST_SESS_REAS_LOUT', 1); // logout
977 define('GHOST_SESS_REAS_ANOT', 2); // another user get session
978 define('GHOST_SESS_REAS_TOUT', 3); // room timeout
979 define('GHOST_SESS_REAS_TTOT', 4); // table timeout
980 define('GHOST_SESS_REAS_ANON', 5); // anonymizer access
981 define('GHOST_SESS_REAS_PROX', 6); // proxy access
982
983 class GhostSessEl
984 {
985     var $time;
986     var $sess;
987     var $reas;
988
989     function GhostSessEl($time, $sess, $reas)
990     {
991         $this->time = $time + GHOST_SESS_TOUT;
992         $this->sess = $sess;
993         $this->reas = $reas;
994     }
995 }
996
997 class GhostSess
998 {
999     var $gs;
1000
1001     function GhostSess()
1002     {
1003         $this->gs = array();
1004     }
1005
1006     // push or update for this session
1007     function push($time, $sess, $reas)
1008     {
1009         foreach($this->gs as $el) {
1010             if ($el->sess == "$sess") {
1011                 $el->reas = $reas;
1012                 $el->time = $time + GHOST_SESS_TOUT;
1013                 return TRUE;
1014             }
1015         }
1016
1017         $this->gs[] = new GhostSessEl($time, $sess, $reas);
1018         return TRUE;
1019     }
1020
1021     function pop($sess)
1022     {
1023         foreach($this->gs as $key => $el) {
1024             if ($el->sess == "$sess") {
1025                 $ret = $this->gs[$key];
1026                 unset($this->gs[$key]);
1027                 return ($ret);
1028             }
1029         }
1030         return FALSE;
1031     }
1032
1033     function garbage_manager($curtime)
1034     {
1035         foreach($this->gs as $key => $el) {
1036             if ($el->time < $curtime) {
1037                 unset($this->gs[$key]);
1038             }
1039         }
1040     }
1041 }
1042
1043 class Brisk
1044 {
1045     static $delta_t;
1046
1047     var $crystal_filename;
1048     var $user;
1049     var $table;
1050     var $match;
1051     var $comm; // commands for many people
1052     var $step; // current step of the comm array
1053     var $garbage_timeout;
1054     var $shm_sz;
1055
1056     var $ban_list;       // ban list (authized allowed)
1057     var $black_list;     // black list (anti-dos, noone allowed)
1058     var $cloud_smasher;  // list of cloud ip ranges to be rejected
1059     var $ghost_sess;
1060     var $delay_mgr;
1061
1062     var $cds;
1063
1064     public static $sess_cur;
1065
1066     function Brisk()
1067     {
1068         $this->cds = NULL;
1069     }
1070
1071     // constructor
1072     static function create($crystal_filename, $ban_list, $black_list, $cloud_smasher) {
1073         if (($brisk_ser = @file_get_contents($crystal_filename)) != FALSE) {
1074             if (($brisk = unserialize($brisk_ser)) != FALSE) {
1075                 fprintf(STDERR, "ROOM FROM FILE\n");
1076                 rename($crystal_filename, $crystal_filename.".old");
1077
1078                 $brisk->reload(TRUE, $ban_list, $black_list, $cloud_smasher);
1079
1080                 return($brisk);
1081             }
1082         }
1083
1084         fprintf(STDERR, "NEW ROOM\n");
1085         $thiz = new Brisk();
1086
1087         $thiz->crystal_filename = $crystal_filename;
1088         $thiz->user  = array();
1089         $thiz->table = array();
1090         $thiz->match = array();
1091
1092         $thiz->ban_list = IpClass::create();
1093         $thiz->black_list = IpClass::create();
1094         $thiz->cloud_smasher = IpClass::create();
1095         $thiz->ghost_sess = new GhostSess();
1096
1097         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1098             $thiz->user[$i] = User::create($thiz, $i, "", "");
1099         }
1100
1101         for ($i = 0 ; $i < TABLES_N ; $i++) {
1102             $thiz->table[$i] = Table::create($i);
1103         }
1104         $thiz->garbage_timeout = 0;
1105         $thiz->shm_sz = SHM_DIMS_MIN;
1106
1107         $thiz->delay_mgr = new Delay_Manager(1.5);
1108
1109         static::$sess_cur = FALSE;
1110
1111         $thiz->reload(TRUE, $ban_list, $black_list, $cloud_smasher);
1112
1113         return ($thiz);
1114     }
1115
1116     function reload($is_first, $ban_list, $black_list, $cloud_smasher)
1117     {
1118         fprintf(STDERR, "RELOAD STUFF (%d)(%d)(%d)\n",
1119                 count($ban_list), count($black_list), count($cloud_smasher));
1120
1121         if (defined('CURL_DE_SAC_VERS')) {
1122             if (brisk_cds_reload($this) == FALSE) {
1123                 exit(12);
1124             }
1125         }
1126         $this->ban_list->update($ban_list);
1127         $this->black_list->update($black_list);
1128         $this->cloud_smasher->update($cloud_smasher);
1129
1130         if (!$is_first) {
1131             $this->banned_kickoff();
1132             $this->garbage_manager(TRUE);
1133         }
1134     }
1135
1136     function banned_kickoff()
1137     {
1138         $is_ban = FALSE;
1139
1140         for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1141             $table_cur = $this->table[$table_idx];
1142             // if the table is complete and exists we check users IP
1143
1144             if ($table_cur->player_n == PLAYERS_N) {
1145                 if (isset($this->match[$table_idx]) &&
1146                     $table_cur->table_token == $bin5->table_token) {
1147                     log_main("PLAYERS == N TABLE ".$table_idx);
1148
1149                     $bin5 = $this->match[$table_idx];
1150
1151                     $is_ban |= $bin5->banned_kickoff();
1152                 }
1153             }
1154         }
1155
1156         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1157             $user_cur = $this->user[$i];
1158
1159             if ($user_cur->is_active() == FALSE)
1160                 continue;
1161
1162             // check if the IP is blacklisted
1163             if ($this->black_check($user_cur->ip) ||
1164                 $this->cloud_check($user_cur->ip)) {
1165                 $user_cur->lacc = 0;
1166                 $is_ban = TRUE;
1167                 continue;
1168             }
1169
1170             // if authorized not check if banlisted
1171             if ($user_cur->is_auth()) {
1172                 continue;
1173             }
1174
1175             if ($this->ban_check($user_cur->ip)) {
1176                 $user_cur->lacc = 0;
1177                 $is_ban = TRUE;
1178             }
1179         }
1180
1181         return $is_ban;
1182     }
1183
1184     function ban_check($ip_str)
1185     {
1186         return ($this->ban_list->check($ip_str));
1187     }
1188
1189     function black_check($ip_str)
1190     {
1191         return ($this->black_list->check($ip_str));
1192     }
1193
1194     function cloud_check($ip_str)
1195     {
1196         return ($this->cloud_smasher->check($ip_str));
1197     }
1198
1199     function users_cleanup()
1200     {
1201         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1202             $user_cur = $this->user[$i];
1203
1204             if ($user_cur->the_end) {
1205                 $user_cur->reset(); // users_cleanup, OK
1206             }
1207         }
1208     }
1209
1210   function garbage_manager($force)
1211   {
1212     GLOBAL $G_lang, $mlang_brisk, $G_base;
1213
1214     $ismod = FALSE;
1215
1216     log_rd2("garbage_manager START");
1217
1218     /* Garbage collector degli utenti in timeout */
1219     $curtime = microtime(TRUE);
1220
1221     $delta = $this->delay_mgr->delta_get($curtime);
1222
1223     if (!$force && !($this->garbage_timeout < $curtime)) {
1224         $this->delay_mgr->lastcheck_set($curtime);
1225         return ($ismod);
1226     }
1227
1228     // Before all align times with table timeout
1229     for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1230         $table_cur = $this->table[$table_idx];
1231         // if the table is complete and exists its shared mem we get the info about users lacc
1232
1233         if ($table_cur->player_n == PLAYERS_N) {
1234             log_main("PLAYERS == N TABLE ".$table_idx);
1235
1236
1237             $no_recovery = FALSE;
1238             if (isset($this->match[$table_idx])) {
1239                 $bin5 = $this->match[$table_idx];
1240
1241                 if ($table_cur->table_token != $bin5->table_token) {
1242                     log_main("ERROR: not matching table_token. Brisk: ".$table_cur->table_token."  Table: ".$bin5->table_token);
1243                     log_main("ERROR: not matching table_start. Brisk: ".$table_cur->table_start."  Table: ".$bin5->table_start);
1244                     $no_recovery = TRUE;
1245                     $bin5 = FALSE;
1246                 }
1247
1248                 if ($bin5 != FALSE) {
1249                     //
1250                     //  SPAWN: JOIN
1251                     //
1252                     log_main("garbage_manager: bri loaded successfully.");
1253                     $bin5->garbage_manager(TRUE);
1254
1255                     $bin5_table = $bin5->table[0];
1256
1257                     // is the end of the table
1258
1259                     if ($bin5->the_end == TRUE) {
1260                         /*
1261                          *  DESTROY OF FINISHED TABLE && MOVE PLAYER TO ROOM AGAIN
1262                          */
1263                         log_main("garbage_manager: INSIDE THE END.");
1264
1265                         $plist = "$table_cur->table_token|$table_cur->idx|$table_cur->player_n";
1266                         for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
1267                             $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
1268                         }
1269
1270                         for ($i = 0 ; $i < $bin5_table->player_n ; $i++) {
1271                             // stat must be "table" by definition
1272                             $user_cur = $this->user[$table_cur->player[$i]];
1273                             $bin5_user = $bin5->user[$i];
1274
1275                             $user_cur->subst      = $bin5_user->subst;
1276                             $user_cur->rd_step    = $bin5_user->rd_step;
1277                             $user_cur->step       = $bin5_user->step;
1278                             $user_cur->lacc       = $bin5_user->lacc;
1279                             $user_cur->laccwr     = $bin5_user->lacc;
1280                             $user_cur->bantime    = $bin5_user->bantime;
1281                             $user_cur->the_end    = $bin5_user->the_end;
1282                             if ($user_cur->the_end) {
1283                                 $this->ghost_sess->push($curtime, $user_cur->sess, GHOST_SESS_REAS_TTOT);
1284                             }
1285                         }
1286
1287                         log_legal($curtime, $user_cur->ip, $user_cur, "STAT:DESTROY_GAME", $plist);
1288
1289                         $this->room_join_wakeup($user_cur, FALSE, 0);
1290                         $table_cur->table_token = "";
1291                         $table_cur->wakeup_time = $curtime + WAKEUP_TIME;
1292
1293                         $this->match_del($table_idx);
1294                     }
1295                     else {
1296                         log_main("gm:: save_data");
1297
1298                         for ($i = 0 ; $i < $bin5_table->player_n ; $i++) {
1299                             $this->user[$table_cur->player[$i]]->lacc = $bin5->user[$i]->lacc;
1300                         }
1301                     }
1302                 } // if ($bin5 == FALSE
1303                 else if ($no_recovery == FALSE) {
1304                     log_crit("ERROR: table ".$table_idx." unrecoverable join");
1305
1306                     for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
1307                         $user_cur = $this->user[$table_cur->player[$i]];
1308                         $user_cur->subst = "shutdowner";
1309                         $user_cur->step_inc();
1310
1311                         $ret = sprintf('stat = "%s"; subst = "%s";',  $user_cur->stat, $user_cur->subst);
1312                         $ret .= "gst.st = ".($user_cur->step+1)."; ";
1313                         // MLANG <br>I dati del tavolo n&deg; ".$user_cur->table." sono inconsistenti, verranno resettati.<br><br>Torni in piedi.<br><br>
1314                         $prestr = sprintf($mlang_brisk['tabincon'][$G_lang], $user_cur->table);
1315                         $ret .= show_notify($prestr, 2000, $mlang_brisk['btn_close'][$G_lang], 400, 110);
1316                         $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1317                         $user_cur->step_inc();
1318                     }
1319
1320                     $plist = "$table_cur->table_token|$user_cur->table|$table_cur->player_n";
1321                     for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
1322                         $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
1323                     }
1324                     log_legal($curtime, $user_cur->ip, $user_cur, "STAT:DESTROY_GAME(RECOVERY)", $plist);
1325
1326                     $this->room_join_wakeup($user_cur, TRUE, -2);
1327                     $table_cur->table_token = "";
1328                 }
1329             }
1330         } //  if ($table_cur->player_n == PLAYERS_N) {
1331     } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1332
1333     log_rd2("out new loop.");
1334
1335     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1336         $user_cur = $this->user[$i];
1337
1338         log_rd2("User: ".$user_cur->name."  stat: ".$user_cur->stat."  subst: ".$user_cur->subst);
1339
1340         if ($user_cur->is_active() == FALSE)
1341             continue;
1342
1343         if ($user_cur->lacc + EXPIRE_TIME_RD < ($curtime - $delta)) {
1344             // Auto logout dell'utente
1345             log_rd2("AUTO LOGOUT.".($user_cur->lacc + EXPIRE_TIME_RD)." curtime - delta ".($curtime - $delta));
1346
1347             $this->ghost_sess->push($curtime, $user_cur->sess, GHOST_SESS_REAS_TOUT);
1348             $user_cur->the_end = TRUE;
1349
1350             log_rd2("AUTO LOGOUT.");
1351             if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
1352                 log_auth($user_cur->sess, "Autologout session.");
1353
1354                 if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
1355                     $this->room_wakeup($user_cur);
1356                 else if ($user_cur->subst == 'standup')
1357                     $this->room_outstandup($user_cur);
1358                 else
1359                     log_rd2("LOGOUT FROM WHAT ???");
1360             }
1361         }
1362
1363         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < ($curtime - $delta)) { // lo rimettiamo in piedi
1364             if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
1365                 $this->room_wakeup($user_cur);
1366                 $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1367                 /* 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" */
1368                 $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);
1369                 $user_cur->step_inc();
1370             }
1371         }
1372     }
1373     log_rd2("GARBAGE UPDATED!");
1374
1375     $this->garbage_timeout = $curtime + GARBAGE_TIMEOUT;
1376     $ismod = TRUE;
1377
1378     $this->ghost_sess->garbage_manager($curtime);
1379
1380     $this->delay_mgr->lastcheck_set($curtime);
1381     return ($ismod);
1382   }
1383
1384   function show_room($user_step, $user)
1385   {
1386     GLOBAL $G_lang, $mlang_brisk;
1387     log_main("show_room: username: ".$user->name);
1388
1389     $ret = sprintf('gst.st = %d; ',  $user_step);
1390
1391     $prefs = Client_prefs::from_user($user);
1392     $ret .= sprintf('prefs_load(\'%s\', false, false);', json_encode($prefs));
1393
1394     if(false) {
1395         if ($user->flags & USER_FLAG_ISOLAUTH) {
1396             $ret .= 'list_set(\'isolation\', false, \''.$mlang_brisk['tit_onisol'][$G_lang].'\' ); ';
1397         }
1398         else if ($user->flags & USER_FLAG_LISTAUTH) {
1399             $ret .= 'list_set(\'auth\', false, \''.$mlang_brisk['tit_onauth'][$G_lang].'\' ); ';
1400         }
1401         else {
1402             $ret .= 'list_set(\'all\', false, \'\' ); ';
1403         }
1404     }
1405
1406     if ($user->subst == 'standup')
1407       $ret .= "tra.show(); ";
1408     else
1409       $ret .= "tra.hide(); ";
1410
1411     $ret .= sprintf('stat = "%s";',  $user->stat);
1412
1413     $ret .= root_welcome($user);
1414     if ($user->flags & USER_FLAG_DBFAILED) {
1415         $ret .= "gst.st = ".($user->step+1)."; ";
1416         $ret .= show_notify($mlang_brisk['db_failed'][$G_lang], 0, $mlang_brisk['btn_close'][$G_lang], 400, 140);
1417     }
1418
1419     $ret .= sprintf('subst = "%s";', $user->subst);
1420     $ret .= $user->myname_innerHTML();
1421
1422     for ($i = 0 ; $i < TABLES_N ; $i++) {
1423
1424       $ret .= $this->table_content($user, $i);
1425
1426       $ret .=  $this->table[$i]->act_content($user);
1427       if ($this->table[$i]->wag_own != -1)
1428         $ret .= sprintf('tra.add(%d, "%s: %s"); ', $i,  $this->user[$this->table[$i]->wag_own]->name, $this->table[$i]->wag_com);
1429       else
1430         $ret .= sprintf('tra.rem(%d); ', $i);
1431     }
1432     $ret .= $this->standup_content($user);
1433     $ret .= "setTimeout(preload_images, 0, g_preload_img_arr, g_imgct); ";
1434
1435     return ($ret);
1436   }
1437
1438
1439   function room_wakeup($user)
1440   {
1441     $table_idx = $user->table;
1442     $table = $this->table[$table_idx];
1443
1444     log_main("WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1445
1446     $curtime = time();
1447
1448     $from_table = ($user->stat == "table");
1449     if ($from_table) {
1450         log_main("WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1451
1452         for ($i = 0 ; $i < $table->player_n ; $i++) {
1453             $user_cur = $this->user[$table->player[$i]];
1454             log_main("PREIMPOST: INLOOP name: ".$user_cur->name);
1455
1456             if ($user->idx_get() != $table->player[$i]) {
1457                 $user_cur->stat_set("room");
1458                 $user_cur->subst = "sitdown";
1459                 $user_cur->laccwr = $curtime;
1460             }
1461             else if ($user->is_active()) {
1462                 $user_cur->stat_set("room");
1463                 $user_cur->subst = "standup";
1464                 $user_cur->laccwr = $curtime;
1465                 $user_cur->table = -1;
1466             }
1467         }
1468     }
1469     else {
1470         $user->stat_set("room");
1471         $user->subst = "standup";
1472         $user->laccwr = $curtime;
1473     }
1474
1475     $remove_wagon = FALSE;
1476     if($table->wag_own == $user->idx_get()) {
1477         $table->wag_reset($curtime);
1478         $remove_wagon = TRUE;
1479     }
1480
1481
1482     /* aggiorna l'array dei giocatori al tavolo. */
1483     $table->user_rem($this, $user);
1484
1485     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1486       $user_cur = $this->user[$i];
1487       if ($user_cur->is_active() == FALSE || $user_cur->stat != 'room') // is not active user or the stat isn't 'room'
1488         continue;
1489
1490       // log_main("VALORI: name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
1491
1492       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1493       if ($from_table && ($user_cur->table == $table_idx || $user->idx_get() == $i)) {
1494         $ret .= 'gst.st_loc++; xstm.stop(); window.onunload = null; window.onbeforeunload = null; document.location.assign("index.php");|';
1495         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
1496         log_main("DOCUMENT.index.php: from table");
1497       }
1498       else if ($user_cur->stat == "room") {
1499         log_main("DOCUMENT.index.php: from table");
1500
1501         $ret .= $this->table_content($user_cur, $table_idx);
1502         $ret .= $this->standup_content($user_cur);
1503
1504         // $ret .= table_act_content(FALSE, 0, $table_idx, $user->table, FALSE);
1505         $ret .= $table->act_content($user);
1506
1507         if ($user->idx_get() == $i) {
1508           // set the new status
1509           $ret .=  'subst = "standup"; tra.show(); ';
1510           // clean the action buttons in other tables
1511           for ($e = 0 ; $e < TABLES_N ; $e++) {
1512             if ($this->table[$e]->player_n < PLAYERS_N) {
1513               $ret .= $this->table[$e]->act_content($user);
1514             }
1515           }
1516         }
1517         else {
1518           $ret .= $table->act_content($user_cur);
1519         }
1520       }
1521       log_wr("ROOM_WAKEUP: ".$ret);
1522       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1523       $user_cur->step_inc();
1524     }
1525   }
1526
1527   function room_join_wakeup($user, $update_lacc = FALSE, $trans_delta)
1528   {
1529     $table_idx = $user->table;
1530     $table = $this->table[$table_idx];
1531
1532     log_main("JOIN_WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1533
1534     $curtime = time();
1535     $user_wup = array();
1536     $user_wup_n = 0;
1537     $user_tab = array();
1538     $user_tab_n = 0;
1539     log_main("JOIN WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1540
1541     for ($i = 0 ; $i < $table->player_n ; $i++) {
1542         $user_cur = $this->user[$table->player[$i]];
1543         log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1544         if ($user_cur->is_empty()) {
1545             continue;
1546         }
1547         if ($update_lacc == TRUE) {
1548             $user_cur->laccwr = $curtime;
1549         }
1550         log_main("cur: ".$user_cur->name."  subst: ".$user_cur->subst);
1551         if ($user_cur->subst == "shutdowned") {
1552             $user_cur->stat_set("room");
1553             $user_cur->subst = "sitdown";
1554         }
1555         else if ($user_cur->subst == "shutdowner") {
1556             $user_cur->stat_set("room");
1557             $user_cur->subst = "standup";
1558             $user_cur->table = -1;
1559             $user_wup[$user_wup_n++] = $user_cur;
1560
1561             $remove_wagon = FALSE;
1562             if($table->wag_own == $table->player[$i]) {
1563                 $remove_wagon = TRUE;
1564                 $table->wag_reset($curtime);
1565             }
1566         }
1567         $user_tab[$user_tab_n++] = $table->player[$i];
1568     }
1569
1570     for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
1571       $table->user_rem($this, $user_wup[$wup_idx]);
1572
1573     /* aggiorna l'array dei giocatori al tavolo. */
1574
1575     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1576       log_main("START LOOP");
1577       $user_cur = $this->user[$i];
1578       if ($user_cur->is_active() == FALSE || $user_cur->stat != 'room') { // is not active user or the stat isn't 'room'
1579         log_main("name: ".$user_cur->name."skip   subst: ".$user_cur->subst);
1580         continue;
1581       }
1582
1583       log_main("___");
1584       log_main("VALORI name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx);
1585
1586       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1587       if ($user_cur->stat == "room") {
1588         log_main("DOCUMENT.index.php from table");
1589
1590         $ret .= $this->table_content($user_cur, $table_idx);
1591         $ret .= $this->standup_content($user_cur);
1592
1593         $ret .= $table->act_content($user_cur);
1594
1595
1596         for ($tab_idx = 0 ; $tab_idx < $user_tab_n  ; $tab_idx++)
1597             if ($user_tab[$tab_idx] == $i)
1598                 break;
1599
1600         // for users that wakeup the room will be reconstructed by index_rd.php
1601         if ($tab_idx < $user_tab_n) {
1602           log_main("PRE show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1603
1604 //        ARRAY_POP DISABLED
1605 //           if ($trans_delta == 0)
1606 //             while (array_pop($user_cur->comm) != NULL);
1607
1608           $user_cur->trans_step = $user_cur->step + 1 + $trans_delta;
1609           $user_cur->comm[$user_cur->step % COMM_N] = "";
1610           $user_cur->step_inc();
1611           $user_cur->comm[$user_cur->step % COMM_N] = $this->show_room(($user_cur->step + 1), $user_cur);
1612           $user_cur->step_inc();
1613           log_main("POST show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1614
1615           continue;
1616         }
1617         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
1618
1619         log_main("JOIN_WAKEUP more");
1620
1621         $ret .= $table->act_content($user_cur);
1622
1623         log_main("JOIN_WAKEUP end more");
1624       }
1625       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
1626       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1627       $user_cur->step_inc();
1628     }
1629   }
1630
1631   function guarantee_show($user, $user_login, $dt)
1632   {
1633       GLOBAL $G_lang, $mlang_brisk, $G_base;
1634
1635       $user_code = -1;
1636       $ret = 0;
1637
1638       do {
1639           if ($user_login == "") {
1640               $ret = 1;
1641               break;
1642           }
1643           if (($bdb = BriskDB::create()) == FALSE) {
1644               $ret = 2;
1645               break;
1646           }
1647           if (($user_item = $bdb->getitem_bylogin($user_login, $user_code)) == FALSE) {
1648               $ret = 3;
1649               break;
1650           }
1651           if (($guar_item = $bdb->getitem_bycode($user_item->guar_code_get())) != FALSE) {
1652               $guar_login = $guar_item->login_get();
1653           }
1654           else {
1655               $guar_login = "";
1656           }
1657           $user_tos_vers = $user_item->tos_vers_get();
1658
1659           if (versions_cmp($user_tos_vers, "1.2") < 0) {
1660               $mesg = nickserv_msg($dt, sprintf($mlang_brisk['tos_old'][$G_lang], xcape($user_login)));
1661           }
1662           else if ($guar_login == "") {
1663               $mesg = nickserv_msg($dt, sprintf($mlang_brisk['gua_nfd'][$G_lang], xcape($user_login)));
1664           }
1665           else if ($guar_login == $user_login) {
1666               $mesg = nickserv_msg($dt, sprintf($mlang_brisk['gua_self'][$G_lang], xcape($user_login)));
1667           }
1668           else {
1669               $mesg = nickserv_msg($dt, sprintf($mlang_brisk['gua_info'][$G_lang],
1670                                                 xcape($user_login), xcape($guar_login)));
1671           }
1672       } while (0);
1673
1674       if ($ret > 0) {
1675           $mesg = nickserv_msg($dt, sprintf($mlang_brisk['gua_err'][$G_lang], $ret));
1676       }
1677
1678       $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ".$mesg;
1679       $user->step_inc();
1680
1681       return TRUE;
1682   }
1683
1684   function room_outstandup($user)
1685   {
1686     $this->room_sitdown($user, -1);
1687   }
1688
1689   function table_update($user)
1690   {
1691     log_main("table_update: pre - USER: ".$user->name);
1692
1693     $table_idx = $user->table;
1694
1695     if ($table_idx > -1)
1696       $table = $this->table[$table_idx];
1697
1698     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1699       $ret = "";
1700       $user_cur = $this->user[$i];
1701       if ($user_cur->is_active() == FALSE || $user_cur->stat != 'room') // is not active user or the stat isn't 'room'
1702           continue;
1703
1704       $ret = "gst.st = ".($user_cur->step+1)."; ";
1705       if ($table_idx > -1)
1706         $ret .= $this->table_content($user_cur, $table_idx);
1707
1708       if ($user->idx_get() == $i) {
1709           $ret .= $user->myname_innerHTML();
1710       }
1711       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1712       $user_cur->step_inc();
1713     }
1714
1715     log_main("table_update: post");
1716   }
1717
1718   function room_sitdown($user, $table_idx)
1719   {
1720       log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1721
1722       $train_app = "";
1723
1724       if ($table_idx > -1 && $table_idx < TABLES_N) {
1725           $table = $this->table[$table_idx];
1726
1727           // wagon shutdown
1728           if ($table->wag_own != -1 && $table->player_n == PLAYERS_N) {
1729               for ($i = 0 ; $i < TABLES_N ; $i++) {
1730                   if ($table->wag_own == $table->player[$i]) {
1731                       $train_app = sprintf("tra.rem(%d); ", $table_idx);
1732                       $table->wag_reset(time());
1733                       break;
1734                   }
1735               }
1736           }
1737       }
1738
1739       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1740           $ret = "";
1741           $user_cur = $this->user[$i];
1742           if ($user_cur->is_active() == FALSE || $user_cur->stat != 'room') // is not active user or the stat isn't 'room'
1743               continue;
1744
1745           $ret = "gst.st = ".($user_cur->step+1)."; ".$train_app;
1746           if ($table_idx > -1)
1747               $ret .= $this->table_content($user_cur, $table_idx);
1748           $ret .= $this->standup_content($user_cur);
1749
1750           if ($user->idx_get() == $i) {
1751               $ret .=  'subst = "sitdown"; tra.hide(); ';
1752               // clean the action buttons in other tables
1753               for ($e = 0 ; $e < TABLES_N ; $e++) {
1754                   $ret .= $this->table[$e]->act_content($user_cur);
1755               }
1756           }
1757           else if ($table_idx > -1) {
1758               if ($table->player_n == PLAYERS_N) {
1759
1760                   $ret .= $table->act_content($user_cur);
1761               }
1762           }
1763           $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1764           $user_cur->step_inc();
1765       }
1766   }
1767
1768   function kickuser($user, $out_reas)
1769   {
1770       $curtime = time();
1771
1772       fprintf(STDERR, "MOP: GHOST_SESS: %d\n", $out_reas);
1773
1774       $this->ghost_sess->push($curtime, $user->sess, $out_reas);
1775
1776       fprintf(STDERR, "MOP: status out: %s %s %d\n", $user->stat, $user->subst, $user->idx);
1777       if ($user->stat == 'table' && $user->subst != 'sitdown') {
1778           $bin5 = &$this->match[$user->table];
1779           $user_bin5 = &$bin5->user[$user->table_pos];
1780           fprintf(STDERR, "MOP: status in: %s %s %d\n", $user_bin5->stat, $user_bin5->subst, $user_bin5->idx);
1781           $bin5->table_wakeup($user_bin5);
1782           $user->the_end = TRUE;
1783           $this->room_wakeup($user);
1784           return;
1785       }
1786
1787       if ($user->stat == 'table' || $user->stat == 'room') {
1788           $user->the_end = TRUE;
1789           if ($user->subst == 'sitdown' || $user->stat == 'table') {
1790               $this->room_wakeup($user);
1791           }
1792           else if ($user->subst == 'standup') {
1793               fprintf(STDERR, "MOP: KICK here [%s]\n", btrace_line(debug_backtrace()));
1794               $this->room_outstandup($user);
1795           }
1796           else {
1797               log_rd2("LOGOUT FROM WHAT ???");
1798           }
1799       }
1800   }
1801
1802   function kickuser_by_name($name, $out_reas)
1803   {
1804       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1805           $user_out = $this->user[$i];
1806           if (strcmp($user_out->name, $name) == 0) {
1807               return ($this->kickuser($user_out, $out_reas));
1808           }
1809       }
1810       return FALSE;
1811   }
1812
1813   function kickuser_by_sess($sess, $out_reas)
1814   {
1815       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1816           $user_out = $this->user[$i];
1817           if (strcmp($user_out->sess, $sess) == 0) {
1818               return ($this->kickuser($user_out, $out_reas));
1819           }
1820       }
1821       return FALSE;
1822   }
1823
1824   function kickuser_by_idx($idx, $out_reas)
1825   {
1826       $user_out = $this->user[$idx];
1827       return ($this->kickuser($user_out, $out_reas));
1828   }
1829
1830   function chatt_send($user, $mesg)
1831   {
1832     GLOBAL $G_base, $G_alarm_passwd, $mlang_brisk, $G_lang;
1833     $only_you = FALSE;
1834
1835     // common settings
1836     $msg = mb_substr($mesg, 6, 128, "UTF-8");
1837     $curtime = time();
1838     $dt = date("H:i ", $curtime);
1839     $target = "";
1840
1841     //
1842     //  Compute actions
1843     //
1844
1845     $to_user     = FALSE;
1846     $to_all      = FALSE;
1847     $to_room     = FALSE;
1848     $to_tabl     = FALSE;
1849     $is_normchat = FALSE;
1850     /* for old isolation management $is_ticker   = FALSE; */
1851     $update_room = FALSE;
1852
1853     if (strcmp($msg,  "/tav") == 0 ||
1854         strncmp($msg, "/tav ", 5) == 0) {
1855       do {
1856         if ($user->stat != 'room' || $user->subst != 'sitdown') {
1857           /* 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>" */
1858           $msg = $mlang_brisk['tickmust'][$G_lang];
1859           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1860
1861           break;
1862         }
1863
1864         $table = $this->table[$user->table];
1865
1866         if ($table->wag_own != -1) {
1867           // MLANG <br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br>
1868           $msg = $mlang_brisk['tickjust'][$G_lang];
1869           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1870
1871           break;
1872         }
1873
1874         $dtime = $curtime - $table->wag_tout;
1875         if ($dtime  < EXPIRE_TIME_WAG) {
1876           // MLANG - <br>Il messaggio di segnalazione del tavolo<br>&egrave; disattivato ancora per %d second%s.<br><br>
1877           $msg = sprintf($mlang_brisk['tickwait'][$G_lang],
1878                          EXPIRE_TIME_WAG - $dtime, (EXPIRE_TIME_WAG - $dtime == 1 ? ($G_lang == 'en' ? "" : "o") : ($G_lang == 'en' ? "s" : "i")));
1879           $to_user = show_notify($msg, 0, $mlang_brisk['btn_close'][$G_lang] , 400, 100);
1880
1881           break;
1882         }
1883
1884         $msg = substr($msg, 5);
1885
1886         $table->wag_set($user->idx_get(), $msg);
1887         $to_user = sprintf('tra.add(%d, "%s");', $user->table, xcape(sprintf("%s: %s", $user->name, $msg)));
1888         $to_room = $to_user;
1889         /* for old isolation management $is_ticker = TRUE; */
1890       } while (0);
1891     } // /tav chat command
1892     // just for development use currently
1893     else if (FALSE && strncmp($msg, "/out ", 5) == 0) {
1894         fprintf(STDERR, "MOP OUT\n");
1895         $target = substr($msg, 5);
1896         $this->kickuser_by_name($target, GHOST_SESS_REAS_ANON);
1897     }
1898     else if (strncmp($msg, "/alarm ", 7) == 0) {
1899       if (strncmp($msg, "/alarm to ", 10) == 0) {
1900         $sp_pos = strpos($msg, " ", 10);
1901         $target = substr($msg, 10, $sp_pos - 10);
1902         $alarm_check = "/alarm to ".$target." ".$G_alarm_passwd." ";
1903       }
1904       else {
1905         $target = "";
1906         $alarm_check = "/alarm ".$G_alarm_passwd." ";
1907       }
1908       do {
1909         if (strncmp($msg, $alarm_check, strlen($alarm_check)) != 0) {
1910           /* MLANG: "<br>La password digitata non &egrave; corretta.<br><br>" */
1911           $msg = $mlang_brisk['alarpass'][$G_lang];
1912           $to_user = show_notify($msg, 0, $mlang_brisk['btn_close'][$G_lang], 400, 100);
1913
1914           break;
1915         }
1916
1917         /* MLANG: "Alarm <b>%s</b> inviato a <b>%s</b>." */
1918         $prestr = sprintf($mlang_brisk['alarret'][$G_lang], xcape(substr($msg, strlen($alarm_check))),
1919                            ($target == "" ? $mlang_brisk['tit_all'][$G_lang] : xcape($target)) );
1920         $to_user = nickserv_msg($dt, $prestr);
1921
1922         $msg = sprintf("<br><b>%s<br><br>%s</b><br><br>",
1923                        $dt.NICKSERV, xcape(substr($msg, strlen($alarm_check))));
1924         /* MLANG: "chiudi" */
1925         $to_all = show_notify($msg, 0, $mlang_brisk['btn_close'][$G_lang], 400, 120);
1926       } while (0);
1927     } // /alarm chat command
1928     else if (strncmp($msg, "/listen ", 8) == 0) {
1929       $arg = substr($msg, 8);
1930
1931       if (strcasecmp($arg, "isolation") == 0) {
1932         $flags_old = 0;
1933         if ($user->stat == 'room' && $user->subst == 'sitdown' &&
1934             $user->table >= TABLES_AUTH_N) {
1935           $to_user = nickserv_msg($dt, $mlang_brisk['listmust'][$G_lang]);
1936
1937         }
1938         else {
1939           $user->flags &= ~USER_FLAG_MAP_AUTH;
1940           $user->flags |= USER_FLAG_ISOLAUTH;
1941           $to_user = 'list_set(\'isolation\', true, \''.$mlang_brisk['tit_onisol'][$G_lang].'\'); ';
1942         }
1943       }
1944       else if (strcasecmp($arg, "auth") == 0) {
1945         $flags_old = $user->flags;
1946         $user->flags &= ~USER_FLAG_MAP_AUTH;
1947         $user->flags |= USER_FLAG_LISTAUTH;
1948         $to_user = 'list_set(\'auth\', true, \''.$mlang_brisk['tit_onauth'][$G_lang].'\'); ';
1949       }
1950       else {
1951         $flags_old = $user->flags;
1952         $user->flags &= ~USER_FLAG_MAP_AUTH;
1953         $to_user = 'list_set(\'all\', true, \'\'); ';
1954
1955       }
1956       // if from isolation redraw standup area
1957       if (($flags_old ^ $user->flags) & USER_FLAG_ISOLAUTH) {
1958         $to_user .= 'standup_data_old = null; '.$this->standup_content($user);
1959
1960       }
1961     }
1962     else if (strcmp($msg, "/authreq") == 0) {
1963         if ($user->is_cert()) {
1964             $to_user = sprintf('authbox(300,200);');
1965         }
1966         else {
1967             /* 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." */
1968             $to_user = nickserv_msg($dt, $mlang_brisk['authmust'][$G_lang]);
1969         }
1970     }
1971     else if (strncmp($msg, "/mesgtoadm", 8) == 0) {
1972         if ($user->is_auth()) {
1973         $to_user = sprintf('mesgtoadmbox(500,300);');
1974       }
1975       else {
1976         /* MLANG: "<b>Per inviare un messaggio devi essere autenticato.</b>" */
1977         $to_user = nickserv_msg($dt, $mlang_brisk['mesgmust'][$G_lang]);
1978       }
1979     }
1980     else if (FALSE && strncmp($msg, "/nick ", 6) == 0) {
1981       log_main("chatt_send BEGIN");
1982
1983       do {
1984         if (($name_new = validate_name(substr($msg, 6))) == FALSE) {
1985           $to_user = nickserv_msg($dt, $mlang_brisk['nickmust'][$G_lang]);
1986           break;
1987         }
1988
1989         $msg = "COMMAND ".$msg;
1990         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1991           $user_cur = $this->user[$i];
1992
1993           if ($user_cur->is_active() == FALSE)
1994             continue;
1995           if (strcasecmp($user_cur->name,$name_new) == 0)
1996             break;
1997           }
1998         if ($i <  MAX_PLAYERS) {
1999           $prestr = sprintf($mlang_brisk['nickdupl'][$G_lang], xcape($name_new));
2000           $to_user = nickserv_msg($dt, $prestr);
2001           break;
2002         }
2003
2004         /* 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>" */
2005         if ($user->is_auth()) {
2006           if (strcasecmp($user->name,$name_new) != 0) {
2007              if (( ($user->flags & USER_FLAG_MAP_AUTH) != USER_FLAG_ISOLAUTH) &&
2008                 ($user->subst == 'standup' ||
2009                  ($user->subst != 'standup' && $this->table[$user->table]->auth_type == TABLE_AUTH_TY_PUBL)
2010                  )
2011                 ) {
2012               $user->flags &= ~(USER_FLAG_AUTH | USER_FLAG_TY_ALL); // Remove auth if name changed
2013               for ($i = 0 ; $i < TABLES_N ; $i++) {
2014                 $to_user .= $this->table[$i]->act_content($user);
2015               }
2016             }
2017             else {
2018               $to_user = nickserv_msg($dt, $mlang_brisk['authchan'][$G_lang]);
2019               break;
2020             }
2021           }
2022         }
2023         $user->name = $name_new; // OK - nick changed
2024         /* se nome gia' in uso, segnala cosa potrebbe capitare */
2025         if ( ! $user->is_auth() ) {
2026             if (($bdb = BriskDB::create()) != FALSE) {
2027                 $bdb->users_load();
2028                 /* 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>" */
2029                 if ($bdb->login_exists($name_new)) {
2030                     $prestr = sprintf($mlang_brisk['nickjust'][$G_lang], xcape($name_new));
2031                     $to_user .= nickserv_msg($dt, $prestr);
2032                 }
2033             }
2034         }
2035
2036         log_main("chatt_send start set");
2037
2038         $update_room = TRUE;
2039       } while (0);
2040     } // nick chat command
2041     else if (strncmp($msg, "/guar ", 6) == 0 || $msg == "/guar") {
2042         $guar_user = substr($msg, 6);
2043
2044         $this->guarantee_show($user, $guar_user, $dt);
2045     }
2046     else if (strncmp($msg, "/st ", 4) == 0) {
2047       log_main("chatt_send BEGIN");
2048
2049       do {
2050         $st_str = substr($msg, 4);
2051
2052         if (strcasecmp($st_str, "normale") == 0) {
2053           $st = USER_FLAG_S_NORM;
2054         }
2055         else if (strcasecmp($st_str, "pausa") == 0) {
2056           $st = USER_FLAG_S_PAU;
2057         }
2058         else if (strcasecmp($st_str, "fuori") == 0) {
2059           $st = USER_FLAG_S_OUT;
2060         }
2061         else if (strcasecmp($st_str, "cane") == 0) {
2062           $st = USER_FLAG_S_DOG;
2063         }
2064         else if (strcasecmp($st_str, "cibo") == 0) {
2065           $st = USER_FLAG_S_EAT;
2066         }
2067         else if (strcasecmp($st_str, "lavoro") == 0) {
2068           $st = USER_FLAG_S_WRK;
2069         }
2070         else if (strcasecmp($st_str, "sigaretta") == 0) {
2071           $st = USER_FLAG_S_SMK;
2072         }
2073         else if (strcasecmp($st_str, "presente") == 0) {
2074           $st = USER_FLAG_S_EYE;
2075         }
2076         else if (strcasecmp($st_str, "coniglio") == 0) {
2077           $st = USER_FLAG_S_RABB;
2078         }
2079         else if (strcasecmp($st_str, "calcio") == 0) {
2080           $st = USER_FLAG_S_SOCC;
2081         }
2082         else if (strcasecmp($st_str, "pupo") == 0) {
2083           $st = USER_FLAG_S_BABY;
2084         }
2085         else if (strcasecmp($st_str, "pulizie") == 0) {
2086           $st = USER_FLAG_S_MOP;
2087         }
2088         else if (strcasecmp($st_str, "babbo") == 0) {
2089           $st = USER_FLAG_S_BABBO;
2090         }
2091         else if (strcasecmp($st_str, "renna") == 0) {
2092           $st = USER_FLAG_S_RENNA;
2093         }
2094         else if (strcasecmp($st_str, "pupazzo") == 0) {
2095           $st = USER_FLAG_S_PUPAZ;
2096         }
2097         else if (strcasecmp($st_str, "vischio") == 0) {
2098           $st = USER_FLAG_S_VISCH;
2099         }
2100         else {
2101           /* MLANG: "Questo stato non esiste." */
2102           $to_user = nickserv_msg($dt, $mlang_brisk['statunkn'][$G_lang]);
2103           break;
2104         }
2105
2106         log_main("chatt_send start set");
2107         if (($user->flags & USER_FLAG_S_ALL) != $st) {
2108           $update_room = TRUE;
2109           $user->flags = ($user->flags & ~USER_FLAG_S_ALL) | $st;
2110         }
2111       } while (0);
2112     } // nick chat command
2113
2114     else { // normal chat line
2115       $is_normchat = TRUE;
2116       if (CHAT_ENABLED && $curtime < ($user->chat_ban + $user->chat_dlt)) {
2117         $only_you = TRUE;
2118         $user->chat_dlt = $user->chat_dlt * 2;
2119         if ($user->chat_dlt > 120)
2120           $user->chat_dlt = 120;
2121       }
2122       else if ($user->chat_lst == $msg)
2123         $only_you = TRUE;
2124       else if (CHAT_ENABLED && $curtime - $user->chattime[($user->chat_cur + 1) % CHAT_N] < CHAT_ILL_TIME) {
2125         $user->chat_ban = $curtime;
2126         $user->chat_dlt = 5;
2127         $only_you = TRUE;
2128       }
2129       else {
2130         $user->chat_ban = 0;
2131         $user->chat_dlt = 0;
2132       }
2133
2134       if ($only_you) {
2135         $to_user = sprintf('chatt_sub("%s",[%d,"%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape("== chat ban =="));
2136       }
2137       else {
2138           if ( TRUE && (! $user->is_auth()) ) {
2139               $to_user = nickserv_msg($dt, xcape("Visto l'elevato numero di molestatori che ultimamente hanno preso dimora su Brisk abbiamo deciso"));
2140               $to_user .= nickserv_msg($dt, xcape("di disattivare temporaneamente la chat in room per i non registrati, non ce ne vogliate e buone feste."));
2141               if (FALSE) {
2142                   $aug_head = array("Tanti", "Tantissimi", "Un enormità", "Un milione", "Un' esagerazione");
2143                   $aug_body = array("a tutti gli utenti", "a tutti gli uomini", "a tutte le donne", "a tutti gli utenti");
2144                   $aug_tail = array("di Brisk", "del sito", "della ciurma", "della comitiva", "del gruppo");
2145
2146                   $auguri = sprintf("%s auguri %s %s.",
2147                                     $aug_head[mt_rand(0, count($aug_head)-1)],
2148                                     $aug_body[mt_rand(0, count($aug_body)-1)],
2149                                     $aug_tail[mt_rand(0, count($aug_tail)-1)]);
2150
2151                   $to_room = sprintf('chatt_sub("%s",[%d,"%s"],"%s");', $dt, $user->flags, xcape($user->name),
2152                                      xcape($auguri));
2153               }
2154           }
2155           else {
2156               $to_user = sprintf('chatt_sub("%s",[%d,"%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape($msg));
2157               // temporary silentiation for troll (will became array check)
2158               // if (strcasecmp($user->name,'JackRokka') != 0 && $user->sess != '47ea653f602e8')
2159               $to_room = $to_user;
2160           }
2161       }
2162
2163       log_legal($curtime, $user->ip, $user,
2164                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$msg);
2165
2166       $user->chat_lst = "$msg";
2167       $user->chattime[$user->chat_cur % CHAT_N] = $curtime;
2168       $user->chat_cur++;
2169     }
2170
2171     if ($to_all) {
2172       $to_room = $to_all;
2173       $to_tabl = $to_all;
2174     }
2175
2176     //
2177     //  Output to clients
2178     //
2179
2180     if ($to_user != FALSE) {
2181       $user->comm[$user->step % COMM_N] =  "gst.st = ".($user->step+1)."; ";
2182       $user->comm[$user->step % COMM_N] .= $to_user;
2183       $user->step_inc();
2184     }
2185
2186     if ($to_room != FALSE) {
2187       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2188         $user_cur = $this->user[$i];
2189         if ($target != "" && $user_cur->name != $target)
2190           continue;
2191         if ($user_cur->is_active() == FALSE // is not active user
2192             || $user_cur->stat == 'table'   // or stat is 'table'
2193             || $user->idx_get() == $i)      // or the $user idx is equal to current var
2194           continue;
2195
2196         if ($is_normchat == TRUE) {
2197           // use MAP_AUTH to check if auth or isolation
2198           if ($user_cur->flags & USER_FLAG_MAP_AUTH) {
2199               if ( ! $user->is_auth() ) {
2200                   continue;
2201               }
2202           }
2203         }
2204         /*
2205         else if ($is_ticker) {
2206           if (($user_cur->flags & USER_FLAG_MAP_AUTH) == USER_FLAG_ISOLAUTH) {
2207             if ($user->table >= TABLES_AUTH_N)
2208               continue;
2209           }
2210         }
2211         */
2212         $user_cur->comm[$user_cur->step % COMM_N] =  "gst.st = ".($user_cur->step+1)."; ";
2213         $user_cur->comm[$user_cur->step % COMM_N] .= $to_room;
2214         $user_cur->step_inc();
2215       }
2216     }
2217
2218     if ($to_tabl) {
2219         // FIXME BRISK4: include for each kind of table
2220         require_once("${G_base}briskin5/Obj/briskin5.phh");
2221         // Before all align times with table timeout
2222         for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
2223             if (isset($this->match[$table_idx])) {
2224                 $bin5 = $this->match[$table_idx];
2225
2226                 $bin5_table = $bin5->table[0];
2227                 for ($i = 0 ; $i < $bin5_table->player_n ; $i++) {
2228                     // stat must be "table" by definition
2229                     $bin5_user = $bin5->user[$i];
2230
2231                     if ($target != "" && $bin5_user->name != $target)
2232                         continue;
2233                     log_main("writa: ".$user_mesg);
2234                     $bin5_user->comm[$bin5_user->step % COMM_N] = "gst.st = ".($bin5_user->step+1)."; ";
2235                     $bin5_user->comm[$bin5_user->step % COMM_N] .= $to_tabl;
2236                     $bin5_user->step_inc();
2237                 }
2238             } // if (isset($this->match
2239         } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
2240     } // if ($to_tabl == true ...
2241
2242     if ($update_room) {
2243       if ($user->stat == 'room' && $user->subst == 'standup') {
2244         $this->standup_update($user);
2245       }
2246       else if ($user->stat == 'room' && $user->subst == 'sitdown') {
2247         log_main("chatt_send pre table update");
2248         $this->table_update($user);
2249         log_main("chatt_send post table update");
2250       }
2251     } // if ($update_room ...
2252
2253     return;
2254   } // function chatt_send( ...
2255
2256   function get_user($sess, &$idx)
2257   {
2258       GLOBAL $PHP_SELF;
2259
2260       if (validate_sess($sess)) {
2261           for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2262               if ($this->user[$i]->is_empty())
2263                   continue;
2264               if (strcmp($sess, $this->user[$i]->sess) == 0) {
2265                   // find it
2266                   $idx = $i;
2267                   $ret = $this->user[$i];
2268                   return ($ret);
2269               }
2270           }
2271           log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
2272           // for ($i = 0 ; $i < MAX_PLAYERS ; $i++)
2273           // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
2274       }
2275       else {
2276           log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
2277       }
2278
2279       return (FALSE);
2280   }
2281
2282   /*
2283    * function add_user(&$brisk, &$sess, &$idx, $name, $pass, $ip, $header, $cookie)
2284    *
2285    * RETURN VALUE:
2286    *   if ($idx >  -1    && ret == FALSE)  =>  duplicated nick
2287    *   if ($idx == -2    && ret == FALSE)  =>  invalid name
2288    *   if ($idx == -3    && ret == FALSE)  =>  wrong password
2289    *   if ($idx == -1    && ret == FALSE)  =>  no space left
2290    *   if ($idx ==  0    && ret == user)   =>  SUCCESS
2291    *   if ($idx == -($idx + 1) && ret == user)   =>  SUCCESS (but the login exists in the auth db)
2292    */
2293
2294   function add_user(&$sess, &$idx, $name, $pass, $ip, $header, $cookie)
2295   {
2296     GLOBAL $G_base;
2297
2298     $idx = 0;
2299
2300     $authenticate = FALSE;
2301     $user_type    = 0;
2302     $login_exists = FALSE;
2303     $ghost = -1;
2304     $ghost_auth = FALSE;
2305     $idx = -1;
2306     $idfree = -1;
2307     $code = FALSE;
2308
2309     if (($name_new = validate_name($name)) == FALSE) {
2310       $idx = -2;
2311       return (FALSE);
2312     }
2313
2314     log_auth("XXX", sprintf("ARRIVA: [%s] pass:[%s]", $sess, ($pass == FALSE ? "FALSE" : $pass)));
2315     if (validate_sess($sess) == FALSE)
2316       $sess = "";
2317
2318     /* if pass != FALSE verify the login with pass */
2319     log_auth("XXX", "auth1");
2320
2321     if (($bdb = BriskDB::create()) != FALSE) {
2322         $bdb->users_load();
2323         if ($pass != FALSE) { // TODO: here add a method to $bdb to check if the db is available.
2324             log_auth("XXX", "auth2");
2325             $authenticate = $bdb->login_verify($name_new, $pass, $code);
2326             log_auth("XXX", "authenticate: ".($authenticate != FALSE ? "TRUE" : "FALSE"));
2327
2328             if ($authenticate != FALSE) {
2329                 $user_type = $authenticate->type_get();
2330             }
2331             else {
2332                 $idx = -3;
2333                 return (FALSE);
2334             }
2335         }
2336         else {
2337             $login_exists =  $bdb->login_exists($name_new);
2338         }
2339     }
2340     else {
2341         // if db is down, send a warning and verify only current users
2342         // no actions at this moment
2343     }
2344     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2345         /* free user ? */
2346         if ($this->user[$i]->is_empty()) {
2347             if ($idfree == -1) {
2348                 $idfree = $i;
2349             }
2350             continue;
2351         }
2352         if (strcmp($sess, $this->user[$i]->sess) == 0) {
2353             if ($idx == -1) {
2354                 $idx = $i;
2355             }
2356         }
2357         if (strcasecmp($this->user[$i]->name, $name_new) == 0) {
2358             if ($authenticate != FALSE) {
2359                 $ghost = $i;
2360                 $ghost_auth = $this->user[$i]->is_auth();
2361             }
2362             else {
2363                 $idx = $i;
2364                 break;
2365             }
2366         }
2367     }
2368     if ($idx == -1)
2369       $idx = $idfree;
2370
2371     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
2372
2373     /* there is another user logged with your account and you and him have authenticated => new user
2374        get the session of the old user */
2375     if ($ghost > -1 && $ghost_auth && ($authenticate != FALSE)) {
2376       /* swap session */
2377
2378       $ghost_user = $this->user[$ghost];
2379       $curtime = time();
2380       $this->ghost_sess->push($curtime, $ghost_user->sess, GHOST_SESS_REAS_ANOT);
2381       $ghost_user->comm[$ghost_user->step % COMM_N] = "";
2382       $ghost_user->step_inc();
2383       if ($sess == "") {
2384         $sess = uniqid("");
2385         $ghost_user->sess = $sess;
2386       }
2387       else {
2388         $ghost_user->sess = $sess;
2389       }
2390
2391       // If user at the table we need to update the table data too
2392       $table_idx = $ghost_user->table;
2393       if ($ghost_user->stat == "table" && $this->table[$table_idx]->player_n == PLAYERS_N) {
2394           require_once("${G_base}briskin5/Obj/briskin5.phh");
2395           if (isset($this->match[$table_idx])) {
2396               $bin5 = $this->match[$table_idx];
2397
2398               if ($bin5->the_end != TRUE) {
2399                   $bin5->user[$ghost_user->table_pos]->comm[$bin5->user[$ghost_user->table_pos]->step % COMM_N] = "";
2400                   $bin5->user[$ghost_user->table_pos]->step_inc();
2401                   $bin5->user[$ghost_user->table_pos]->sess = $sess;
2402               }
2403           }
2404       }
2405
2406       $idx = $ghost;
2407       if (defined('CURL_DE_SAC_VERS')) {
2408           brisk_cds_execute($this, $ghost, $idx, $sess, $ip, $authenticate, $header);
2409       }
2410       return ($this->user[$ghost]);
2411     }
2412     else if ($idx != -1 && $i == MAX_PLAYERS) {
2413       /* SUCCESS */
2414       $curtime = time();
2415       if ($sess == "") {
2416         $sess = uniqid("");
2417         $this->user[$idx]->sess = $sess;
2418       }
2419       else {
2420         $this->user[$idx]->sess = $sess;
2421       }
2422       $this->user[$idx]->name = $name_new; // OK - add new user
2423       $this->user[$idx]->stat_set("room");
2424       $this->user[$idx]->step_set(0);
2425       while (array_pop($this->user[$idx]->comm) != NULL);
2426       $this->user[$idx]->subst = "standup";
2427       $this->user[$idx]->lacc =   $curtime;
2428       $this->user[$idx]->laccwr = $curtime;
2429       $this->user[$idx]->bantime = 0;
2430       $this->user[$idx]->ip = $ip;
2431
2432       $this->user[$idx]->rec = $authenticate;
2433       $this->user[$idx]->flags = $user_type;
2434       $this->user[$idx]->flags |= ($authenticate != FALSE ? USER_FLAG_AUTH : 0x00);
2435       $this->user[$idx]->flags |= ( ($pass != FALSE && $bdb == FALSE) ? USER_FLAG_DBFAILED : 0x00);
2436       log_auth("XXX", sprintf("FLAGS: [%x]", $this->user[$idx]->flags));
2437
2438       if ($authenticate != FALSE) {
2439           $this->user[$idx]->code = $authenticate->code_get();
2440           if (0 == 1) {
2441               // all this part is included in the db server
2442               $this->user[$idx]->flags |= USER_FLAG_LISTAUTH;
2443
2444               if (isset($cookie['CO_list'])) {
2445                   fprintf(STDERR, "QQ: %s CO_list: [%s]\n", __FUNCTION__, $cookie['CO_list']);
2446                   if (strcmp($cookie['CO_list'], "auth") == 0) {
2447                       $this->user[$idx]->flags &= ~USER_FLAG_MAP_AUTH;
2448                       $this->user[$idx]->flags |= USER_FLAG_LISTAUTH;
2449                   }
2450                   if (strcmp($cookie['CO_list'], "isolation") == 0) {
2451                       $this->user[$idx]->flags &= ~USER_FLAG_MAP_AUTH;
2452                       $this->user[$idx]->flags |= USER_FLAG_ISOLAUTH;
2453                   }
2454                   else {
2455                       $this->user[$idx]->flags &= ~USER_FLAG_MAP_AUTH;
2456                   }
2457               }
2458           }
2459           else {
2460               fprintf(STDERR, "QQ: CO_list not set flags: %x\n", __FUNCTION__, $this->user[$idx]->flags);
2461           }
2462       }
2463       fprintf(STDERR, "QQ %s: flag %x\n", __FUNCTION__, $this->user[$idx]->flags);
2464       if ($ghost > -1) {
2465         log_main("ghost: rename!");
2466         $ghost_user = $this->user[$ghost];
2467
2468         if ($ghost_auth == FALSE) {
2469           for ($sfx = 1 ; $sfx <= MAX_PLAYERS ; $sfx++) {
2470             $ghostname = 'ghost'.$sfx;
2471             for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2472               if (strcmp("", $this->user[$i]->sess) == 0)
2473                 continue;
2474
2475               if (strcasecmp($this->user[$i]->name, $ghostname) == 0) {
2476                 $ghostname = '';
2477                 break;
2478               }
2479             }
2480             if ($ghostname != '')
2481               break;
2482           }
2483
2484           $ghost_user->name = $ghostname;
2485
2486           if ($ghost_user->stat == 'room' && $ghost_user->subst == 'standup') {
2487             $this->standup_update($ghost_user);
2488           }
2489           else {
2490             log_main("chatt_send pre table update");
2491             $this->table_update($ghost_user);
2492           log_main("chatt_send post table update");
2493           }
2494         } // if ($ghost_auth == FALSE
2495         else {
2496           // FIXME: cacciare il vecchio utente room && table (if needed)
2497           $ghost_user->the_end = TRUE;
2498           $ghost_user->lacc = 0;
2499           $this->garbage_manager(TRUE);
2500         }
2501       } //  if ($ghost > -1) {
2502
2503       $real_idx = $idx;
2504       if ($login_exists)
2505         $idx = -($idx + 1);
2506       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));
2507
2508       $ret = $this->user[$real_idx];
2509       if (defined('CURL_DE_SAC_VERS')) {
2510           brisk_cds_execute($this, $ghost, $real_idx, $sess, $ip, $authenticate, $header);
2511       }
2512       return ($ret);
2513     }
2514
2515     return (FALSE);
2516   }
2517
2518   function standup_update($user)
2519   {
2520     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
2521       $user_cur = $this->user[$i];
2522       if ($user_cur->is_active() == FALSE)
2523         continue;
2524
2525       log_main("STANDUP START: ".$user_cur->stat);
2526
2527       if ($user_cur->stat == 'room') {
2528         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".$this->standup_content($user_cur);
2529         if ($user->idx_get() == $i) {
2530           $user_cur->comm[$user_cur->step % COMM_N] .= $user->myname_innerHTML();
2531         }
2532         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
2533
2534         $user_cur->step_inc();
2535       }
2536     }
2537   }
2538
2539   function dump_data()
2540   {
2541       $brisk_ser = serialize($this);
2542       $brisk_ser_len = mb_strlen($brisk_ser, "ASCII");
2543       if (file_put_contents($this->crystal_filename, $brisk_ser) == $brisk_ser_len) {
2544           return (TRUE);
2545       }
2546
2547       return (FALSE);
2548   }
2549
2550   function standup_content($user)
2551   {
2552     $ret = "";
2553
2554     if ($user->stat != 'room')
2555       return;
2556
2557     $content = ' j_stand_cont( [ ';
2558
2559     $user_cur_id = $user->idx_get();
2560     for ($i = 0 , $ct = 0 ; $i < MAX_PLAYERS ; $i++) {
2561         if ($this->user[$i]->is_active() == FALSE // is not active user
2562             || $this->user[$i]->stat != "room"    // or the stat isn't 'room'
2563             || $this->user[$i]->name == "")       // or the name is empty, happens when user is reset (TODO: check it)
2564         continue;
2565
2566       $flags = $this->user[$i]->flags;
2567
2568       // sql record exists AND last donate > 2013-01-01
2569       if ($this->user[$i]->is_supp_custom()) {
2570           $supp_comp_s = sprintf(', "%s"', $this->user[$i]->rec->supp_comp_get());
2571       }
2572       else {
2573           $supp_comp_s = '';
2574       }
2575
2576       if ($this->user[$i]->subst == "standup") {
2577           if ($user_cur_id == $i) {
2578               $flags |= 1;
2579           }
2580
2581           $content .= sprintf('%s[ %d, "%s"%s ]',($ct > 0 ? ', ' : ''), $flags,
2582                               xcape($this->user[$i]->name), $supp_comp_s);
2583           $ct++;
2584       }
2585     }
2586     $content .= ' ]);';
2587
2588     return ($content);
2589   }
2590
2591   function table_content($user, $table_idx)
2592   {
2593     $content = "";
2594     $ret = "";
2595     // TODO
2596     //
2597     //   Si possono usare i dati nella classe table
2598     //
2599
2600     $sess = $user->sess;
2601     $table = $this->table[$table_idx];
2602
2603     if ($user->stat != 'room')
2604       return;
2605
2606     $user_cur_id = $user->idx_get();
2607     $content = "[ ";
2608     for ($i = 0 ; $i < $table->player_n ; $i++) {
2609         $user_cur = $this->user[$table->player[$i]];
2610
2611         $flags = $user_cur->flags;
2612
2613         if ($user_cur_id == $table->player[$i])
2614             $flags |= 1;
2615
2616         log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2617         if ($user_cur->is_supp_custom())
2618             $supp_comp_s = sprintf(', "%s"', $user_cur->rec->supp_comp_get());
2619         else
2620             $supp_comp_s = '';
2621
2622         $content .= sprintf('%s[ %d, "%s"%s ]',($i == 0 ? '' : ', '), $flags,
2623                             xcape($user_cur->name), $supp_comp_s);
2624     }
2625
2626     $content .= ' ]';
2627
2628     $ret .= sprintf('j_tab_cont(%d, %s);', $table_idx, $content);
2629
2630     return ($ret);
2631   }
2632
2633   function request_mgr(&$s_a_p, $header, &$header_out, &$new_socket, $path, $addr, $get, $post, $cookie)
2634   {
2635       GLOBAL $G_ban_list, $G_black_list, $G_cloud_smasher;
2636
2637       printf("NEW_SOCKET (root): %d PATH [%s]\n", intval($new_socket), $path);
2638
2639       fprintf(STDERR, "\n\n\n PRE_BLACK [%s]\n\n\n", $addr);
2640       if ($this->black_check($addr)) {
2641           // TODO: waiting async 5 sec before close
2642           fprintf(STDERR, "\n\n\n BLACK CHECK\n\n\n");
2643           return (FALSE);
2644       }
2645       if ($path != "" && $path != "index.php") {
2646           if ($this->cloud_check($addr)) {
2647               // TODO: waiting async 5 sec before close
2648               return (FALSE);
2649           }
2650       }
2651
2652       $enc = get_encoding($header);
2653       if (isset($header['User-Agent'])) {
2654           if (strstr($header['User-Agent'], "MSIE")) {
2655               $transp_type = "htmlfile";
2656           }
2657           else {
2658               $transp_type = "xhr";
2659           }
2660       }
2661       else {
2662           $transp_type = "iframe";
2663       }
2664       force_no_cache($header_out);
2665
2666       switch ($path) {
2667       case "":
2668       case "index.php":
2669           ob_start();
2670           index_main($this, $transp_type, $header, $header_out, $addr, $get, $post, $cookie);
2671           $content = ob_get_contents();
2672           ob_end_clean();
2673
2674           // fprintf(STDERR, "\n\nCONTENT [%s]\n\n", $content);
2675           $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2676           return TRUE;
2677
2678           break;
2679       case "index_wr.php":
2680           //
2681           // Enhance required: in the POST case, after the header you must get content
2682           //                   from the socket, waiting if necessary
2683           //
2684
2685           ob_start();
2686           index_wr_main($this, $addr, $get, $post, $cookie);
2687           $content = ob_get_contents();
2688           ob_end_clean();
2689
2690           $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2691           return TRUE;
2692
2693           break;
2694       case "index_rd.php":
2695           if (($transp  = gpcs_var('transp', $get, $post, $cookie)) === FALSE)
2696               $transp = "iframe";
2697           if ($transp == 'websocket')
2698               $enc = 'plain';
2699
2700           do {
2701               if (!isset($cookie['sess'])
2702                   || (($user = $this->get_user($cookie['sess'], $idx)) == FALSE)) {
2703
2704                   $content = User::stream_fini($transp, $s_a_p->rndstr, TRUE);
2705
2706                   $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2707                   return TRUE;
2708
2709                   break;
2710               }
2711               $this->sess_cur_set($user->sess);
2712               // close a previous opened index_read_ifra socket, if exists
2713               if (($prev = $user->rd_socket_get()) != NULL) {
2714                   $s_a_p->socks_unset($user->rd_socket_get());
2715                   fclose($user->rd_socket_get());
2716                   printf("CLOSE AND OPEN AGAIN ON IFRA2\n");
2717                   $user->rd_socket_set(NULL);
2718               }
2719
2720               $content = "";
2721               $user->stream_init($s_a_p->rndstr, $enc, $header, $header_out, $content, $get, $post, $cookie);
2722               $response = headers_render($header_out, -1).$user->chunked_content($content);
2723               $response_l = mb_strlen($response, "ASCII");
2724
2725               $wret = @fwrite($new_socket, $response, $response_l);
2726               if ($wret < $response_l) {
2727                   printf("TROUBLES WITH FWRITE: %d\n", $wret);
2728                   $user->rd_cache_set(mb_substr($content, $wret, $response_l - $wret, "ASCII"));
2729               }
2730               else {
2731                   $user->rd_cache_set("");
2732               }
2733               fflush($new_socket);
2734
2735
2736               $s_a_p->socks_set($new_socket, $user, NULL);
2737               $user->rd_socket_set($new_socket);
2738               printf(" - qui ci siamo - ");
2739               return TRUE;
2740           } while (FALSE);
2741
2742           return FALSE;
2743           break;
2744       case 'test.php':
2745           if (!(BRISK_DEBUG & DBG_ENGI))
2746               return (FALSE);
2747           fprintf(STDERR, "TEST.PHP running\n");
2748           if (isset($post['data'])) {
2749               $content = $post['data'];
2750           }
2751           else {
2752               $content = "NO DATA AVAILABLE";
2753           }
2754           $header_out['Content-Type'] = 'text/plain';
2755           $s_a_p->pendpage_try_addflush($new_socket, 20, $enc, $header_out, $content);
2756           return TRUE;
2757           break;
2758       default:
2759           /* FAR TODO: move all into an array of registered sub-apps */
2760           $subs = "briskin5/";
2761           $subs_l = strlen($subs);
2762           if (!strncmp($path, $subs, $subs_l)) {
2763               $ret = Bin5::request_mgr(&$s_a_p, $header, &$header_out, &$new_socket, substr($path, $subs_l) , $addr, $get, $post, $cookie);
2764               return ($ret);
2765           }
2766           break;
2767       }
2768
2769       return (FALSE);
2770   }
2771
2772   function match_add($idx, $match)
2773   {
2774       $this->match[$idx] = $match;
2775   }
2776
2777   function match_del($idx)
2778   {
2779       unset($this->match[$idx]);
2780   }
2781
2782   function match_get($idx, $token)
2783   {
2784       if (isset($this->match[$idx])) {
2785           if (   $token == NULL
2786               || $token == $this->match[$idx]->table_token) {
2787               return ($this->match[$idx]);
2788           }
2789       }
2790       return NULL;
2791   }
2792   function sess_cur_set($sess)
2793   {
2794       static::$sess_cur = $sess;
2795   }
2796
2797   static function sess_cur_get()
2798   {
2799       return(static::$sess_cur);
2800   }
2801 } // end class Brisk
2802
2803 function make_seed()
2804 {
2805   list($usec, $sec) = explode(' ', microtime());
2806   return (float) $sec + ((float) $usec * 100000);
2807 }
2808
2809 function btrace_line($ar)
2810 {
2811     GLOBAL $G_btrace_pref_sub;
2812
2813     $ret = "";
2814     for ($i = 0 ; $i < count($ar) ; $i++) {
2815         $with_class = isset($ar[$i]['class']);
2816         $with_file  = isset($ar[$i]['file']);
2817         $ret .= sprintf("%s%s%s (%s:%d)", ($i == 0 ? "" : ", "),
2818                         ($with_class ?  $ar[$i]['class'].$ar[$i]['type'] : ""),
2819                         $ar[$i]['function'], ($with_file ? str_replace($G_btrace_pref_sub, "", $ar[$i]['file']) : ""),
2820                         ($with_file ? $ar[$i]['line'] : ""));
2821     }
2822
2823     return ($ret);
2824 }
2825
2826 function trace_ftok($id, $add)
2827 {
2828     // NOTE: without space to use sed to substitute "= @ftok("  with "= @ftok("
2829     $tok=@ftok($id, $add);
2830
2831     log_shme($tok.": ".$id." + ".$add);
2832
2833     return ($tok);
2834 }
2835
2836 function log_mop($step, $log)
2837 {
2838     GLOBAL $PHP_SELF;
2839
2840     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LMOP) == 0)
2841         return;
2842
2843     $sess = Brisk::sess_cur_get();
2844     if (isset($sess) == FALSE)
2845         $ssess = "XXXX";
2846     else
2847         $ssess = $sess;
2848
2849     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LMOP) == 0)
2850         return;
2851
2852     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2853         $btrace = btrace_line(debug_backtrace());
2854     else
2855         $btrace = "";
2856     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2857         fwrite($fp, sprintf("LMOP: [%f] [%05d] [%s] [%s]\n", gettimeofday(TRUE), $step, $log, $btrace));
2858         fclose($fp);
2859     }
2860 }
2861
2862 function log_step($log)
2863 {
2864     GLOBAL $PHP_SELF;
2865
2866     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_STEP) == 0)
2867         return;
2868
2869     $sess = Brisk::sess_cur_get();
2870     if (isset($sess) == FALSE)
2871         $ssess = "XXXX";
2872     else
2873         $ssess = $sess;
2874
2875     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_STEP) == 0)
2876         return;
2877
2878     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2879         $btrace = btrace_line(debug_backtrace());
2880     else
2881         $btrace = "";
2882     if (($fp = @fopen(LEGAL_PATH."/step.log", 'a')) != FALSE) {
2883         fwrite($fp, sprintf("STEP: [%f] [%s] [%s]\n", gettimeofday(TRUE), $log, $btrace));
2884         fclose($fp);
2885     }
2886 }
2887
2888
2889
2890 function log_cds($log)
2891 {
2892     GLOBAL $PHP_SELF;
2893
2894     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CDS) == 0)
2895         return;
2896
2897     $sess = Brisk::sess_cur_get();
2898     if (isset($sess) == FALSE)
2899         $ssess = "XXXX";
2900     else
2901         $ssess = $sess;
2902
2903     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CDS) == 0)
2904         return;
2905
2906     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2907         $btrace = btrace_line(debug_backtrace());
2908     else
2909         $btrace = "";
2910     if (($fp = @fopen(LEGAL_PATH."/cds.log", 'a')) != FALSE) {
2911         fwrite($fp, sprintf("CDS: [%f] [%s] [%s]\n", gettimeofday(TRUE), $log, $btrace));
2912         fclose($fp);
2913     }
2914 }
2915
2916
2917 function log_only2($log)
2918 {
2919     GLOBAL $PHP_SELF;
2920
2921     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONL2) == 0)
2922         return;
2923
2924     $sess = Brisk::sess_cur_get();
2925     if (isset($sess) == FALSE)
2926         $ssess = "XXXX";
2927     else
2928         $ssess = $sess;
2929
2930     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONL2) == 0)
2931         return;
2932
2933     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2934         $btrace = btrace_line(debug_backtrace());
2935     else
2936         $btrace = "";
2937     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2938         fwrite($fp, sprintf("ONL2: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2939         fclose($fp);
2940     }
2941 }
2942
2943 function log_crit($log)
2944 {
2945     GLOBAL $PHP_SELF;
2946
2947     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CRIT) == 0)
2948         return;
2949
2950     $sess = Brisk::sess_cur_get();
2951     if (isset($sess) == FALSE)
2952         $ssess = "XXXX";
2953     else
2954         $ssess = $sess;
2955
2956     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CRIT) == 0)
2957         return;
2958
2959     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2960         $btrace = btrace_line(debug_backtrace());
2961     else
2962         $btrace = "";
2963     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2964         fwrite($fp, sprintf("CRIT: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2965         fclose($fp);
2966     }
2967 }
2968
2969 function log_only($log)
2970 {
2971     GLOBAL $PHP_SELF;
2972
2973     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONLY) == 0)
2974         return;
2975
2976     $sess = Brisk::sess_cur_get();
2977     if (isset($sess) == FALSE)
2978         $ssess = "XXXX";
2979     else
2980         $ssess = $sess;
2981
2982     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONLY) == 0)
2983         return;
2984
2985     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
2986         $btrace = btrace_line(debug_backtrace());
2987     else
2988         $btrace = "";
2989     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2990         fwrite($fp, sprintf("ONLY: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
2991         fclose($fp);
2992     }
2993 }
2994
2995 function log_main($log)
2996 {
2997     GLOBAL $PHP_SELF;
2998
2999     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_MAIN) == 0)
3000         return;
3001
3002     $sess = Brisk::sess_cur_get();
3003     if (isset($sess) == FALSE)
3004         $ssess = "XXXX";
3005     else
3006         $ssess = $sess;
3007
3008     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_MAIN) == 0)
3009         return;
3010
3011     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3012         $btrace = btrace_line(debug_backtrace());
3013     else
3014         $btrace = "";
3015     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3016         fwrite($fp, sprintf("MAIN: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3017         fclose($fp);
3018     }
3019 }
3020
3021 function log_rd($log)
3022 {
3023     GLOBAL $PHP_SELF;
3024
3025     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_READ) == 0)
3026         return;
3027
3028     $sess = Brisk::sess_cur_get();
3029     if (isset($sess) == FALSE)
3030         $ssess = "XXXX";
3031     else
3032         $ssess = $sess;
3033
3034     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_READ) == 0)
3035         return;
3036
3037     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3038         $btrace = btrace_line(debug_backtrace());
3039     else
3040         $btrace = "";
3041     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3042         fwrite($fp, sprintf("READ: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3043         fclose($fp);
3044     }
3045 }
3046
3047 function log_rd2($log)
3048 {
3049     GLOBAL $PHP_SELF;
3050
3051     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_REA2) == 0)
3052         return;
3053
3054     $sess = Brisk::sess_cur_get();
3055     if (isset($sess) == FALSE)
3056         $ssess = "XXXX";
3057     else
3058         $ssess = $sess;
3059
3060     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_REA2) == 0)
3061         return;
3062
3063     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3064         $btrace = btrace_line(debug_backtrace());
3065     else
3066         $btrace = "";
3067
3068     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3069         fwrite($fp, sprintf("REA2: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3070         fclose($fp);
3071     }
3072 }
3073
3074 function log_send($log)
3075 {
3076     GLOBAL $PHP_SELF;
3077
3078     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SEND) == 0)
3079         return;
3080
3081     $sess = Brisk::sess_cur_get();
3082     if (isset($sess) == FALSE)
3083         $ssess = "XXXX";
3084     else
3085         $ssess = $sess;
3086
3087     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SEND) == 0)
3088         return;
3089
3090     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3091         $btrace = btrace_line(debug_backtrace());
3092     else
3093         $btrace = "";
3094     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3095         fwrite($fp, sprintf("SEND: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3096         fclose($fp);
3097     }
3098 }
3099
3100 function log_lock($log)
3101 {
3102     GLOBAL $PHP_SELF;
3103
3104     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOCK) == 0)
3105         return;
3106
3107     $sess = Brisk::sess_cur_get();
3108     if (isset($sess) == FALSE)
3109         $ssess = "XXXX";
3110     else
3111         $ssess = $sess;
3112
3113     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOCK) == 0)
3114         return;
3115
3116     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3117         $btrace = btrace_line(debug_backtrace());
3118     else
3119         $btrace = "";
3120     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3121         fwrite($fp, sprintf("LOCK: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3122         fclose($fp);
3123     }
3124 }
3125
3126 function log_wr($log)
3127 {
3128     GLOBAL $PHP_SELF;
3129
3130     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_WRIT) == 0)
3131         return;
3132
3133     $sess = Brisk::sess_cur_get();
3134     if (isset($sess) == FALSE)
3135         $ssess = "XXXX";
3136     else
3137         $ssess = $sess;
3138
3139     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_WRIT) == 0)
3140         return;
3141
3142     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3143         $btrace = btrace_line(debug_backtrace());
3144     else
3145         $btrace = "";
3146     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3147         fwrite($fp, sprintf("WRIT: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3148         fclose($fp);
3149     }
3150 }
3151
3152 function log_load($log)
3153 {
3154     GLOBAL $PHP_SELF;
3155
3156     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOAD) == 0)
3157         return;
3158
3159     $sess = Brisk::sess_cur_get();
3160     if (isset($sess) == FALSE)
3161         $ssess = "XXXX";
3162     else
3163         $ssess = $sess;
3164
3165     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOAD) == 0)
3166         return;
3167
3168     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3169         $btrace = btrace_line(debug_backtrace());
3170     else
3171         $btrace = "";
3172     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3173         fwrite($fp, sprintf("LOAD: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3174         fclose($fp);
3175     }
3176 }
3177
3178 function log_auth($sess, $log)
3179 {
3180     GLOBAL $PHP_SELF;
3181
3182     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_AUTH) == 0)
3183         return;
3184
3185     if (( (BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_AUTH) == 0)
3186         return;
3187
3188     if ((BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3189         $btrace = btrace_line(debug_backtrace());
3190     else
3191         $btrace = "";
3192     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3193         fwrite($fp, sprintf("LOAD: [%s] [%d] [%s] [%s]\n", $sess, time(), $log, $btrace));
3194         fclose($fp);
3195     }
3196 }
3197
3198 function log_shme($log)
3199 {
3200     GLOBAL $PHP_SELF;
3201
3202     if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SHME) == 0)
3203         return;
3204
3205     $sess = Brisk::sess_cur_get();
3206     if (isset($sess) == FALSE)
3207         $ssess = "XXXX";
3208     else
3209         $ssess = $sess;
3210
3211     if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SHME) == 0)
3212         return;
3213
3214     if ((BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_TRAC)
3215         $btrace = btrace_line(debug_backtrace());
3216     else
3217         $btrace = "";
3218     if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
3219         fwrite($fp, sprintf("SHME: [%s] [%s] [%s]\n", $ssess, $log, $btrace));
3220         fclose($fp);
3221     }
3222 }
3223
3224
3225
3226 // function log_legal($curtime, $sess, $name, $where, $mesg)
3227 function log_legal($curtime, $addr, $user, $where, $mesg)
3228 {
3229
3230   if (($fp = @fopen(LEGAL_PATH."/legal.log", 'a')) != FALSE) {
3231     /* Unix time | session | nickname | IP | where was | mesg */
3232     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
3233                         ($user->is_auth() ? 'A' : 'N'),
3234                         $user->name, $addr, $where , $mesg));
3235     fclose($fp);
3236   }
3237 }
3238
3239 function table_act_content($isstanding, $sitted, $table, $cur_table, $allowed)
3240 {
3241   $ret = "";
3242
3243   if ($isstanding) {
3244     if ($sitted < PLAYERS_N) {
3245       if ($allowed)
3246         $act = 'sit';
3247       else
3248         $act = 'reserved';
3249     }
3250   }
3251   else {
3252     if ($table == $cur_table)
3253       $act = 'wake';
3254     else
3255       $act = 'none';
3256   }
3257
3258   if ($act != '')
3259     $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
3260
3261   return ($ret);
3262 }
3263
3264 function show_notify($text, $tout, $butt, $w, $h)
3265 {
3266   log_main("SHOW_NOTIFY: ".$text);
3267   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
3268 }
3269
3270 function show_notify_ex($text, $tout, $butt, $w, $h, $is_opaque, $block_time)
3271 {
3272   log_main("SHOW_NOTIFY OPAQUE: ".$text);
3273   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);
3274 }
3275
3276 function show_notify_document($text, $tout, $butt_arr, $confirm_func, $confirm_func_args, $w, $h, $is_opaque, $block_time)
3277 {
3278   log_main("SHOW_NOTIFY OPAQUE: ".$text);
3279
3280   $butts = "";
3281   for ($i = 0 ; $i < count($butt_arr) ; $i++) {
3282       $butts .= sprintf("%s'%s'", ($i == 0 ? "" : ","), $butt_arr[$i]);
3283   }
3284
3285   return sprintf('g_nd = new notify_document(gst, "%s", %d, [ %s ], %s, %s, %d, %d, %s, %d);|',
3286                  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);
3287 }
3288
3289
3290 function root_welcome($user)
3291 {
3292   GLOBAL $root_wellarr, $G_lang;
3293   $ret = "";
3294
3295   $curtime = time();
3296   $dt = date("H:i ", $curtime);
3297
3298   for ($i = 0 ; $i < count($root_wellarr[$G_lang]) ; $i++)
3299       $ret .= nickserv_msg($dt, str_replace('"', '\"', $root_wellarr[$G_lang][$i]));
3300
3301   return ($ret);
3302 }
3303
3304
3305
3306 function validate_sess($sess)
3307 {
3308   if (strlen($sess) == SESS_LEN)
3309     return (TRUE);
3310   else
3311     return (FALSE);
3312 }
3313
3314 function validate_name($name)
3315 {
3316     $name_new = str_replace(' ', '_', mb_substr(trim($name),0,12, "UTF-8"));
3317
3318   for ($i = 0 ; $i < mb_strlen($name_new) ; $i++) {
3319     $c = $name_new[$i];
3320     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
3321       return ($name_new);
3322   }
3323
3324   return (FALSE);
3325 }
3326
3327 function playsound($filename)
3328 {
3329   return (sprintf('playsound("flasou", "%s");', $filename));
3330 }
3331
3332 function secstoword($secs)
3333 {
3334   GLOBAL $G_lang;
3335
3336   $ret = "";
3337
3338   $mins = floor($secs / 60);
3339   $secs = $secs % 60;
3340   if ($G_lang == 'en') {
3341     if ($mins > 0)
3342       $ret = sprintf("%d minute%s%s", $mins, ($mins > 1 ? "s" : ""), ($secs > 0 ? " and " : ""));
3343
3344     if ($secs > 0)
3345       $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "s" : ""));
3346   }
3347   else {
3348     if ($mins > 0)
3349       $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
3350
3351     if ($secs > 0)
3352       $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
3353   }
3354   return ($ret);
3355 }
3356
3357 function sharedmem_sz($tok)
3358 {
3359   if (($shm_id = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
3360     log_main("shmop_open failed");
3361     return (-1);
3362   }
3363   $shm_sz = shmop_size($shm_id);
3364   shmop_close($shm_id);
3365
3366   // log_main("shm_sz: ".$shm_sz."   SHM_DIMS: ".SHM_DIMS);
3367   return ($shm_sz);
3368 }
3369
3370 class Warrant {
3371     static $delta_t;
3372
3373   static function lock_data($is_exclusive)
3374   {
3375       if (($res = file_lock(FTOK_PATH."/warrant", $is_exclusive)) != FALSE) {
3376           self::$delta_t = microtime(TRUE);
3377           log_lock("LOCK   warrant      [".self::$delta_t."]");
3378
3379           return ($res);
3380       }
3381
3382       return (FALSE);
3383   }
3384
3385   static function unlock_data($res)
3386   {
3387     GLOBAL $sess;
3388
3389     log_lock("UNLOCK warrant      [".(microtime(TRUE) - (self::$delta_t))."]");
3390
3391     file_unlock($res);
3392   }
3393 }
3394
3395 class Poll {
3396     static $delta_t;
3397
3398   static function lock_data($is_exclusive)
3399   {
3400       if (($res = file_lock(FTOK_PATH."/poll", $is_exclusive)) != FALSE) {
3401           self::$delta_t = microtime(TRUE);
3402           log_lock("LOCK   poll         [".self::$delta_t."]");
3403
3404           return ($res);
3405       }
3406
3407       return (FALSE);
3408   }
3409
3410   static function unlock_data($res)
3411   {
3412     GLOBAL $sess;
3413
3414     log_lock("UNLOCK poll         [".(microtime(TRUE) - (self::$delta_t))."]");
3415
3416     file_unlock($res);
3417   }
3418 }
3419
3420 function carousel_top()
3421 {
3422     $what = rand(1,2);
3423     if ($what == 1) {
3424         $rn = rand(1, 3);
3425         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));
3426         }
3427     else {
3428         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>'));
3429     }
3430 }
3431
3432
3433 ?>