updated
[brisk.git] / web / Obj / brisk.phh
1 <?php
2 /*
3  *  brisk - brisk.phh
4  *
5  *  Copyright (C) 2006-2009 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(PLAYERS_N, 3);
32 define(MAX_POINTS, 5);
33 define(MAX_PLAYERS, (20 + (PLAYERS_N * TABLES_N)));
34 define(SHM_DIMS_MIN, (50000 + 10000 * TABLES_N + 15000 * MAX_PLAYERS));
35 define(SHM_DIMS_MAX, SHM_DIMS_MIN + 1048576);
36 define(SHM_DIMS_DLT, 65536);
37  
38 define(COMM_N, 18);
39 define(COMM_GEN_N, 50);
40
41 define(CHAT_N, 3);
42 define(CHAT_ILL_TIME, 6);
43
44 define(SESS_LEN, 13);
45 define(STREAM_TIMEOUT, 20);
46 define(EXPIRE_TIME_RD, 180);
47 define(EXPIRE_TIME_SMAMMA, 360); 
48 define(EXPIRE_TIME_WAG, 10);
49 define(WAKEUP_TIME, 12); 
50 // BAN_TIME da allineare anche in commons.js
51 define(BAN_TIME, 3600); 
52 define(GARBAGE_TIMEOUT, 10);
53 define(NICKSERV, "<i>BriskServ</i>");
54
55 define(DBG_ONL2, 0x0001);
56 define(DBG_ONLY, 0x0002);
57 define(DBG_MAIN, 0x0004);
58 define(DBG_READ, 0x0008);
59 define(DBG_REA2, 0x0010);
60 define(DBG_SEND, 0x0020);
61 define(DBG_LOCK, 0x0040);
62 define(DBG_WRIT, 0x0080);
63 define(DBG_LOAD, 0x0100);
64 define(DBG_AUTH, 0x0200);
65 define(DBG_CRIT, 0x0400);
66
67 // NOTE: BRISK DEBUG must be a numerical constant, not the result of operations on symbols 
68 define(BRISK_DEBUG, 0xffffffbf);
69
70 define(BRISK_SINGLE_DEBUG,0);
71 define(BRISK_SINGLE_SESS, "");
72 // define(DEBUGGING, "local");
73
74 require_once("$DOCUMENT_ROOT/Etc/".BRISK_CONF);
75
76 $G_false = FALSE;
77 $G_lang = "it";
78 $G_lng = "";
79 // $G_lang = "en";
80 // $G_lng = "_en";
81
82 $G_all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
83 $G_brisk_version = "2.1.8 - trusty";
84
85 /* MLANG: ALL THE INFO STRINGS IN brisk.phh */
86 $root_wellarr = Array ( 'Brisk (Ver. '.$G_brisk_version.'), <b>NOVITA\'</b>: Sponsor alternati, menù rivisto, AUTO-GARANZIE, sondaggi quasi ultimati.',
87                         'Se vuoi iscriverti alla <a target="_blank" href="http://www.milug.org/cgi-bin/mailman/listinfo/ml-briscola">Mailing List</a>, cliccala!' );
88
89 $G_room_help= '
90 <div style=\\"text-align: left; padding: 8px;\\">
91 <b>Descrizione</b><br>
92 Questa è un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
93 <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>
94 <b>Configurazione del browser.</b><br>
95 Occorre abilitare i cookies.<br>
96 <br>
97 <b>Uso del sito</b><br>
98 Potete sedervi a un tavolo o rimanere in piedi.<br>
99 Se al vostro tavolo si raggiungono i 5 giocatori inizia automaticamente la partita.<br>
100 <br>
101 <b>Partita</b><br>
102 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>
103 Chi vince l\'asta dovr&agrave; decidere il seme della carta scelta e inizier&agrave; la mano.<br>
104 Per giocare le carte dovrete trascinarle nel quadrato al centro del vostro schermo.<br><br>
105 Il vostro turno &egrave; sempre segnalato da una cornice verde lampeggiante intorno al quadrato al centro del vostro schermo.<br><br>
106 Durante la partita, se vorrete ricaricare la pagina, usate l\'apposito bottone \\"reload\\" in basso a destra.<br>
107 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.
108 <dl>
109 <dt><b>Comandi della chat</b>
110 <dd><b>/nick <i>&lt;nuovo_nickname&gt;</i></b> - cambio di nickname
111 <dd><b>/tav <i>&lt;frase di invito&gt;</i></b> - invito per gli altri giocatori al tavolo dove si &egrave; seduti 
112 <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\\"
113 <dd><b>/garante</b> - se si &egrave; autenticati permette di garantire per un utente fidato
114 <dd><b>/mesgtoadm</b> - se si &egrave; autenticati permette di lasciare un messaggio all\'amministratore del sito
115 <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)
116 </dl>
117 </div>
118 ';
119
120 //  
121 $G_room_passwdhowto= '<br><h2>Come registrarsi su Brisk</h2>
122 <div style=\\"text-align: left; padding: 8px;\\">
123 Attualmente ci sono due metodi per ottenere una password sul sito:<br><br>
124 <dir>
125 <li><b>Facendosi garantire da un utente di Brisk che gi&agrave; possidede una password</b><br><br>
126 <li><b>Auto-garantendosi utilizzando uno dei seguenti sistemi di identificazione digitale:</b><br><br>
127 <dir>
128 <li>Carta Regionale dei Servizi della Lombardia (la tessera sanitaria)
129 <li>Carta Regionale dei Servizi del Friuli Venezia Giulia (la tessera sanitaria)
130 </dir>
131 <br>
132 <b>Per auto-garantisi occorre possedere:</b><br><br>
133 <dir>
134 <li>il codice PIN della propria carta
135 <li>il lettore di smart-card per collegare la carta al PC (acquistabile di solito presso le edicole)
136 </dir>
137 <br>
138 <b>Per effettuare la registrazione collegarsi al sito:</b><br><br>
139 <dl>
140 <dd><a class=\\"flat\\"  target=\\"_blank\\" href=\\"https://brisk.mine.nu\\">https://brisk.mine.nu</a>
141 </dl>
142 <br><br>
143 Se sei in possesso di una carta che permette l\'identificazione via internet che non è nell\'elenco qui sopra
144 <a class=\\"flat\\" href=\\"mailto:authadmbrisk@alternativeoutput.it\\">fai una segnalazione</a>.
145
146 </dir>
147 </div>
148 ';
149 /*
150 <dd>Seguendo la procedura di auto-garanzia all\'url: <a href="https://brisk.mine.nu">https://brisk.mine.nu</a>
151 ';
152 */
153
154 $G_room_about= '<br>
155 <div id=\\"header\\" class=\\"header\\">
156   <img class=\\"nobo\\" src=\\"img/brisk_logo64.png\\">
157   briscola chiamata in salsa ajax
158 </div>
159 <br><b>version '.$G_brisk_version.'</b><br><br>
160 Copyright 2006-2008 <a href=\\"mailto:brisk@alternativeoutput.it\\">Matteo Nastasi</a> (aka mop)<br><br>';
161
162
163 function xcape($s)
164 {
165   $from = array (   '\\',     '@',        '|' );
166   $to   = array ( '\\\\', '&#64;', '&brvbar;' );
167
168   return (str_replace($from, $to, htmlentities($s,ENT_COMPAT,"UTF-8")));
169 }
170
171 function xcapelt($s)
172 {
173   $from = array (   '\\',     '|',  "\t",  "\n");
174   $to   = array ( '\\\\',   '\\|', "\\t", "\\n");
175
176   return (str_replace($from, $to, $s));
177 }
178
179 function xcapemesg($s)
180 {
181   $from = array (  "\n");
182   $to   = array ( "\\n");
183
184   return (str_replace($from, $to, $s));
185 }
186
187
188 class Table {
189   var $idx;
190   var $player;
191   var $player_n;
192
193   var $auth_only;     // se tavolo riservato o libero
194
195   var $wag_own;
196   var $wag_com;
197   var $wag_tout;
198
199   var $table_token;
200   var $table_start;   // information field
201
202   var $wakeup_time;
203
204   function Table() 
205   {
206   }
207   
208   function &create($idx) 
209   {
210     GLOBAL $G_false;
211
212     if (($thiz =& new Table()) == FALSE)
213       return ($G_false);
214
215     $thiz->idx       =   $idx;
216     $thiz->player    =   array();
217     $thiz->player_n  =   0;
218     $thiz->auth_only =   FALSE;
219
220     $thiz->wag_own   =  NULL;
221     $thiz->wag_com   =  "";
222     $thiz->wag_tout   =  0;
223
224     $thiz->table_token  = "";
225     $thiz->table_start  = 0;
226     
227     $thiz->wakeup_time = 0;
228
229     return ($thiz);
230   }
231
232   function copy(&$from)
233   {
234     GLOBAL $G_false;
235     
236     $this->idx = $from->idx;
237     $this->player = array();
238     for ($i = 0 ; $i < $from->player_n ; $i++)
239       $this->player[$i] = $from->player[$i];
240     $this->player_n = $from->player_n;
241
242     log_main("PLAYER_N - parent::copy.".$this->player_n);
243     
244     $this->auth_only =  $from->auth_only;
245
246     $this->wag_own   =  $from->wag_own;
247     $this->wag_com   =  $from->wag_com;
248     $this->wag_tout  =  $from->wag_tout;
249
250     $this->table_token  = $from->table_token;
251     $this->table_start  = $from->table_start;
252
253     $this->wakeup_time = $from->wakeup_time;
254   }
255
256   function &clone(&$from)
257   {
258     GLOBAL $G_false;
259     
260     if (($thiz =& new Table()) == FALSE)
261       return ($G_false);
262
263     $this->copy($from);
264
265     return ($thiz);
266   }
267   
268   function &spawn(&$from)
269   {
270     GLOBAL $G_false;
271     
272     if (($thiz =& new Table()) == FALSE)
273       return ($G_false);
274     
275     $thiz->idx = $from->idx;
276     $thiz->player = array();
277     for ($i = 0 ; $i < $from->player_n ; $i++)
278       $thiz->player[$i] = $i;
279     $thiz->player_n = $from->player_n;
280
281     $thiz->auth_only =  $from->auth_only;
282
283     $thiz->wag_own = $from->wag_own;
284     $thiz->wag_com = $from->wag_com;
285     $thiz->wag_tout  =  $from->wag_tout;
286
287     $thiz->table_token  = $from->table_token;
288     $thiz->table_start  = $from->table_start;
289
290     $thiz->wakeup_time = $from->wakeup_time;
291
292     return ($thiz);
293   }
294
295   function wag_set(&$user, $mesg)
296   {
297     log_main("WAG_SET");
298
299     $this->wag_own  = &$user;
300     $this->wag_com  =  $mesg;
301     $this->wag_tout =  0;
302   }
303
304   function wag_reset($timeout)
305   {
306     log_main("WAG_RESET");
307
308     unset($this->wag_own);
309     $this->wag_own = NULL;
310     $this->wag_com  = "";
311     $this->wag_tout = $timeout;
312   }
313
314   function getPlayer($idx)
315   {
316     return ($this->player[$idx]);
317   }
318
319   function setPlayer($idx, $player)
320   {
321     $this->player[$idx] = $player;
322   }
323
324   function user_add($idx)
325   {
326     $this->player[$this->player_n] = $idx;
327     $this->player_n++;
328     
329     return ($this->player_n - 1);
330   }
331   
332   function user_rem(&$room, &$user)
333   {
334     $tabpos = $user->table_pos;
335     
336     /* verifico la consistenza dei dati */
337     if ($room->user[$this->player[$tabpos]] == $user) {
338       
339       /* aggiorna l'array dei giocatori al tavolo. */
340       for ($i = $tabpos ; $i < $this->player_n-1 ; $i++) {
341         $this->player[$i] = $this->player[$i+1];
342         $user_cur = &$room->user[$this->player[$i]];
343         $user_cur->table_pos = $i;
344       }
345       $this->player_n--;
346     }
347     else {
348       log_main("INCONSISTENCY ON TABLE.");
349     }
350   }
351
352
353
354   //      $ret .= table_act_content(($user->subst == 'standup'), $this->table[$i]->player_n, $i, $user->table, 
355   //                              ($this->table[$i]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
356
357   // function act_content($isstanding, $sitted, $table, $cur_table, $allowed)
358   function act_content(&$user)
359   {
360     $ret = "";
361     $isstanding = ($user->subst == 'standup');
362     $sitted = $this->player_n;
363     $table = $this->idx;
364     $cur_table = $user->table;
365     $allowed = TRUE;
366
367     if ($isstanding) {
368       if ($sitted < PLAYERS_N) {
369         if ($this->auth_only) {
370           if ($user->flags & USER_FLAG_AUTH) 
371             $act = "sitreser";
372           else
373             $act = 'reserved';
374         }
375         else {
376           $act = 'sit';
377         }
378       }
379       else {
380         $act = 'none';
381       }
382     }
383     else {
384       if ($table == $cur_table)
385         $act = 'wake';
386       else
387         $act = 'none';
388     }
389     
390     if ($act != '')
391       $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
392     
393     return ($ret);
394   }
395 } // end class Table
396
397
398 // User flags
399 define(USER_FLAG_AUTH,     0x02);
400 define(USER_FLAG_LISTAUTH, 0x04);
401
402 //   user status
403 define(USER_FLAG_S_NORM,  0x000); // done
404 define(USER_FLAG_S_PAU,   0x100); // done
405 define(USER_FLAG_S_OUT,   0x200); // done
406 define(USER_FLAG_S_DOG,   0x300); // done
407 define(USER_FLAG_S_EAT,   0x400); // done
408 define(USER_FLAG_S_WRK,   0x500); // done
409 define(USER_FLAG_S_SMK,   0x600); // done
410 define(USER_FLAG_S_EYE,   0x700); // done
411
412 define(USER_FLAG_S_ALL,   0xf00); // done
413
414 class User {
415   var $name;       // name of the user
416   var $sess;       // session of the user
417   var $ip;         // ip of the user
418   var $lacc;       // last access (for the cleanup)
419   var $laccwr;     // last access (for the cleanup)
420   var $bantime;    // timeout to temporary ban
421   var $stat;       // status (outdoor, room, table, game, ...)
422   var $subst;      // substatus for each status   
423   var $step;       // step of the current status
424   var $trans_step; // step to enable transition between pages (disable == -1)
425   var $comm;       // commands array
426   // var $asta_card;  // 
427   // var $asta_pnt;   //
428   // var $handpt;     // Total card points at the beginning of the current hand.
429   // var $exitislock; // Player can exit from the table ?
430
431   // FIXME: the table_orig field must be removed after table field verify of index management (in spawned table
432   //        it is allways ZERO
433   var $table_orig; // id of the current table (if in table state)
434   var $table;      // id of the current table (if in table state)
435   var $table_pos;  // idx on the table
436   var $table_token;// token that identify a game on a table
437   var $flags;      // Bitfield with: AUTHENTICATE: 0x02 
438   var $the_end;    // Flag to change the end of the session
439
440   var $chat_lst;      // Last chat line
441   var $chattime;      // Array of chat times
442   var $chat_cur;      // Current chat line number
443   var $chat_ban;      // Time for ban chat
444   var $chat_dlt;      // Delta t for ban
445   function User() {
446   }
447
448   function &create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
449     GLOBAL $G_false;
450
451     if (($thiz =& new User()) == FALSE)
452       return ($G_false);
453
454     $thiz->name  = $name;
455     $thiz->sess  = $sess;
456     $thiz->ip    = $ip;
457     $thiz->lacc   = time();
458     $thiz->laccwr = time();
459     $thiz->bantime = 0;
460     $thiz->stat  = $stat;
461     $thiz->subst  = $subst;
462     $thiz->step  = 1;
463     $thiz->trans_step  = -1;
464     $thiz->comm  = array();
465     $thiz->asta_card = -2;
466     $thiz->asta_pnt  = -1;
467     $thiz->handpt = -1;
468     $thiz->exitislock = TRUE;
469
470     $thiz->flags = 0x00;
471     
472     $thiz->chattime = array_fill(0, CHAT_N, 0);
473     $thiz->chat_cur = 0;
474     $thiz->chat_lst = "";
475     $thiz->chat_ban = 0;
476     $thiz->chat_dlt = 0;
477
478     $thiz->table_orig = $table;
479     $thiz->table      = $table;
480     $thiz->table_pos = -1;
481     $thiz->table_token = "";
482
483     return ($thiz);
484   }
485
486   function copy(&$from)
487   {
488     GLOBAL $G_false;
489     
490     $this->name       = $from->name;
491     $this->sess       = $from->sess;
492     $this->ip         = $from->ip;
493     $this->lacc       = $from->lacc;
494     $this->laccwr     = $from->laccwr;
495     $this->bantime    = $from->bantime;
496     $this->stat       = $from->stat;
497     $this->subst      = $from->subst;
498     $this->step       = $from->step;
499     $this->trans_step = $from->trans_step;
500     $this->comm       = array();
501
502     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
503     for ($i = $i_start ; $i < $from->step ; $i++) {
504       $ii = $i % COMM_N;
505       $this->comm[$ii] = $from->comm[$ii];
506     }
507     $this->asta_card  = $from->asta_card;
508     $this->asta_pnt   = $from->asta_pnt;
509     $this->handpt     = $from->handpt;
510     $this->exitislock = $from->exitislock;
511
512     $this->flags = $from->flags;
513
514     $this->chattime = array();
515     for ($i = 0 ; $i < CHAT_N ; $i++)
516       $this->chattime[$i] = $from->chattime[$i];
517     $this->chat_cur = $from->chat_cur;
518     $this->chat_lst = $from->chat_lst;
519     $this->chat_ban = $from->chat_ban;
520     $this->chat_dlt = $from->chat_dlt;
521
522     $this->table_orig = $from->table_orig;
523     $this->table      = $from->table;
524     $this->table_pos  = $from->table_pos;
525     $this->table_token = $from->table_token;
526     $this->the_end    = $from->the_end;
527
528     return (TRUE);
529   }
530
531
532   function &clone(&$from)
533   {
534     GLOBAL $G_false;
535     
536     if (($thiz =& new User()) == FALSE)
537       return ($G_false);
538     
539     $thiz->copy($from);
540
541     return ($thiz);
542   }
543   
544   function &spawn(&$from, $table, $table_pos)
545   {
546     GLOBAL $G_false;
547     
548     if (($thiz =& new User()) == FALSE)
549       return ($G_false);
550     
551     $thiz->name       = $from->name;
552     $thiz->sess       = $from->sess;
553     $thiz->ip         = $from->ip;
554     $thiz->lacc       = $from->lacc;
555     $thiz->laccwr     = $from->laccwr;
556     $thiz->bantime    = $from->bantime;
557     $thiz->stat       = $from->stat;
558     $thiz->subst      = $from->subst;
559     $thiz->step       = $from->step;
560     $thiz->trans_step = $from->trans_step;
561     $thiz->comm       = array();
562
563     /*
564     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
565     for ($i = $i_start ; $i < $from->step ; $i++) {
566       log_wr("TRY PUSH:".$i);
567       $ii = $i % COMM_N;
568       $thiz->comm[$ii]   = $from->comm[$ii];
569     }
570     */
571     $thiz->asta_card  = $from->asta_card;
572     $thiz->asta_pnt   = $from->asta_pnt;
573     $thiz->handpt     = $from->handpt;
574     $thiz->exitislock = $from->exitislock;
575     $thiz->the_end    = $from->the_end;
576
577     $thiz->flags      = $from->flags;
578
579     $thiz->chattime   = array_fill(0, CHAT_N, 0);
580     $thiz->chat_cur   = 0;
581     $thiz->chat_lst   = "";
582     $thiz->chat_ban   = 0;
583     $thiz->chat_dlt   = 0;
584
585
586     $thiz->table_orig = $table;
587     $thiz->table      = 0;
588     $thiz->table_pos  = $table_pos;
589     $thiz->table_token = $from->table_token;
590
591     return ($thiz);
592   }
593   
594   function stat_set($stat) {
595     log_main("sess: [".$this->sess. "] NEW STAT: [".$stat."]"); 
596     $this->stat = "$stat";
597     
598     /*
599     if (validate_sess($this->sess)) {
600       if (file_exists(PROXY_PATH) == FALSE)
601         mkdir(PROXY_PATH);
602       $fp = fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
603       fwrite($fp, sprintf("%s\n",$this->stat));
604       fclose($fp);
605     }
606     */
607   }
608
609   function step_set($step) {
610     $this->step = $step;
611     
612     do {
613       if (validate_sess($this->sess) == FALSE)
614         break;
615       if (file_exists(PROXY_PATH) == FALSE)
616         mkdir(PROXY_PATH);
617       if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
618         break;
619       fwrite($fp, pack("l",$this->step), 4);
620       fclose($fp);
621
622       return (TRUE);
623     } while (0);
624
625     return (FALSE);
626   }
627
628   function step_inc($delta = 1) {
629     $this->step += $delta;
630     
631     if (validate_sess($this->sess)) {
632       if (file_exists(PROXY_PATH) == FALSE)
633         mkdir(PROXY_PATH);
634       $fp = fopen(PROXY_PATH."/".$this->sess.".step", 'w');
635       fwrite($fp, pack("l",$this->step), 4);
636       fclose($fp);
637
638       return (TRUE);
639     }
640     
641     return (FALSE);
642   }
643
644   function reset() {
645     $curtime = time();
646     log_legal($curtime, $this, "STAT:LOGOUT", '');
647
648     $tmp_sess = $this->sess;
649     $this->sess = "";
650     step_unproxy($tmp_sess);
651     $this->name = "";  // OK here
652     while (array_pop($this->comm) != NULL);
653     $this->step = 0;
654     $this->chattime = array_fill(0, CHAT_N, 0);
655     $this->chat_cur = 0;
656     $this->chat_lst = "";
657     $this->chat_ban = 0;
658     $this->chat_dlt = 0;
659     $this->the_end = FALSE;
660   }
661 } // end class User
662
663
664
665
666
667
668
669 function step_get($sess) {
670   $fp = FALSE;
671   do {
672     if (validate_sess($sess) == FALSE)
673       break;
674
675     if (file_exists(PROXY_PATH) == FALSE)
676       mkdir(PROXY_PATH);
677     if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
678       break;
679     if (($s = fread($fp, 4)) == FALSE)
680       break;
681     if (strlen($s) != 4)
682       break;
683     $arr = unpack('l', $s);
684     fclose($fp);
685
686     // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
687     return ($arr[1]);
688   } while (0);
689
690   if ($fp != FALSE)
691     fclose($fp);
692
693   log_rd2("STEP_GET: return false ");
694
695   return (FALSE);
696 }
697
698 function step_unproxy($sess) {
699   log_rd2("UNPROXY: ".PROXY_PATH."/".$sess.".step");
700   if (file_exists(PROXY_PATH) == FALSE)
701     mkdir(PROXY_PATH);
702   @unlink(PROXY_PATH."/".$sess.".step");
703 }
704
705
706 class Room {
707   var $user;
708   var $table;
709   var $comm; // commands for many people
710   var $step; // current step of the comm array
711   var $garbage_timeout;
712   var $shm_sz;
713
714   function Room () {
715     $this->user = array();
716     $this->table = array();
717
718     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
719       $this->user[$i] =& User::create("", "");
720     }
721
722     for ($i = 0 ; $i < TABLES_N ; $i++) {
723       $this->table[$i] =& Table::create($i);
724       /* OLD METHOD
725       if ($i < 12) {
726         $row = ( (((int)($i / 4)) % 2) == 0 );
727         $col = ($i % 2 == 0);
728         $this->table[$i]->auth_only = (($row && $col) || (!$row && !$col));
729       }
730       else {
731         $this->table[$i]->auth_only = FALSE;
732       }
733       */
734       if ($i < 12) 
735         $this->table[$i]->auth_only = TRUE;
736       else
737         $this->table[$i]->auth_only = FALSE;
738     }
739     $this->garbage_timeout = 0;
740   }
741
742   function garbage_manager($force)
743   {
744     $ismod = FALSE;
745
746     log_rd2("garbage_manager START");
747
748     /* Garbage collector degli utenti in timeout */
749     $curtime = time();
750     if ($force || $this->garbage_timeout < $curtime) {
751       
752       // FIXME BRISK4: include for each kind of table
753       require_once("briskin5/Obj/briskin5.phh");
754
755       // Before all align times with table timeout
756       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
757         $table_cur =& $this->table[$table_idx];
758         // if the table is complete and exists its shared mem we get the info about users lacc
759
760         if ($table_cur->player_n == PLAYERS_N) {
761           log_main("PLAYERS == N TABLE ".$table_idx);
762           
763           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
764             log_main("bin5 lock data success");
765             
766             $no_recovery = FALSE;
767             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
768               if ($table_cur->table_token != $bri->table_token) {
769                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
770                 log_main("ERROR: not matching table_start. Room: ".$table_cur->table_start."  Table: ".$bri->table_start);
771                 $no_recovery = TRUE;
772                 $bri = FALSE;
773               }
774             }
775             
776             if ($bri != FALSE) {
777               //
778               //  SPAWN: JOIN
779               //
780               log_main("garbage_manager: bri loaded successfully.");
781               $bri->garbage_manager(TRUE);
782               
783               $bri_table = &$bri->table[0];
784
785               // is the end of the table
786               if ($bri->the_end == TRUE) {
787                 /*
788                  *  DESTROY OF FINISHED TABLE && MOVE PLAYER TO ROOM AGAIN
789                  */
790                 log_main("garbage_manager: INSIDE THE END.");
791
792                 $plist = "$table_cur->table_token|$table_cur->idx|$table_cur->player_n";
793                 for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
794                   $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
795                 }
796
797                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
798                   // stat must be "table" by definition
799                   $user_cur =& $this->user[$table_cur->player[$i]];
800                   $bri_user =& $bri->user[$i];
801                   
802                   $user_cur->subst      = $bri_user->subst;
803                   $user_cur->step       = $bri_user->step;
804                   $user_cur->lacc       = $bri_user->lacc;
805                   $user_cur->laccwr     = $bri_user->lacc;
806                   $user_cur->bantime    = $bri_user->bantime;
807                 }
808
809                 log_legal($curtime, $user_cur, "STAT:DESTROY_GAME", $plist);
810
811                 $this->room_join_wakeup(&$user_cur, FALSE, 0); 
812                 $table_cur->table_token = "";
813                 $table_cur->wakeup_time = $curtime + WAKEUP_TIME;
814                 Briskin5::destroy_data($table_idx);
815               }
816               else {
817                 log_main("gm:: save_data");
818
819                 for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
820                   $this->user[$table_cur->player[$i]]->lacc = $bri->user[$i]->lacc;
821                 }
822               
823                 Briskin5::save_data(&$bri);
824               }
825             } // else if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
826             else if ($no_recovery == FALSE) {
827               log_crit("ERROR: table ".$table_idx." unrecoverable join");
828
829               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
830                 $user_cur = &$this->user[$table_cur->player[$i]];
831                 $user_cur->subst = "shutdowner";
832                 $user_cur->step_inc();
833                 
834                 $ret = sprintf('stat = "%s"; subst = "%s";',  $user_cur->stat, $user_cur->subst);
835                 $ret .= "gst.st = ".($user_cur->step+1)."; ";
836                 $ret .= show_notify("<br>I dati del tavolo n&deg; ".$user_cur->table." sono inconsistenti, verranno resettati.<br><br>Torni in piedi.<br><br>", 2000, "Chiudi.", 400, 110);
837                 $user_cur->comm[$user_cur->step % COMM_N] = $ret;
838                 $user_cur->step_inc();
839               }
840
841               $plist = "$table_cur->table_token|$user_cur->table|$table_cur->player_n";
842               for ($i = 0 ; $i < $table_cur->player_n ; $i++) {
843                 $plist .= '|'.$this->user[$table_cur->player[$i]]->sess;
844               }
845               log_legal($curtime, $user_cur, "STAT:DESTROY_GAME(RECOVERY)", $plist);
846               
847               $this->room_join_wakeup(&$user_cur, TRUE, -2); 
848               $table_cur->table_token = "";
849             }
850
851             Briskin5::unlock_data($sem);
852           } // bri::lock_data
853         } //  if ($table_cur->player_n == PLAYERS_N) {
854       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
855     
856       log_rd2("out new loop.");
857                 
858       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
859         $user_cur = &$this->user[$i];
860         
861         log_rd2("User: ".$user_cur->name."  stat: ".$user_cur->stat."  subst: ".$user_cur->subst);
862           
863         if ($user_cur->sess == "") 
864           continue;
865         
866         if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) {
867           // Auto logout dell'utente
868           log_rd2("AUTO LOGOUT.".($user_cur->lacc + EXPIRE_TIME_RD)." curtime ".$curtime);
869           
870           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
871             log_auth($user_cur->sess, "Autologout session.");
872             
873             $user_cur->reset();
874             
875             log_rd2("AUTO LOGOUT.");
876             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
877               $this->room_wakeup(&$user_cur);
878             else if ($user_cur->subst == 'standup')
879               $this->room_outstandup(&$user_cur);
880             else
881               log_rd2("LOGOUT FROM WHAT ???");
882           }
883         }
884
885         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < $curtime) { // lo rimettiamo in piedi
886           if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
887             $this->room_wakeup(&$user_cur);
888             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
889             /* 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" */
890             $user_cur->comm[$user_cur->step % COMM_N] .=  show_notify("<br>Sei stato inattivo per ".(EXPIRE_TIME_SMAMMA/60.0)." minuti. <br><br>Quindi ritorni tra i <b>Giocatori in piedi</b>.", 0, "torna ai tavoli", 400, 100);
891             $user_cur->step_inc();
892           }
893         }
894       }
895       log_rd2("GARBAGE UPDATED!");
896       
897       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
898       $ismod = TRUE;
899     }
900
901     return ($ismod);
902   }
903
904   function show_room($user_step, &$user)
905   {
906     log_main("show_room: username: ".$user->name);
907     
908     $ret = sprintf('gst.st = %d; ',  $user_step);
909
910     if ($user->flags & USER_FLAG_LISTAUTH) {
911       $ret .= 'list_set(\'auth\', false, \'(solo aut.)\' ); ';
912     }
913     else {
914       $ret .= 'list_set(\'all\', false, \'\' ); ';
915     }
916
917     if ($user->subst == 'standup')
918       $ret .= "tra.show(); ";
919     else
920       $ret .= "tra.hide(); ";
921
922     $ret .= sprintf('stat = "%s";',  $user->stat);
923     
924     $ret .= root_wellcome($user);
925     $ret .= sprintf('subst = "%s";', $user->subst);
926     $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
927     $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
928     $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>";', $itin, xcape($user->name), $itou);
929     for ($i = 0 ; $i < TABLES_N ; $i++) {
930       $ret .= $this->table_content($user, $i);
931       // $ret .= table_act_content(($user->subst == 'standup'), $this->table[$i]->player_n, $i, $user->table, 
932       //                          ($this->table[$i]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
933       $ret .=  $this->table[$i]->act_content($user);
934       if ($this->table[$i]->wag_own != NULL) 
935         $ret .= sprintf('tra.add(%d, "%s: %s"); ', $i,  $this->table[$i]->wag_own->name, $this->table[$i]->wag_com);
936       else 
937         $ret .= sprintf('tra.rem(%d); ', $i);
938     }
939     $ret .= $this->standup_content($user);
940     
941     return ($ret);
942   }
943   
944
945   function room_wakeup(&$user)
946   {
947     $table_idx = $user->table;
948     $table = &$this->table[$table_idx];
949
950     log_main("WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
951
952     $curtime = time();
953
954     $from_table = ($user->stat == "table");
955     if ($from_table) {
956       log_main("WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
957
958       for ($i = 0 ; $i < $table->player_n ; $i++) {
959         $user_cur = &$this->user[$table->player[$i]];
960         log_main("PREIMPOST: INLOOP name: ".$user_cur->name);
961
962         if ($user_cur != $user) {
963           $user_cur->stat_set("room");
964           $user_cur->subst = "sitdown";
965           $user_cur->laccwr = $curtime;
966         }
967         else if ($user->sess != "") {
968           $user_cur->stat_set("room");
969           $user_cur->subst = "standup";
970           $user_cur->laccwr = $curtime;
971           $user_cur->table = -1;
972         }
973       }
974     }
975     else {
976       $user->stat_set("room");
977       $user->subst = "standup";
978       $user->laccwr = $curtime;
979     }
980     
981     $remove_wagon = false;
982     if($table->wag_own == $user) {
983       $remove_wagon = true;
984       $table->wag_reset($curtime);
985       
986     }
987     
988
989     /* aggiorna l'array dei giocatori al tavolo. */
990     $table->user_rem(&$this, &$user);
991
992     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
993       $user_cur = &$this->user[$i];
994       if ($user_cur->sess == '' || $user_cur->stat != 'room')
995         continue;
996       
997       log_main("VALORI: name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
998
999       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1000       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
1001         $ret .= 'gst.st_loc++; the_end=true; window.onunload = null; window.onbeforeunload = null; document.location.assign("index.php");|';
1002         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
1003         log_main("DOCUMENT.index.php: from table");
1004       }
1005       else if ($user_cur->stat == "room") {
1006         log_main("DOCUMENT.index.php: from table");
1007
1008         $ret .= $this->table_content($user_cur, $table_idx);
1009         $ret .= $this->standup_content($user_cur);
1010         
1011         // $ret .= table_act_content(FALSE, 0, $table_idx, $user->table, FALSE);
1012         $ret .= $table->act_content($user);
1013
1014         if ($user_cur == $user) {
1015           // set the new status 
1016           $ret .=  'subst = "standup"; tra.show(); ';
1017           // clean the action buttons in other tables
1018           for ($e = 0 ; $e < TABLES_N ; $e++) {
1019             if ($this->table[$e]->player_n < PLAYERS_N) {
1020               // $ret .= table_act_content(TRUE, 0, $e, $user->table, 
1021               //                           ($this->table[$e]->auth_only == FALSE ? TRUE : $user->flags & USER_FLAG_AUTH));
1022               $ret .= $this->table[$e]->act_content($user);
1023             }
1024           }
1025         }
1026         else {
1027           // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
1028           //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1029           $ret .= $table->act_content($user_cur);
1030         }
1031       }
1032       log_wr("ROOM_WAKEUP: ".$ret);
1033       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1034       $user_cur->step_inc();
1035     }
1036   }
1037
1038   function room_join_wakeup(&$user, $update_lacc = FALSE, $trans_delta)
1039   {
1040     $table_idx = $user->table;
1041     $table = &$this->table[$table_idx];
1042     
1043     log_main("JOIN_WAKEUP: begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
1044
1045     $curtime = time();
1046     $user_wup = array();
1047     $user_wup_n = 0;
1048     $user_tab = array();
1049     $user_tab_n = 0;
1050     log_main("JOIN WAKEUP: from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1051     
1052     for ($i = 0 ; $i < $table->player_n ; $i++) {
1053       $user_cur = &$this->user[$table->player[$i]];
1054       log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1055       if ($user_cur->sess != "") {
1056         if ($update_lacc == TRUE) {
1057           $user_cur->laccwr = $curtime;
1058         }
1059         log_main("cur: ".$user_cur->name."  subst: ".$user_cur->subst);
1060         if ($user_cur->subst == "shutdowned") {
1061           $user_cur->stat_set("room");
1062           $user_cur->subst = "sitdown";
1063         }
1064         else if ($user_cur->subst == "shutdowner") {
1065           $user_cur->stat_set("room");
1066           $user_cur->subst = "standup";
1067           $user_cur->table = -1;
1068           $user_wup[$user_wup_n++] = &$user_cur;
1069           
1070           $remove_wagon = false;
1071           if($table->wag_own == $user_cur) {
1072             $remove_wagon = true;
1073             $table->wag_reset($curtime);
1074           }
1075         }
1076         $user_tab[$user_tab_n++] = &$user_cur;
1077       }
1078     }
1079
1080     for ($wup_idx = 0 ; $wup_idx < $user_wup_n  ; $wup_idx++)
1081       $table->user_rem(&$this, &$user_wup[$wup_idx]);
1082
1083     /* aggiorna l'array dei giocatori al tavolo. */
1084
1085     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1086       log_main("START LOOP");
1087       $user_cur = &$this->user[$i];
1088       if ($user_cur->sess == '' || $user_cur->stat != 'room') {
1089         log_main("name: ".$user_cur->name."skip   subst: ".$user_cur->subst);
1090         continue;
1091       }
1092
1093       log_main("___");
1094       log_main("VALORI name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
1095
1096       $ret = "gst.st = ".($user_cur->step+1)."; ".($remove_wagon ? sprintf("tra.rem(%d);",$table_idx) : "");
1097       if ($user_cur->stat == "room") {
1098         log_main("DOCUMENT.index.php from table");
1099
1100         $ret .= $this->table_content($user_cur, $table_idx);
1101         $ret .= $this->standup_content($user_cur);
1102         
1103         // $ret .= table_act_content(FALSE, 0, $table_idx, $user_cur->table,
1104         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1105         $ret .= $table->act_content($user_cur);
1106
1107
1108         for ($tab_idx = 0 ; $tab_idx < $user_tab_n  ; $tab_idx++)
1109           if ($user_cur == $user_tab[$tab_idx]) 
1110             break;
1111
1112         // for users that wakeup the room will be reconstructed by index_rd.php
1113         if ($tab_idx < $user_tab_n) {
1114           log_main("PRE show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1115
1116 //        ARRAY_POP DISABLED
1117 //        if ($trans_delta == 0)
1118 //          while (array_pop($user_cur->comm) != NULL);
1119
1120           $user_cur->trans_step = $user_cur->step + 1 + $trans_delta;
1121           $user_cur->comm[$user_cur->step % COMM_N] = "";
1122           $user_cur->step_inc();
1123           $user_cur->comm[$user_cur->step % COMM_N] = $this->show_room(($user_cur->step + 1), &$user_cur);
1124           $user_cur->step_inc();
1125           log_main("POST show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1126
1127           continue;
1128         }
1129         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
1130
1131         log_main("JOIN_WAKEUP more");
1132         // $ret .= table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table,
1133         //                           ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1134         $ret .= $table->act_content($user_cur);
1135
1136         log_main("JOIN_WAKEUP end more");
1137       }
1138       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
1139       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1140       $user_cur->step_inc();
1141     }
1142   }
1143
1144   function room_outstandup(&$user)
1145   {
1146     $this->room_sitdown(&$user, -1);
1147   }
1148   
1149   function table_update(&$user)
1150   {
1151     log_main("table_update: pre - USER: ".$user->name);
1152
1153     $table_idx = $user->table;
1154
1155     if ($table_idx > -1) 
1156       $table = &$this->table[$table_idx];
1157     
1158     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1159       $ret = "";
1160       $user_cur = &$this->user[$i];
1161       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1162       continue;
1163       
1164       $ret = "gst.st = ".($user_cur->step+1)."; ";
1165       if ($table_idx > -1)
1166         $ret .= $this->table_content($user_cur, $table_idx);
1167       
1168       if ($user_cur == $user) {
1169         $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1170         $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1171         $ret .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', $itin, xcape($user->name), $itou);
1172       }
1173       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1174       $user_cur->step_inc();
1175     }
1176
1177     log_main("table_update: post");
1178   }
1179
1180   function room_sitdown(&$user, $table_idx)
1181   {
1182     log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1183
1184     $train_app = "";
1185
1186     if ($table_idx > -1 && $table_idx < TABLES_N) { 
1187       $table = &$this->table[$table_idx];
1188
1189       // wagon shutdown 
1190       if ($table->wag_own != NULL && $table->player_n == PLAYERS_N) {        
1191         for ($i = 0 ; $i < TABLES_N ; $i++) {
1192           $user_cur =& $this->user[$table->player[$i]];
1193           if ($user_cur == $table->wag_own) {
1194             $train_app = sprintf("tra.rem(%d); ", $table_idx); 
1195             $table->wag_reset(time());
1196             break;
1197           }
1198         }
1199       }
1200     }
1201
1202     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1203       $ret = "";
1204       $user_cur = &$this->user[$i];
1205       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1206       continue;
1207       
1208       $ret = "gst.st = ".($user_cur->step+1)."; ".$train_app;
1209       if ($table_idx > -1)
1210       $ret .= $this->table_content($user_cur, $table_idx);
1211       $ret .= $this->standup_content($user_cur);
1212       
1213       if ($user_cur == $user) {
1214         $ret .=  'subst = "sitdown"; tra.hide(); ';
1215         // clean the action buttons in other tables
1216         for ($e = 0 ; $e < TABLES_N ; $e++) {
1217           // $ret .= table_act_content(FALSE, 0, $e, $user_cur->table, FALSE);
1218           $ret .= $this->table[$e]->act_content($user_cur);
1219         }
1220       }
1221       else if ($table_idx > -1) {
1222         if ($table->player_n == PLAYERS_N) {
1223           // $ret .= table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table,
1224           ///                      ($table->auth_only == FALSE ? TRUE : $user_cur->flags & USER_FLAG_AUTH));
1225           $ret .= $table->act_content($user_cur);
1226         }
1227       }
1228       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1229       $user_cur->step_inc();
1230     }
1231   }
1232
1233   function chatt_send(&$user, $mesg)
1234   {
1235     GLOBAL $G_alarm_passwd;
1236     $only_you = FALSE;
1237     
1238     // common settings
1239     $msg = substr($mesg, 6, 128);
1240     $curtime = time();
1241     $dt = date("H:i ", $curtime);
1242
1243     //
1244     //  Compute actions
1245     //
1246
1247     $to_user     = FALSE;
1248     $to_all      = FALSE;
1249     $to_room     = FALSE;
1250     $to_tabl     = FALSE;
1251     $is_normchat = FALSE;
1252     $update_room = FALSE;
1253
1254     if (strcmp($msg,  "/tav") == 0 || 
1255         strncmp($msg, "/tav ", 5) == 0) {
1256       do {
1257         if ($user->stat != 'room' || $user->subst != 'sitdown') {
1258           /* 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>" */
1259           $msg = "<br>Per attivare il messaggio di segnalazione del tavolo occorre essere seduti.<br><br>";
1260           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1261
1262           break;
1263         }
1264
1265         $table = &$this->table[$user->table];
1266         
1267         if ($table->wag_own != NULL) {
1268           $msg = "<br>Il messaggio di segnalazione del tavolo &egrave; gi&agrave; attivato.<br><br>";
1269           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1270
1271           break;
1272         }
1273
1274         $dtime = $curtime - $table->wag_tout;
1275         if ($dtime  < EXPIRE_TIME_WAG) {
1276           $msg = sprintf("<br>Il messaggio di segnalazione del tavolo<br>&egrave; disattivato ancora per %d second%s.<br><br>",
1277                          EXPIRE_TIME_WAG - $dtime, (EXPIRE_TIME_WAG - $dtime == 1 ? "o" : "i"));
1278           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1279
1280           break;
1281         }
1282         
1283         $msg = substr($msg, 5);
1284         
1285         $table->wag_set($user, $msg);
1286         $to_user = sprintf('tra.add(%d, "%s");', $user->table, xcape(sprintf("%s: %s", $user->name, $msg)));
1287         $to_room = $to_user;
1288         
1289       } while (0);
1290     } // /tav chat command
1291
1292     else if (strncmp($msg, "/alarm ", 7) == 0) {
1293       if (strncmp($msg, "/alarm to ", 10) == 0) {
1294         $sp_pos = strpos($msg, " ", 10);
1295         $target = substr($msg, 10, $sp_pos - 10);
1296         $alarm_check = "/alarm to ".$target." ".$G_alarm_passwd." ";
1297       }
1298       else {
1299         $target = "";
1300         $alarm_check = "/alarm ".$G_alarm_passwd." ";
1301       }
1302       do {
1303         if (strncmp($msg, $alarm_check, strlen($alarm_check)) != 0) {
1304           /* MLANG: "<br>La password digitata non &egrave; corretta.<br><br>" */
1305           $msg = "<br>La password digitata non &egrave; corretta.<br><br>";
1306           $to_user = show_notify($msg, 0, "chiudi", 400, 100);
1307
1308           break;
1309         }
1310
1311         /* MLANG: "Alarm <b>%s</b> inviato a <b>%s</b>." */
1312         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Alarm <b>%s</b> inviato a <b>%s</b>.");', 
1313                            $dt, NICKSERV, xcape(substr($msg, strlen($alarm_check))), 
1314                            ($target == "" ? "tutti" : xcape($target)) );
1315
1316         $msg = sprintf("<br><b>%s<br><br>%s</b><br><br>",
1317                        $dt.NICKSERV, xcape(substr($msg, strlen($alarm_check))));
1318         /* MLANG: "chiudi" */
1319         $to_all = show_notify($msg, 0, "chiudi", 400, 120);
1320       } while (0);
1321     } // /alarm chat command
1322     else if (strncmp($msg, "/listen ", 8) == 0) {
1323       $arg = substr($msg, 8);
1324
1325       if (strcasecmp($arg, "auth") == 0) {
1326         $user->flags |= USER_FLAG_LISTAUTH;
1327         $to_user = 'list_set(\'auth\', true, \'(solo aut.)\'); ';
1328       }
1329       else {
1330         $user->flags &= ~USER_FLAG_LISTAUTH;
1331         $to_user = 'list_set(\'all\', true, \'\'); ';
1332       }
1333     }
1334     else if (strncmp($msg, "/garante", 8) == 0) {
1335       if ($user->flags & USER_FLAG_AUTH) {
1336         $to_user = sprintf('authbox(300,200);');
1337       }
1338       else {
1339         /* 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." */
1340         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Per autenticare qualcuno devi a tua volta essere autenticato.</b>");', $dt, NICKSERV);
1341       }
1342     }
1343     else if (strncmp($msg, "/mesgtoadm", 8) == 0) {
1344       if ($user->flags & USER_FLAG_AUTH) {
1345         $to_user = sprintf('mesgtoadmbox(500,300);');
1346       }
1347       else {
1348         /* MLANG: "<b>Per inviare un messaggio devi essere autenticato.</b>" */
1349         $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Per inviare un messaggio devi essere autenticato.</b>");', $dt, NICKSERV);
1350       }
1351     }
1352     else if (strncmp($msg, "/nick ", 6) == 0) {
1353       log_main("chatt_send BEGIN");
1354
1355       do {
1356         if (($name_new = validate_name(substr($msg, 6))) == FALSE) {
1357           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Il nickname deve contenere almeno una lettera dell\'alfabeto o una cifra.");', $dt, NICKSERV);
1358           break;
1359         }
1360
1361         $msg = "COMMAND ".$msg;
1362         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1363           $user_cur = &$this->user[$i];
1364
1365           if ($user_cur->sess == '')
1366             continue;
1367           if ($user_cur->name == $name_new)
1368             break;
1369           }
1370         if ($i <  MAX_PLAYERS) {
1371           $to_user = sprintf('chatt_sub("%s", [2, "%s"],"Nickname <b>%s</b> gi&agrave; in uso.");', $dt, NICKSERV, xcape($name_new));
1372           break;
1373         }
1374         
1375         /* 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>" */
1376         if ($user->flags & USER_FLAG_AUTH) {
1377           if (strcasecmp($user->name,$name_new) != 0) {
1378             if ($user->subst == 'standup' || ($user->subst != 'standup' && $this->table[$user->table]->auth_only == FALSE)) {
1379               $user->flags &= ~USER_FLAG_AUTH; // Remove auth if name changed
1380               for ($i = 0 ; $i < TABLES_N ; $i++) {
1381                 $to_user .= $this->table[$i]->act_content($user);
1382               }
1383             }
1384             else {
1385               $to_user = sprintf('chatt_sub("%s", [2, "%s"],"<b>Non puoi cambiare nick a un tavolo per soli autenticati.</b>");', $dt, NICKSERV);
1386               break;
1387             }
1388           }
1389         }
1390         $user->name = $name_new; // OK - nick changed
1391         /* se nome gia' in uso, segnala cosa potrebbe capitare */
1392         if (($user->flags & USER_FLAG_AUTH) == 0) {
1393           $userdb = new LoginDB();
1394           /* 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>" */
1395           if ($userdb->login_exists($name_new)) {
1396             $to_user .= sprintf('chatt_sub("%s", [2, "%s"],"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>");', $dt, NICKSERV, xcape($name_new));
1397           }
1398         }
1399
1400         log_main("chatt_send start set");
1401
1402         $update_room = TRUE;
1403       } while (0);
1404     } // nick chat command
1405
1406     else if (strncmp($msg, "/st ", 4) == 0) {
1407       log_main("chatt_send BEGIN");
1408
1409       do {
1410         $st_str = substr($msg, 4);
1411         
1412         if (strcasecmp($st_str, "normale") == 0) {
1413           $st = USER_FLAG_S_NORM;
1414         }
1415         else if (strcasecmp($st_str, "pausa") == 0) {
1416           $st = USER_FLAG_S_PAU;
1417         }
1418         else if (strcasecmp($st_str, "fuori") == 0) {
1419           $st = USER_FLAG_S_OUT;
1420         }
1421         else if (strcasecmp($st_str, "cane") == 0) {
1422           $st = USER_FLAG_S_DOG;
1423         }
1424         else if (strcasecmp($st_str, "cibo") == 0) {
1425           $st = USER_FLAG_S_EAT;
1426         }
1427         else if (strcasecmp($st_str, "lavoro") == 0) {
1428           $st = USER_FLAG_S_WRK;
1429         }
1430         else if (strcasecmp($st_str, "sigaretta") == 0) {
1431           $st = USER_FLAG_S_SMK;
1432         }
1433         else if (strcasecmp($st_str, "presente") == 0) {
1434           $st = USER_FLAG_S_EYE;
1435         }
1436         else {
1437           /* MLANG: "Questo stato non esiste." */
1438           $to_user = sprintf('chatt_sub("%s", [2,"%s"],"Questo stato non esiste.");', $dt, NICKSERV);
1439           break;
1440         }
1441
1442         log_main("chatt_send start set");
1443         if (($user->flags & USER_FLAG_S_ALL) != $st) {
1444           $update_room = TRUE;
1445           $user->flags = ($user->flags & ~USER_FLAG_S_ALL) | $st;
1446         }
1447       } while (0);
1448     } // nick chat command
1449
1450     else { // normal chat line
1451       $is_normchat = TRUE;
1452       if ($curtime < ($user->chat_ban + $user->chat_dlt)) {
1453         $only_you = TRUE;
1454         $user->chat_dlt = $user->chat_dlt * 2; 
1455         if ($user->chat_dlt > 120)
1456           $user->chat_dlt = 120; 
1457       }
1458       else if ($user->chat_lst == $msg)
1459         $only_you = TRUE;
1460       else if ($curtime - $user->chattime[($user->chat_cur + 1) % CHAT_N] < CHAT_ILL_TIME) {
1461         $user->chat_ban = $curtime;
1462         $user->chat_dlt = 5;
1463         $only_you = TRUE;
1464       }
1465       else {
1466         $user->chat_ban = 0;
1467         $user->chat_dlt = 0;
1468       }
1469
1470       if ($only_you) {
1471         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape("== chat ban =="));
1472       }
1473       else {
1474         $to_user = sprintf('chatt_sub("%s", [%d, "%s"],"%s");', $dt, $user->flags, xcape($user->name), xcape($msg));
1475         // temporary silentiation for troll (will became array check)
1476         if (strcasecmp($user->name,'JackRokka') != 0 && $user->sess != '47ea653f602e8')
1477           $to_room = $to_user;
1478       }
1479
1480       log_legal($curtime, $user, 
1481                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$msg);
1482       
1483       $user->chat_lst = "$msg";
1484       $user->chattime[$user->chat_cur % CHAT_N] = $curtime;
1485       $user->chat_cur++;
1486     }
1487
1488     if ($to_all) {
1489       $to_room = $to_all;
1490       $to_tabl = $to_all;
1491     }
1492
1493     //
1494     //  Output to clients
1495     //
1496
1497     if ($to_user != FALSE) {
1498       $user->comm[$user->step % COMM_N] =  "gst.st = ".($user->step+1)."; ";
1499       $user->comm[$user->step % COMM_N] .= $to_user;
1500       $user->step_inc();
1501     }
1502
1503     if ($to_room != FALSE) {
1504       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1505         $user_cur = &$this->user[$i];
1506         if ($target != "" && $user_cur->name != $target)
1507           continue;
1508         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1509         if ($user_cur->sess == '' || $user_cur->stat == 'table' || $user_cur == $user)
1510           continue;
1511         
1512         if ($is_normchat == TRUE) {
1513           if ($user_cur->flags & USER_FLAG_LISTAUTH) {
1514             if (($user->flags & USER_FLAG_AUTH) == 0) {
1515               continue;
1516             }
1517           }
1518         }
1519   
1520         $user_cur->comm[$user_cur->step % COMM_N] =  "gst.st = ".($user_cur->step+1)."; ";
1521         $user_cur->comm[$user_cur->step % COMM_N] .= $to_room; 
1522         $user_cur->step_inc();
1523       }
1524     }
1525     
1526     if ($to_tabl) {
1527       // FIXME BRISK4: include for each kind of table
1528       require_once("briskin5/Obj/briskin5.phh");
1529       // Before all align times with table timeout
1530       for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1531         $table_cur =& $this->table[$table_idx];
1532         // if the table is complete and exists its shared mem we get the info about users lacc
1533         
1534         if ($table_cur->player_n == PLAYERS_N) {
1535           log_main("PLAYERS == N TABLE ".$table_idx);
1536         
1537           if (($sem = Briskin5::lock_data($table_idx)) != FALSE) { 
1538             log_main("bin5 lock data success");
1539             
1540             $no_recovery = FALSE;
1541             if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1542               if ($table_cur->table_token != $bri->table_token) {
1543                 log_main("ERROR: not matching table_token. Room: ".$table_cur->table_token."  Table: ".$bri->table_token);
1544                 $bri = FALSE;
1545               }
1546             }
1547             
1548             if ($bri != FALSE) {
1549               $bri_table = &$bri->table[0];
1550               for ($i = 0 ; $i < $bri_table->player_n ; $i++) {
1551                 // stat must be "table" by definition
1552                 $bri_user =& $bri->user[$i];
1553               
1554                 if ($target != "" && $bri_user->name != $target)
1555                   continue;
1556                 log_main("writa: ".$user_mesg);
1557                 $bri_user->comm[$bri_user->step % COMM_N] = "gst.st = ".($bri_user->step+1)."; ";
1558                 $bri_user->comm[$bri_user->step % COMM_N] .= $to_tabl;
1559                 $bri_user->step_inc();
1560               }
1561               Briskin5::save_data(&$bri);
1562             }
1563             Briskin5::unlock_data($sem);
1564           } // bri::lock_data
1565         } //  if ($table_cur->player_n == PLAYERS_N) {
1566       } //  for ($table_idx = 0 ; $table_idx < TABLES_N ; $table_idx++) {
1567     } // if ($to_tabl == true ...
1568
1569     if ($update_room) {
1570       if ($user->stat == 'room' && $user->subst == 'standup') {
1571         $this->standup_update(&$user);
1572       }
1573       else if ($user->stat == 'room' && $user->subst == 'sitdown') {
1574         log_main("chatt_send pre table update");
1575         $this->table_update(&$user);
1576         log_main("chatt_send post table update");
1577       }
1578     } // if ($update_room ...
1579
1580     return;
1581   } // function chatt_send( ...
1582
1583   function &get_user($sess, &$idx)
1584   {
1585     GLOBAL $PHP_SELF, $G_false;
1586
1587     if (validate_sess($sess)) {
1588       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1589         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1590           // find it
1591           $idx = $i;
1592           $ret = &$this->user[$i];
1593           return ($ret);
1594         }
1595       }
1596       log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1597       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1598       // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1599     }
1600     else {
1601       log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
1602     }
1603
1604     return ($G_false);
1605   }
1606
1607   
1608
1609   /*
1610    * function &add_user(&$room, &$sess, &$idx, $name, $pass, $ip)
1611    *
1612    * RETURN VALUE:
1613    *   if ($idx >  -1    && ret == FALSE)  =>  duplicated nick
1614    *   if ($idx == -2    && ret == FALSE)  =>  invalid name
1615    *   if ($idx == -3    && ret == FALSE)  =>  wrong password
1616    *   if ($idx == -1    && ret == FALSE)  =>  no space left
1617    *   if ($idx ==  0    && ret == user)   =>  SUCCESS
1618    *   if ($idx == -$idx && ret == user)   =>  SUCCESS (but the login exists in the auth db 
1619    */
1620
1621
1622
1623   function &add_user(&$sess, &$idx, $name, $pass, $ip)
1624   {
1625     GLOBAL $G_false, $CO_list;
1626
1627     $idx = 0;
1628
1629     $authenticate = FALSE;
1630     $login_exists = FALSE;
1631     $ghost = -1;
1632     $ghost_auth = FALSE;
1633     $idx = -1;
1634     $idfree = -1;
1635     
1636     if (($name_new = validate_name($name)) == FALSE) {
1637       $idx = -2;
1638       return ($G_false);
1639     }
1640
1641     log_auth("XXX", sprintf("ARRIVA: [%s] pass:[%s]", $sess, ($pass == FALSE ? "FALSE" : $pass)));
1642     if (validate_sess($sess) == FALSE) 
1643       $sess = "";
1644
1645     /* if pass != FALSE verify the login with pass */
1646     log_auth("XXX", "auth1");
1647     $userdb = new LoginDB();
1648     if ($pass != FALSE) {
1649       log_auth("XXX", "auth2");
1650       $authenticate = $userdb->login_verify($name_new, $pass);
1651       log_auth("XXX", "authenticate: ".($authenticate == TRUE ? "TRUE" : "FALSE"));
1652       
1653       if ($authenticate == FALSE) {
1654         $idx = -3;
1655         return ($G_false);
1656       }
1657     }
1658     else {
1659       $login_exists =  $userdb->login_exists($name_new);
1660     }
1661     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1662       /* free user ? */
1663       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1664         if ($idx == -1)
1665           $idx = $i;
1666       }
1667       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
1668         $idfree = $i;
1669         continue; // NOTE: CHECK IT !!
1670       }
1671       if (strcasecmp($this->user[$i]->name, $name_new) == 0) {
1672         if ($authenticate == FALSE) {
1673           $idx = $i;
1674           break;
1675         }
1676         else {
1677           $ghost = $i;
1678           $ghost_auth = ($this->user[$i]->flags & USER_FLAG_AUTH);
1679         }
1680       }
1681     }
1682     if ($idx == -1)
1683       $idx = $idfree;
1684
1685     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1686
1687     if ($ghost > -1 && $ghost_auth && $authenticate) {
1688       /* swap session */
1689
1690       $ghost_user =& $this->user[$ghost];
1691       $curtime = time();
1692       $ghost_user->step_inc();
1693       if ($sess == "") {
1694         $sess = uniqid(""); 
1695         $ghost_user->sess = $sess;
1696       }
1697       else {
1698         $ghost_user->sess = $sess;
1699       }
1700       
1701       // If user at the table we need to update the table data too
1702       $table_idx = $ghost_user->table;
1703       if ($ghost_user->stat == "table" && $this->table[$table_idx]->player_n == PLAYERS_N) {
1704         // FIXME BRISK4: include for each kind of table
1705         require_once("briskin5/Obj/briskin5.phh");
1706         if (($brisem = Briskin5::lock_data($table_idx)) != FALSE) { 
1707           if (($bri = &Briskin5::load_data($table_idx)) != FALSE) {
1708             if ($bri->the_end != TRUE) {
1709               $bri->user[$ghost_user->table_pos]->step_inc();
1710               $bri->user[$ghost_user->table_pos]->sess = $sess;
1711               Briskin5::save_data(&$bri);
1712             }
1713           }
1714           Briskin5::unlock_data($brisem);
1715         }
1716       }
1717
1718       $idx = $ghost;
1719       return ($this->user[$ghost]);
1720     }
1721     else if ($idx != -1 && $i == MAX_PLAYERS) {
1722       /* SUCCESS */
1723       $curtime = time();
1724       if ($sess == "") {
1725         $sess = uniqid("");
1726         $this->user[$idx]->sess = $sess;
1727       }
1728       else {
1729         $this->user[$idx]->sess = $sess;
1730       }
1731       $this->user[$idx]->name = $name_new; // OK - add new user
1732       $this->user[$idx]->stat_set("room");
1733       $this->user[$idx]->step_set(0);
1734       while (array_pop($this->user[$idx]->comm) != NULL);
1735       $this->user[$idx]->subst = "standup";
1736       $this->user[$idx]->lacc =   $curtime;
1737       $this->user[$idx]->laccwr = $curtime;
1738       $this->user[$idx]->bantime = 0;
1739       $this->user[$idx]->ip = $ip;
1740
1741       $this->user[$idx]->flags = ($authenticate ? USER_FLAG_AUTH : 0x00);
1742       
1743       if ($authenticate) {
1744         $this->user[$idx]->flags |= USER_FLAG_LISTAUTH;
1745
1746         if (isset($CO_list) && strcmp($CO_list, "all") == 0) {
1747           $this->user[$idx]->flags &= ~USER_FLAG_LISTAUTH;
1748         }
1749       }
1750       
1751       if ($ghost > -1) {
1752         log_main("ghost: rename!");
1753         $ghost_user =& $this->user[$ghost];
1754
1755         if ($ghost_auth == FALSE) {
1756           for ($sfx = 1 ; $sfx <= MAX_PLAYERS ; $sfx++) {
1757             $ghostname = 'ghost'.$sfx;
1758             for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1759               if (strcmp("", $this->user[$i]->sess) == 0) 
1760                 continue;
1761               
1762               if (strcmp($this->user[$i]->name, $ghostname) == 0) {
1763                 $ghostname = '';
1764                 break;
1765               }
1766             }
1767             if ($ghostname != '')
1768               break;
1769           }
1770           
1771           $ghost_user->name = $ghostname;
1772           
1773           if ($ghost_user->stat == 'room' && $ghost_user->subst == 'standup') {
1774             $this->standup_update(&$ghost_user);
1775           }
1776           else {
1777             log_main("chatt_send pre table update");
1778             $this->table_update(&$ghost_user);
1779           log_main("chatt_send post table update");
1780           }
1781         } // if ($ghost_auth == FALSE
1782         else {
1783           // FIXME: cacciare il vecchio utente room && table (if needed)
1784           $ghost_user->the_end = TRUE;
1785           $ghost_user->lacc = 0;
1786           $this->garbage_manager(TRUE);
1787         }
1788       } //  if ($ghost > -1) {
1789
1790       log_main(sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1791       $real_idx = $idx;
1792       if ($login_exists)
1793         $idx = -($idx + 1);
1794       return ($this->user[$real_idx]);
1795     }
1796
1797     return ($G_false);
1798   }
1799   
1800   function standup_update(&$user)
1801   {
1802     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1803       $user_cur = &$this->user[$i];
1804       if ($user_cur->sess == '')
1805         continue;
1806
1807       log_main("STANDUP START: ".$user_cur->stat);
1808       
1809       if ($user_cur->stat == 'room') {
1810         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".$this->standup_content($user_cur);
1811         if ($user_cur == $user) {
1812           $itin = ($user->flags & USER_FLAG_AUTH ? "<i>" : "");
1813           $itou = ($user->flags & USER_FLAG_AUTH ? "</i>" : "");
1814
1815           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s%s%s</b>: ";', 
1816                                                                $itin, xcape($user->name), $itou);
1817         }
1818         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1819         
1820         $user_cur->step_inc();
1821       }
1822     }
1823   }
1824
1825   // Static functions
1826   function &init_data()
1827   {
1828     $room =& new Room();
1829     
1830     return $room;
1831   }
1832   
1833
1834   function &load_data() 
1835   {
1836     GLOBAL $G_false, $sess;
1837     $doexit = FALSE;
1838     do {
1839       if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1840         log_main("ftok failed");
1841         $doexit = TRUE;
1842         break;
1843       }
1844     
1845       if (($shm_sz = sharedmem_sz($tok)) == -1) {
1846         log_main("shmop_open failed");
1847       }
1848         
1849       if ($shm_sz == -1)
1850         $shm_sz = SHM_DIMS_MIN;
1851
1852       if ($shm = shm_attach($tok, $shm_sz)) {
1853         $room = @shm_get_var($shm, $tok);
1854         
1855         log_only("bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
1856         if (isset($room)) 
1857           log_only("bri count ".count($room));
1858         
1859         if ($room == FALSE) {
1860           log_only("INIT MAIN DATA");
1861           
1862           $room =& Room::init_data();
1863           if (@shm_put_var($shm, $tok, $room) == FALSE) {
1864             log_only("PUT_VAR FALLITA ".strlen(serialize($room)));
1865             log_only(serialize($room));
1866           }
1867         }
1868         $room->shm_sz = $shm_sz;
1869         
1870         shm_detach($shm);
1871       }
1872       $ret = &$room;
1873       return ($ret);
1874     } while (0);
1875     
1876     if ($doexit)
1877       exit();
1878     
1879     return ($G_false);
1880   }
1881   
1882
1883   function save_data(&$room) 
1884   {
1885     GLOBAL $sess;
1886     
1887     $shm =   FALSE;
1888     
1889     // var_dump($room);
1890     
1891     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) 
1892       return (FALSE);
1893     
1894     while ($room->shm_sz < SHM_DIMS_MAX) {
1895       if (($shm = shm_attach($tok, $room->shm_sz)) == FALSE)
1896         break;
1897       
1898       // log_only("PUT_VAR DI ".strlen(serialize($room)));
1899       if (shm_put_var($shm, $tok, $room) != FALSE) {
1900         shm_detach($shm);
1901         return (TRUE);
1902       }
1903       if (shm_remove($shm) === FALSE) {
1904         log_only("REMOVE FALLITA");
1905         break;
1906       }
1907       shm_detach($shm);
1908       $room->shm_sz += SHM_DIMS_DLT;
1909     } 
1910
1911     if ($shm)
1912       shm_detach($shm);
1913     
1914     return (FALSE);
1915   }
1916
1917   function lock_data()
1918   {
1919     GLOBAL $sess; 
1920     
1921     //  echo "LOCK: ".FTOK_PATH."/main";
1922     //  exit;
1923     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1924       return (FALSE);
1925     }
1926     // echo "FTOK ".$tok."<br>";
1927     if (($res = sem_get($tok)) == FALSE) {
1928       return (FALSE);
1929     }
1930     if (sem_acquire($res)) {   
1931       log_lock("LOCK room");
1932       return ($res);
1933     }
1934     else
1935       return (FALSE);
1936   }
1937   
1938   function unlock_data($res)
1939   {
1940     GLOBAL $sess; 
1941     
1942     log_lock("UNLOCK room");
1943
1944     return (sem_release($res));
1945   }
1946
1947
1948   function standup_content($user)
1949   {
1950     $ret = "";
1951     $content = "";
1952     
1953     if ($user->stat != 'room')
1954       return;
1955     
1956     for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1957       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
1958         continue;
1959       $ct++;
1960     }
1961     
1962     // $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1963     
1964     $content = ' j_stand_cont( [ ';
1965
1966     for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1967       if ($this->user[$e]->sess == "" || $this->user[$e]->stat != "room" || $this->user[$e]->name == "")
1968         continue;
1969       
1970       $flags = $this->user[$e]->flags;
1971       
1972       if ($this->user[$e]->subst == "standup") {
1973         if ($this->user[$e] == $user) 
1974           { 
1975             $flags |= 1;
1976           }
1977         
1978         $content .= sprintf('%s[ %d, "%s" ]',($ct > 0 ? ', ' : ''), $flags, xcape($this->user[$e]->name));
1979         $ct++;
1980       }
1981     }
1982     $content .= ' ]);';
1983     
1984     return ($content);
1985   }
1986   
1987   function table_content_old($user, $table_idx)
1988   {
1989     $content = "";
1990     $ret = "";
1991     // TODO
1992     //
1993     //   Si possono usare i dati nella classe table
1994     //
1995     
1996     $sess = $user->sess;
1997     $table = &$this->table[$table_idx];
1998     
1999     if ($user->stat != 'room')
2000       return;
2001     
2002     for ($i = 0 ; $i < $table->player_n ; $i++) {
2003       $user_cur = &$this->user[$table->player[$i]];
2004       
2005       if ($user_cur == $user) 
2006         { $hilion = "<b>"; $hilioff = "</b>"; }
2007       else
2008         { $hilion = ""; $hilioff = ""; }
2009       
2010       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2011       
2012       $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
2013     }
2014     /*
2015   for ( ; $i < PLAYERS_N ; $i++)
2016     $content .= "<br>";
2017     */
2018     
2019     $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
2020     
2021     return ($ret);
2022   }
2023
2024
2025   function table_content($user, $table_idx)
2026   {
2027     $content = "";
2028     $ret = "";
2029     // TODO
2030     //
2031     //   Si possono usare i dati nella classe table
2032     //
2033     
2034     $sess = $user->sess;
2035     $table = &$this->table[$table_idx];
2036     
2037     if ($user->stat != 'room')
2038       return;
2039     
2040     $content = "[ ";
2041     for ($i = 0 ; $i < $table->player_n ; $i++) {
2042       $user_cur = &$this->user[$table->player[$i]];
2043
2044       $flags = $user_cur->flags;
2045
2046       if ($user_cur == $user) 
2047         $flags |= 1;
2048       
2049       log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
2050       
2051       $content .= sprintf('%s[ %d, "%s" ]',($i == 0 ? '' : ', '), $flags, xcape($user_cur->name));
2052     }
2053
2054     $content .= ' ]';
2055
2056     $ret .= sprintf('j_tab_cont(%d, %s);', $table_idx, $content);
2057     
2058     return ($ret);
2059   }
2060
2061 } // end class Room
2062
2063 function make_seed()
2064 {
2065   list($usec, $sec) = explode(' ', microtime());
2066   return (float) $sec + ((float) $usec * 100000);
2067 }
2068
2069
2070 function log_only2($log) {
2071   GLOBAL $sess;
2072
2073   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONL2) == 0)
2074     return;
2075
2076   if (isset($sess) == FALSE)
2077     $ssess = "XXXX";
2078   else
2079     $ssess = $sess;
2080
2081   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONL2) == 0)
2082     return;
2083
2084   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2085     fwrite($fp, sprintf("ONL2: [%s] [%s]\n", $ssess, $log));
2086     fclose($fp);
2087   }
2088 }
2089
2090 function log_crit($log) {
2091   GLOBAL $sess;
2092
2093   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CRIT) == 0)
2094     return;
2095
2096   if (isset($sess) == FALSE)
2097     $ssess = "XXXX";
2098   else
2099     $ssess = $sess;
2100
2101   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CRIT) == 0)
2102     return;
2103
2104   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2105     fwrite($fp, sprintf("CRIT: [%s] [%s]\n", $ssess, $log));
2106     fclose($fp);
2107   }
2108 }
2109
2110 function log_only($log) {
2111   GLOBAL $sess;
2112
2113   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONLY) == 0)
2114     return;
2115
2116   if (isset($sess) == FALSE)
2117     $ssess = "XXXX";
2118   else
2119     $ssess = $sess;
2120
2121   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONLY) == 0)
2122     return;
2123
2124   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2125     fwrite($fp, sprintf("ONLY: [%s] [%s]\n", $ssess, $log));
2126     fclose($fp);
2127   }
2128 }
2129
2130 function log_main($log) {
2131   GLOBAL $sess;
2132
2133   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_MAIN) == 0)
2134     return;
2135
2136   if (isset($sess) == FALSE)
2137     $ssess = "XXXX";
2138   else
2139     $ssess = $sess;
2140
2141   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_MAIN) == 0)
2142     return;
2143
2144   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2145     fwrite($fp, sprintf("MAIN: [%s] [%s]\n", $ssess, $log));
2146     fclose($fp);
2147   }
2148 }
2149
2150 function log_rd($log) {
2151   GLOBAL $sess;
2152
2153   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_READ) == 0)
2154     return;
2155
2156   if (isset($sess) == FALSE)
2157     $ssess = "XXXX";
2158   else
2159     $ssess = $sess;
2160
2161   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_READ) == 0)
2162     return;
2163
2164   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2165     fwrite($fp, sprintf("READ: [%s] [%s]\n", $ssess, $log));
2166     fclose($fp);
2167   }
2168 }
2169
2170 function log_rd2($log) {
2171   GLOBAL $sess;
2172
2173   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_REA2) == 0)
2174     return;
2175
2176   if (isset($sess) == FALSE)
2177     $ssess = "XXXX";
2178   else
2179     $ssess = $sess;
2180       
2181   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_REA2) == 0)
2182     return;
2183
2184   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2185     fwrite($fp, sprintf("REA2: [%s] [%s]\n", $ssess, $log));
2186     fclose($fp);
2187   }
2188 }
2189
2190 function log_send($log) {
2191   GLOBAL $sess;
2192
2193   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SEND) == 0)
2194     return;
2195
2196   if (isset($sess) == FALSE)
2197     $ssess = "XXXX";
2198   else
2199     $ssess = $sess;
2200       
2201   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SEND) == 0)
2202     return;
2203
2204   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2205     fwrite($fp, sprintf("SEND: [%s] [%s]\n", $ssess, $log));
2206     fclose($fp);
2207   }
2208 }
2209
2210 function log_lock($log) {
2211   GLOBAL $sess;
2212
2213   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOCK) == 0)
2214     return;
2215
2216   if (isset($sess) == FALSE)
2217     $ssess = "XXXX";
2218   else
2219     $ssess = $sess;
2220
2221   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOCK) == 0)
2222     return;
2223
2224   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2225     fwrite($fp, sprintf("LOCK: [%s] [%s]\n", $ssess, $log));
2226     fclose($fp);
2227   }
2228 }
2229
2230 function log_wr($log) {
2231   GLOBAL $sess;
2232
2233   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_WRIT) == 0)
2234     return;
2235
2236   if (isset($sess) == FALSE)
2237     $ssess = "XXXX";
2238   else
2239     $ssess = $sess;
2240       
2241   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_WRIT) == 0)
2242     return;
2243
2244   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2245     fwrite($fp, sprintf("WRIT: [%s] [%s]\n", $ssess, $log));
2246     fclose($fp);
2247   }
2248 }
2249
2250 function log_load($log) {
2251   GLOBAL $sess;
2252
2253   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOAD) == 0)
2254     return;
2255
2256   if (isset($sess) == FALSE)
2257     $ssess = "XXXX";
2258   else
2259     $ssess = $sess;
2260
2261   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOAD) == 0)
2262     return;
2263       
2264   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2265     fwrite($fp, sprintf("LOAD: [%s] [%s]\n", $ssess, $log));
2266     fclose($fp);
2267   }
2268 }
2269
2270 function log_auth($sess, $log) {
2271   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_AUTH) == 0)
2272     return;
2273
2274   if (( (BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_AUTH) == 0)
2275     return;
2276
2277   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
2278     fwrite($fp, sprintf("AUTH: [%s] [%d] [%s]\n", $sess, time(), $log));
2279     fclose($fp);
2280   }
2281 }
2282
2283
2284 // function log_legal($curtime, $sess, $name, $where, $mesg) 
2285 function log_legal($curtime, &$user, $where, $mesg) 
2286 {
2287   GLOBAL $_SERVER;
2288
2289   if (($fp = @fopen(LEGAL_PATH."/legal.log", 'a')) != FALSE) {
2290     /* Unix time | session | nickname | IP | where was | mesg */
2291     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
2292                         ($user->flags & USER_FLAG_AUTH ? 'A' : 'N'),
2293                         $user->name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
2294     fclose($fp);
2295   }
2296 }
2297
2298
2299
2300
2301 function lock_banlist()
2302 {
2303   if (($tok = @ftok(FTOK_PATH."/main", "L")) == -1) {
2304     echo "FTOK FAILED";
2305     exit;
2306   }
2307   if (($res = sem_get($tok)) == FALSE) {
2308     echo "SEM_GET FAILED";
2309     exit;
2310   }
2311   if (sem_acquire($res)) 
2312     return ($res);
2313   else
2314     return (FALSE);
2315 }
2316
2317 function unlock_banlist($res)
2318 {
2319   return (sem_release($res));
2320 }
2321
2322 function table_act_content_old($isstanding, $sitted, $table, $cur_table)
2323 {
2324   $ret = "";
2325
2326   if ($isstanding) {
2327     if ($sitted < PLAYERS_N) {
2328       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
2329     }
2330   }
2331   else {
2332     if ($table == $cur_table)
2333       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
2334     else
2335       $ret = "";
2336   }
2337   return ($ret);
2338 }
2339
2340 function table_act_content($isstanding, $sitted, $table, $cur_table, $allowed)
2341 {
2342   $ret = "";
2343
2344   if ($isstanding) {
2345     if ($sitted < PLAYERS_N) {
2346       if ($allowed)
2347         $act = 'sit';
2348       else
2349         $act = 'reserved';
2350     }
2351   }
2352   else {
2353     if ($table == $cur_table)
2354       $act = 'wake';
2355     else
2356       $act = 'none';
2357   }
2358
2359   if ($act != '')
2360     $ret = sprintf('j_tab_act_cont(%d, \'%s\');', $table, $act);
2361
2362   return ($ret);
2363 }
2364
2365 function show_notify($text, $tout, $butt, $w, $h)
2366 {
2367   log_main("SHOW_NOTIFY: ".$text);
2368   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
2369 }
2370
2371 function multoval($mult)
2372 {
2373   if ($mult == 2)
2374     return ("doppio");
2375   else if ($mult == 4)
2376     return ("quadruplo");
2377   else
2378     return (sprintf("%d-plo", $mult));
2379 }
2380
2381
2382 function root_wellcome($user)
2383 {
2384   GLOBAL $root_wellarr;
2385   $ret = "";
2386
2387   $curtime = time();
2388   $dt = date("H:i ", $curtime);
2389     
2390   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
2391     $ret .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, str_replace('"', '\"', $root_wellarr[$i]));
2392
2393   return ($ret);
2394 }
2395
2396
2397
2398 function validate_sess($sess) 
2399 {
2400   if (strlen($sess) == SESS_LEN) 
2401     return (TRUE);
2402   else
2403     return (FALSE);
2404 }
2405
2406 function validate_name($name) 
2407 {
2408   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
2409
2410   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2411     $c = $name_new[$i];
2412     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2413       return ($name_new);
2414   }
2415
2416   return (FALSE);
2417 }
2418
2419 function playsound($filename)
2420 {
2421   return (sprintf('playsound("flasou", "%s");', $filename));
2422 }
2423
2424 function secstoword($secs)
2425 {
2426   $mins = floor($secs / 60);
2427   $secs = $secs % 60;
2428   if ($mins > 0) 
2429     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
2430   
2431   if ($secs > 0)
2432     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
2433   
2434   return ($ret);
2435 }
2436
2437 function sharedmem_sz($tok)
2438 {
2439   if (($shm_id = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
2440     log_main("shmop_open failed");
2441     return (-1);
2442   }
2443   $shm_sz = shmop_size($shm_id);
2444   shmop_close($shm_id);
2445   
2446   log_main("shm_sz: ".$shm_sz."   SHM_DIMS: ".SHM_DIMS);
2447   return ($shm_sz);
2448 }    
2449
2450 class Warrant {
2451   function lock_data()
2452   {
2453     GLOBAL $sess; 
2454     
2455     if (($tok = @ftok(FTOK_PATH."/warrant", "B")) == -1) {
2456       return (FALSE);
2457     }
2458     // echo "FTOK ".$tok."<br>";
2459     if (($res = sem_get($tok)) == FALSE) {
2460       return (FALSE);
2461     }
2462     if (sem_acquire($res)) {   
2463       log_lock("LOCK room");
2464       return ($res);
2465     }
2466     else
2467       return (FALSE);
2468   }
2469   
2470   function unlock_data($res)
2471   {
2472     GLOBAL $sess; 
2473     
2474     log_lock("UNLOCK room");
2475     
2476     return (sem_release($res));
2477   }
2478
2479   
2480 }
2481 ?>