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