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