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