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