disabled comm flush optimization
[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.3";
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 //        ARRAY_POP DISABLED
1009 //        if ($trans_delta == 0)
1010 //          while (array_pop($user_cur->comm) != NULL);
1011
1012           $user_cur->trans_step = $user_cur->step + 1 + $trans_delta;
1013           $user_cur->comm[$user_cur->step % COMM_N] = "";
1014           $user_cur->step_inc();
1015           $user_cur->comm[$user_cur->step % COMM_N] = show_room(&$this, ($user_cur->step + 1), &$user_cur);
1016           $user_cur->step_inc();
1017           log_main("POST show_room username: ".$user_cur->name."  STEP: ".$user_cur->step);
1018
1019           continue;
1020         }
1021         log_main("JOIN_WAKEUP wup_idx ".$wup_idx."  wup_n ".$user_wup_n);
1022
1023         log_main("JOIN_WAKEUP more");
1024         $act_content = table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table);
1025         $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
1026         log_main("JOIN_WAKEUP end more");
1027       }
1028       log_wr("ROOM_JOIN_WAKEUP: ".$ret);
1029       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1030       $user_cur->step_inc();
1031     }
1032   }
1033
1034   function room_outstandup(&$user)
1035   {
1036     $this->room_sitdown(&$user, -1);
1037   }
1038   
1039   function table_update(&$user)
1040   {
1041     log_main("table_update: pre - USER: ".$user->name);
1042
1043     $table_idx = $user->table;
1044
1045     if ($table_idx > -1) 
1046       $table = &$this->table[$table_idx];
1047     
1048     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1049       $ret = "";
1050       $user_cur = &$this->user[$i];
1051       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1052       continue;
1053       
1054       $ret = "gst.st = ".($user_cur->step+1)."; ";
1055       if ($table_idx > -1)
1056         $ret .= table_content($this, $user_cur, $table_idx);
1057       
1058       if ($user_cur == $user) {
1059         $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
1060       }
1061       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1062       $user_cur->step_inc();
1063     }
1064
1065     log_main("table_update: post");
1066   }
1067
1068   function room_sitdown(&$user, $table_idx)
1069   {
1070     log_main("room_sitdown ".($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
1071
1072     if ($table_idx > -1) 
1073       $table = &$this->table[$table_idx];
1074     
1075     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1076       $ret = "";
1077       $user_cur = &$this->user[$i];
1078       if ($user_cur->sess == '' || $user_cur->stat != 'room')
1079       continue;
1080       
1081       $ret = "gst.st = ".($user_cur->step+1)."; ";
1082       if ($table_idx > -1)
1083       $ret .= table_content($this, $user_cur, $table_idx);
1084       $ret .= standup_content($this, $user_cur);
1085       
1086       if ($user_cur == $user) {
1087         $ret .=  'subst = "sitdown"; ';
1088         // clean the action buttons in other tables
1089         for ($e = 0 ; $e < TABLES_N ; $e++) {
1090           $act_content = table_act_content(FALSE, 0, $e, $user_cur->table);
1091           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, $act_content);
1092         }
1093       }
1094       else if ($table_idx > -1) {
1095         if ($table->player_n == PLAYERS_N) {
1096           $act_content = table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table);
1097           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
1098         }
1099       }
1100       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1101       $user_cur->step_inc();
1102     }
1103   }
1104
1105   function chatt_send(&$user, $mesg)
1106   {
1107     if ($user->stat == 'table') {
1108       $table = &$this->table[$user->table];
1109     }
1110     
1111     $user_mesg = substr($mesg,6);
1112     
1113     $timecur = time();
1114     
1115     $dt = date("H:i ", $timecur);
1116     if (strncmp($user_mesg, "/nick ", 6) == 0) {
1117       log_main("chatt_send BEGIN");
1118
1119       if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
1120           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1121           $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));
1122           $user->step_inc();
1123
1124           return;
1125       }
1126       $user_mesg = "COMMAND ".$user_mesg;
1127       // Search dup name
1128       // change
1129       // update local graph
1130       // update remote graphs
1131       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1132         $user_cur = &$this->user[$i];
1133         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1134         if ($user_cur->sess == '')
1135           continue;
1136         if ($user_cur->name == $name_new) {
1137           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1138           $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Nickname <b>%s</b> gi&agrave; in uso.");', $dt.NICKSERV, xcape($name_new));
1139           $user->step_inc();
1140           break;
1141         }
1142       }
1143       if ($i == MAX_PLAYERS) {
1144         $user->name = $name_new;
1145
1146       log_main("chatt_send start set");
1147         
1148
1149         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1150           log_main("chatt_send set loop");
1151           
1152           $user_cur = &$this->user[$i];
1153           if ($user_cur->sess == '')
1154             continue;
1155           if ($user_cur->stat == 'room') {
1156             if ($user->stat == 'room' && $user->subst == 'standup') {
1157               $this->standup_update(&$user);
1158             }
1159             else if ($user->stat == 'room' && $user->subst == 'sitdown' ||
1160                      $user->stat == 'table') {
1161               log_main("chatt_send pre table update");
1162
1163               $this->table_update(&$user);
1164
1165               log_main("chatt_send post table update");
1166             }
1167           }
1168           else if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
1169             $table = &$this->table[$user->table];
1170             
1171             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1172             $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1173                 xcape($this->user[$table->player[($user_cur->table_pos)%PLAYERS_N]]->name),
1174                 xcape($this->user[$table->player[($user_cur->table_pos+1)%PLAYERS_N]]->name),
1175                 xcape($this->user[$table->player[($user_cur->table_pos+2)%PLAYERS_N]]->name),
1176                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3)%PLAYERS_N]]->name)),
1177                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4)%PLAYERS_N]]->name)));
1178             if ($user_cur == $user)
1179               $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>";', 
1180                                                                    xcape($user->name,ENT_COMPAT,"UTF-8"));
1181             $user_cur->step_inc();
1182           }
1183         }
1184       }
1185     }
1186     else {
1187       for ($i = 0 ; $i < ($user->stat == 'room' ? MAX_PLAYERS : PLAYERS_N) ; $i++) {
1188         if ($user->stat == 'room') {
1189           $user_cur = &$this->user[$i];
1190           if ($user_cur->sess == '' || $user_cur->stat != 'room')
1191             continue;
1192         }
1193         else {
1194           $user_cur = &$this->user[$table->player[$i]];
1195         }
1196         
1197         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1198         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s","%s");',
1199                                                              $dt.xcape($user->name), xcape($user_mesg));
1200         $user_cur->step_inc();
1201       }
1202       log_legal($timecur, $user->sess, $user->name, 
1203                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$user_mesg);
1204     }
1205   }
1206
1207   function &get_user($sess, &$idx)
1208   {
1209     GLOBAL $PHP_SELF, $G_false;
1210
1211     if (validate_sess($sess)) {
1212       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1213         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1214           // find it
1215           $idx = $i;
1216           $ret = &$this->user[$i];
1217           return ($ret);
1218         }
1219       }
1220       log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1221       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1222       // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1223     }
1224     else {
1225       log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
1226     }
1227
1228     return ($G_false);
1229   }
1230
1231   /*
1232    * function &add_user(&$room, &$sess, &$idx, $name, $ip)
1233    *
1234    * RETURN VALUE:
1235    *   if ($idx != -1 && ret == FALSE)  =>  duplicated nick
1236    *   if ($idx == -2 && ret == FALSE)  =>  invalid name
1237    *   if ($idx == -1 && ret == FALSE)  =>  no space left
1238    *   if (ret == TRUE)                 =>  SUCCESS
1239    */
1240   function &add_user(&$sess, &$idx, $name, $ip)
1241   {
1242     GLOBAL $G_false;
1243
1244     $idx = -1;
1245     $idfree = -1;
1246     
1247     if (($name_new = validate_name($name)) == FALSE) {
1248       $idx = -2;
1249       return ($G_false);
1250     }
1251
1252     log_auth("XXX", sprintf("ARRIVA: [%s]", $sess));
1253     if (validate_sess($sess) == FALSE) 
1254       $sess = "";
1255
1256     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1257       /* free user ? */
1258       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1259         if ($idx == -1)
1260           $idx = $i;
1261       }
1262       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
1263         $idfree = $i;
1264       }
1265       if (strcmp($this->user[$i]->name, $name_new) == 0) {
1266         $idx = $i;
1267         break;
1268       }
1269     }
1270     if ($idx == -1)
1271       $idx = $idfree;
1272
1273     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1274
1275     if ($idx != -1 && $i == MAX_PLAYERS) {
1276       /* SUCCESS */
1277       $curtime = time();
1278       if ($sess == "") {
1279         $this->user[$idx]->sess = uniqid("");
1280         $sess = $this->user[$idx]->sess;
1281         
1282       }
1283       else {
1284         $this->user[$idx]->sess = $sess;
1285       }
1286       $this->user[$idx]->name = $name_new;
1287       $this->user[$idx]->stat_set("room");
1288       $this->user[$idx]->step_set(0);
1289       while (array_pop($this->user[$idx]->comm) != NULL);
1290       $this->user[$idx]->subst = "standup";
1291       $this->user[$idx]->lacc =   $curtime;
1292       $this->user[$idx]->laccwr = $curtime;
1293       $this->user[$idx]->bantime = 0;
1294       $this->user[$idx]->ip = $ip;
1295       log_main(sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1296       
1297       return ($this->user[$idx]);
1298     }
1299
1300     return ($G_false);
1301   }
1302   
1303   function standup_update(&$user)
1304   {
1305     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1306       $user_cur = &$this->user[$i];
1307       if ($user_cur->sess == '')
1308         continue;
1309
1310       log_main("STANDUP START: ".$user_cur->stat);
1311       
1312       if ($user_cur->stat == 'room') {
1313         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".standup_content($this, $user_cur);
1314         if ($user_cur == $user)
1315           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
1316         
1317         log_main("FROM STANDUP: NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1318         
1319         $user_cur->step_inc();
1320       }
1321     }
1322   }
1323
1324   // Static functions
1325   function &init_data()
1326   {
1327     $room =& new Room();
1328     
1329     return $room;
1330   }
1331   
1332
1333   function &load_data() 
1334   {
1335     GLOBAL $G_false, $sess;
1336     $doexit = FALSE;
1337     do {
1338       if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1339         log_main("ftok failed");
1340         $doexit = TRUE;
1341         break;
1342       }
1343     
1344       if (($shm_sz = sharedmem_sz($tok)) == -1) {
1345         log_main("shmop_open failed");
1346       }
1347         
1348       if ($shm_sz == -1)
1349         $shm_sz = SHM_DIMS_MIN;
1350
1351       if ($shm = shm_attach($tok, $shm_sz)) {
1352         $room = @shm_get_var($shm, $tok);
1353         
1354         log_only("bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
1355         if (isset($room)) 
1356           log_only("bri count ".count($room));
1357         
1358         if ($room == FALSE) {
1359           log_only("INIT MAIN DATA");
1360           
1361           $room =& Room::init_data();
1362           if (@shm_put_var($shm, $tok, $room) == FALSE) {
1363             log_only("PUT_VAR FALLITA ".strlen(serialize($room)));
1364             log_only(serialize($room));
1365           }
1366         }
1367         $room->shm_sz = $shm_sz;
1368         
1369         shm_detach($shm);
1370       }
1371       $ret = &$room;
1372       return ($ret);
1373     } while (0);
1374     
1375     if ($doexit)
1376       exit();
1377     
1378     return ($G_false);
1379   }
1380   
1381
1382   function save_data(&$room) 
1383   {
1384     GLOBAL $sess;
1385     
1386     $ret =   FALSE;
1387     $shm =   FALSE;
1388     
1389     // var_dump($room);
1390     
1391     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) 
1392       return (FALSE);
1393     
1394     while ($room->shm_sz < SHM_DIMS_MAX) {
1395       if (($shm = shm_attach($tok, $room->shm_sz)) == FALSE)
1396         break;
1397       
1398       // log_only("PUT_VAR DI ".strlen(serialize($room)));
1399       if (shm_put_var($shm, $tok, $room) != FALSE) {
1400         shm_detach($shm);
1401         return (TRUE);
1402       }
1403       if (shm_remove($shm) === FALSE) {
1404         log_only("REMOVE FALLITA");
1405         break;
1406       }
1407       shm_detach($shm);
1408       $room->shm_sz += SHM_DIMS_DLT;
1409     } 
1410
1411     if ($shm)
1412       shm_detach($shm);
1413     
1414     return ($ret);
1415   }
1416
1417   function lock_data()
1418   {
1419     GLOBAL $sess; 
1420     
1421     //  echo "LOCK: ".FTOK_PATH."/main";
1422     //  exit;
1423     if (($tok = @ftok(FTOK_PATH."/main", "B")) == -1) {
1424       echo "FTOK FAILED";
1425       exit;
1426     }
1427     // echo "FTOK ".$tok."<br>";
1428     if (($res = sem_get($tok)) == FALSE) {
1429       echo "SEM_GET FAILED";
1430       exit;
1431     }
1432     if (sem_acquire($res)) {   
1433       log_lock("LOCK room");
1434       return ($res);
1435     }
1436     else
1437       return (FALSE);
1438   }
1439   
1440   function unlock_data($res)
1441   {
1442     GLOBAL $sess; 
1443     
1444     log_lock("UNLOCK room");
1445
1446     return (sem_release($res));
1447   }
1448 } // end class Room
1449
1450 function make_seed()
1451 {
1452   list($usec, $sec) = explode(' ', microtime());
1453   return (float) $sec + ((float) $usec * 100000);
1454 }
1455
1456
1457 function log_only2($log) {
1458   GLOBAL $sess;
1459
1460   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONL2) == 0)
1461     return;
1462
1463   if (isset($sess) == FALSE)
1464     $ssess = "XXXX";
1465   else
1466     $ssess = $sess;
1467
1468   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONL2) == 0)
1469     return;
1470
1471   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1472     fwrite($fp, sprintf("ONL2: [%s] [%s]\n", $ssess, $log));
1473     fclose($fp);
1474   }
1475 }
1476
1477 function log_crit($log) {
1478   GLOBAL $sess;
1479
1480   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_CRIT) == 0)
1481     return;
1482
1483   if (isset($sess) == FALSE)
1484     $ssess = "XXXX";
1485   else
1486     $ssess = $sess;
1487
1488   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_CRIT) == 0)
1489     return;
1490
1491   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1492     fwrite($fp, sprintf("CRIT: [%s] [%s]\n", $ssess, $log));
1493     fclose($fp);
1494   }
1495 }
1496
1497 function log_only($log) {
1498   GLOBAL $sess;
1499
1500   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_ONLY) == 0)
1501     return;
1502
1503   if (isset($sess) == FALSE)
1504     $ssess = "XXXX";
1505   else
1506     $ssess = $sess;
1507
1508   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_ONLY) == 0)
1509     return;
1510
1511   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1512     fwrite($fp, sprintf("ONLY: [%s] [%s]\n", $ssess, $log));
1513     fclose($fp);
1514   }
1515 }
1516
1517 function log_main($log) {
1518   GLOBAL $sess;
1519
1520   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_MAIN) == 0)
1521     return;
1522
1523   if (isset($sess) == FALSE)
1524     $ssess = "XXXX";
1525   else
1526     $ssess = $sess;
1527
1528   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_MAIN) == 0)
1529     return;
1530
1531   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1532     fwrite($fp, sprintf("MAIN: [%s] [%s]\n", $ssess, $log));
1533     fclose($fp);
1534   }
1535 }
1536
1537 function log_rd($log) {
1538   GLOBAL $sess;
1539
1540   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_READ) == 0)
1541     return;
1542
1543   if (isset($sess) == FALSE)
1544     $ssess = "XXXX";
1545   else
1546     $ssess = $sess;
1547
1548   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_READ) == 0)
1549     return;
1550
1551   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1552     fwrite($fp, sprintf("READ: [%s] [%s]\n", $ssess, $log));
1553     fclose($fp);
1554   }
1555 }
1556
1557 function log_rd2($log) {
1558   GLOBAL $sess;
1559
1560   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_REA2) == 0)
1561     return;
1562
1563   if (isset($sess) == FALSE)
1564     $ssess = "XXXX";
1565   else
1566     $ssess = $sess;
1567       
1568   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_REA2) == 0)
1569     return;
1570
1571   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1572     fwrite($fp, sprintf("REA2: [%s] [%s]\n", $ssess, $log));
1573     fclose($fp);
1574   }
1575 }
1576
1577 function log_send($log) {
1578   GLOBAL $sess;
1579
1580   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_SEND) == 0)
1581     return;
1582
1583   if (isset($sess) == FALSE)
1584     $ssess = "XXXX";
1585   else
1586     $ssess = $sess;
1587       
1588   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_SEND) == 0)
1589     return;
1590
1591   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1592     fwrite($fp, sprintf("SEND: [%s] [%s]\n", $ssess, $log));
1593     fclose($fp);
1594   }
1595 }
1596
1597 function log_lock($log) {
1598   GLOBAL $sess;
1599
1600   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOCK) == 0)
1601     return;
1602
1603   if (isset($sess) == FALSE)
1604     $ssess = "XXXX";
1605   else
1606     $ssess = $sess;
1607
1608   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOCK) == 0)
1609     return;
1610
1611   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1612     fwrite($fp, sprintf("LOCK: [%s] [%s]\n", $ssess, $log));
1613     fclose($fp);
1614   }
1615 }
1616
1617 function log_wr($log) {
1618   GLOBAL $sess;
1619
1620   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_WRIT) == 0)
1621     return;
1622
1623   if (isset($sess) == FALSE)
1624     $ssess = "XXXX";
1625   else
1626     $ssess = $sess;
1627       
1628   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_WRIT) == 0)
1629     return;
1630
1631   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1632     fwrite($fp, sprintf("WRIT: [%s] [%s]\n", $ssess, $log));
1633     fclose($fp);
1634   }
1635 }
1636
1637 function log_load($log) {
1638   GLOBAL $sess;
1639
1640   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_LOAD) == 0)
1641     return;
1642
1643   if (isset($sess) == FALSE)
1644     $ssess = "XXXX";
1645   else
1646     $ssess = $sess;
1647
1648   if (( (BRISK_DEBUG | ($ssess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_LOAD) == 0)
1649     return;
1650       
1651   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1652     fwrite($fp, sprintf("LOAD: [%s] [%s]\n", $ssess, $log));
1653     fclose($fp);
1654   }
1655 }
1656
1657 function log_auth($sess, $log) {
1658   if (BRISK_SINGLE_SESS == "" && (BRISK_DEBUG & DBG_AUTH) == 0)
1659     return;
1660
1661   if (( (BRISK_DEBUG | ($sess == BRISK_SINGLE_SESS ? BRISK_SINGLE_DEBUG : 0) ) & DBG_AUTH) == 0)
1662     return;
1663
1664   if (($fp = @fopen(LEGAL_PATH."/brisk.log", 'a')) != FALSE) {
1665     fwrite($fp, sprintf("AUTH: [%s] [%d] [%s]\n", $sess, time(), $log));
1666     fclose($fp);
1667   }
1668 }
1669
1670
1671 function log_legal($timecur, $sess, $name, $where, $mesg) 
1672 {
1673   GLOBAL $_SERVER;
1674
1675   if (($fp = @fopen(LEGAL_PATH."/legal.log", 'a')) != FALSE) {
1676     /* Unix time | session | nickname | IP | where was | mesg */
1677     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $timecur, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
1678     fclose($fp);
1679   }
1680 }
1681
1682
1683
1684
1685 function lock_banlist()
1686 {
1687   if (($tok = @ftok(FTOK_PATH."/main", "L")) == -1) {
1688     echo "FTOK FAILED";
1689     exit;
1690   }
1691   if (($res = sem_get($tok)) == FALSE) {
1692     echo "SEM_GET FAILED";
1693     exit;
1694   }
1695   if (sem_acquire($res)) 
1696     return ($res);
1697   else
1698     return (FALSE);
1699 }
1700
1701 function unlock_banlist($res)
1702 {
1703   return (sem_release($res));
1704 }
1705
1706 function table_act_content($isstanding, $sitted, $table, $cur_table)
1707 {
1708   $ret = "";
1709
1710   if ($isstanding) {
1711     if ($sitted < PLAYERS_N) {
1712       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
1713     }
1714   }
1715   else {
1716     if ($table == $cur_table)
1717       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
1718     else
1719       $ret = "";
1720   }
1721   return ($ret);
1722 }
1723
1724 function table_content($room, $user, $table_idx)
1725 {
1726   $content = "";
1727   $ret = "";
1728   // TODO
1729   //
1730   //   Si possono usare i dati nella classe table
1731   //
1732
1733   $sess = $user->sess;
1734   $table = &$room->table[$table_idx];
1735
1736   if ($user->stat != 'room')
1737     return;
1738
1739   for ($i = 0 ; $i < $table->player_n ; $i++) {
1740     $user_cur = &$room->user[$table->player[$i]];
1741
1742     if ($user_cur == $user) 
1743         { $hilion = "<b>"; $hilioff = "</b>"; }
1744       else
1745         { $hilion = ""; $hilioff = ""; }
1746
1747     log_main($user_cur->name. sprintf(" IN TABLE [%d]", $table_idx));
1748     
1749     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1750   }
1751   /*
1752   for ( ; $i < PLAYERS_N ; $i++)
1753     $content .= "<br>";
1754   */
1755
1756   $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1757   
1758   return ($ret);
1759 }
1760
1761 function standup_content(&$room, $user)
1762 {
1763   $ret = "";
1764   $content = "";
1765
1766   if ($user->stat != 'room')
1767     return;
1768
1769   for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1770     if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
1771       continue;
1772     $ct++;
1773   }
1774
1775   $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1776
1777   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1778     if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
1779       continue;
1780
1781
1782     if ($room->user[$e]->subst == "standup") {
1783       if (($ct % 4) == 0) {
1784         $content .= '<tr>';
1785       }
1786       if ($room->user[$e] == $user) 
1787         { $hilion = "<b>"; $hilioff = "</b>"; }
1788       else
1789         { $hilion = ""; $hilioff = ""; }
1790
1791       $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($room->user[$e]->name), $hilioff);
1792       if (($ct % 4) == 3) {
1793         $content .= '</tr>';
1794       }
1795       $ct++;
1796     }
1797   }
1798   $content .= '</table>';
1799         
1800   $content2 = '<input class=\\"button\\" name=\\"logout\\" value=\\"Esco.\\" onclick=\\"window.onunload = null; act_logout();\\" type=\\"button\\">';
1801   $ret .= sprintf('$("standup").innerHTML = "%s";  $("esco").innerHTML = "%s";', 
1802                   $content, $content2);
1803
1804   return ($ret);
1805 }
1806
1807
1808 function show_notify($text, $tout, $butt, $w, $h)
1809 {
1810   log_main("SHOW_NOTIFY: ".$text);
1811   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
1812 }
1813
1814 function briscola_show($room, $table, $user)
1815 {
1816   $ptnadd = "";
1817   $ret = "";
1818
1819   if ($table->asta_card == 9) 
1820     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
1821   
1822   /* text of caller cell */
1823   if ($user->table_pos == $table->asta_win) 
1824     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
1825   else 
1826     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
1827                     xcape($room->user[$table->player[$table->asta_win]]->name), $ptnadd);
1828
1829   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1830                   $table->asta_win);
1831   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1832   $ret .= sprintf('$("caller").style.visibility = "visible";');
1833   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1834   $ret .= sprintf('$("astalascio").style.visibility = "";');
1835   $ret .= sprintf('$("asta").style.visibility = "hidden";');
1836   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1837   
1838   return ($ret);
1839 }
1840
1841
1842 function game_result($asta_pnt, $pnt)
1843 {
1844   if ($asta_pnt == 61) {
1845     if ($pnt > 60)
1846       return (1);
1847     else if ($pnt == 60)
1848       return (0);
1849     else
1850       return (-1);
1851   }
1852   else {
1853     if ($pnt >= $asta_pnt)
1854       return (1);
1855     else
1856       return (-1);
1857   }
1858 }
1859
1860 function multoval($mult)
1861 {
1862   if ($mult == 2)
1863     return ("doppio");
1864   else if ($mult == 4)
1865     return ("quadruplo");
1866   else
1867     return (sprintf("%d-plo", $mult));
1868 }
1869
1870 function show_table_info(&$room, &$table, $table_pos)
1871 {
1872   $ret = "";
1873   $user = &$room->user[$table->player[$table_pos]];
1874
1875   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1876   $noty = sprintf('<table class=\"points\"><tr><th></th>');
1877   
1878   // Names.
1879   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1880     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($room->user[$table->player[$i]]->name));
1881   $noty .= sprintf("</tr>");
1882
1883   // Points.
1884   log_main("show_table_info: pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1885
1886   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1887     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1888     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1889       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1890     $noty .= "</tr>";
1891   }
1892
1893   // Total points.
1894   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1895   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1896     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1897   $noty .= "</tr></table>";
1898
1899   if ($table->old_reason != "") {
1900     $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1901   }
1902
1903   if ($table->old_win != -1) {
1904     $win = $table->player[$table->old_win];
1905     $fri = $table->player[$table->old_friend];
1906
1907     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1908
1909     if ($win != $fri) {
1910       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
1911                        xcape($room->user[$win]->name),
1912                        xcape($room->user[$fri]->name));
1913       if ($table->old_pnt == 120) {
1914         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
1915       }
1916       else {
1917         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
1918                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1919                           'pi&ugrave; di 60'), $table->old_pnt,
1920                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1921       }
1922     }
1923     else {
1924       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
1925                        xcape($room->user[$win]->name));
1926       if ($table->old_pnt == 120) {
1927         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
1928       }
1929       else {
1930         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
1931                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1932                           'pi&ugrave; di 60'), $table->old_pnt,
1933                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1934       }
1935     }
1936   }
1937   if ($table->mazzo == $table_pos) 
1938     $noty .= "Fai <b>tu</b> il mazzo,";
1939   else {
1940     $unam = xcape($room->user[$table->player[$table->mazzo]]->name);
1941     $noty .= "Il mazzo a <b>$unam</b>,";
1942   }
1943
1944   if ($user->subst == 'asta') {
1945     if ($table->asta_win == -1)  // auction case
1946       $curplayer = $table->gstart % PLAYERS_N;
1947     else 
1948       $curplayer = $table->asta_win;
1949   }
1950   else if ($user->subst == 'game') {
1951     $curplayer = ($table->gstart + $table->turn) % PLAYERS_N;
1952   }
1953
1954
1955   if ($curplayer == $table_pos) {
1956     $noty .= " tocca a <b>te</b> giocare.";
1957   }
1958   else {
1959     $unam = xcape($room->user[$table->player[$curplayer]]->name);
1960     $noty .= " tocca a <b>$unam</b> giocare.";
1961   }
1962
1963   if ($table->mult > 1) {
1964     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
1965   }
1966   $noty .= "<hr><br>";
1967
1968   $ret .= show_notify($noty, 3000, "torna alla partita", 500, 400);
1969   
1970   return ($ret);
1971 }
1972
1973 function root_wellcome($user)
1974 {
1975   GLOBAL $root_wellarr;
1976   $ret = "";
1977
1978   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
1979     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $root_wellarr[$i]));
1980
1981   return ($ret);
1982 }
1983
1984 function table_wellcome($user)
1985 {
1986   GLOBAL $table_wellarr;
1987   $ret = "";
1988
1989   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
1990     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $table_wellarr[$i]));
1991
1992   return ($ret);
1993 }
1994
1995 function show_room(&$room, $user_step, &$user)
1996 {
1997   log_main("show_room: username: ".$user->name);
1998
1999
2000   $ret = sprintf('gst.st = %d;',  $user_step);
2001   $ret .= sprintf('stat = "%s";',  $user->stat);
2002
2003   $ret .= root_wellcome($user);
2004   $ret .= sprintf('subst = "%s";', $user->subst);
2005   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
2006   for ($i = 0 ; $i < TABLES_N ; $i++) {
2007     $ret .= table_content($room, $user, $i);
2008     $act_content = table_act_content(($user->subst == 'standup'), 
2009                                      $room->table[$i]->player_n, $i, $user->table);
2010     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
2011   }
2012   $ret .= standup_content($room, $user);
2013   
2014   return ($ret);
2015 }
2016
2017
2018
2019 /* show table 
2020 is_transition (is from room to table ?)
2021 is_again      (is another game)
2022
2023 Examples                    of $is_transition, $is_again:
2024   from reload of the page:              FALSE, FALSE
2025   from sitdown in room:                  TRUE, FALSE
2026   from table: asta cmd e tutti passano:  TRUE, TRUE
2027   from table: fine partita:              TRUE, TRUE
2028  */
2029 function show_table(&$room, &$user, $sendstep, $is_transition, $is_again)
2030 {
2031   $table_idx = $user->table;
2032   $table = &$room->table[$table_idx];
2033   $table_pos = $user->table_pos;
2034
2035   $ret = "table_init();";
2036   $ret .= $table->exitlock_show(&$room->user, $table_pos);
2037   if (!$is_again) {
2038     /* GENERAL STATUS */
2039     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
2040                      $sendstep, $user->stat, $user->subst, $table_pos);
2041
2042     log_rd(sprintf( 'SHOW_TABLE: gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
2043                      $sendstep, $user->stat, $user->subst, $table_pos));
2044
2045     /* BACKGROUND */
2046     $ret .= "background_set();";
2047     
2048     /* USERS INFO */
2049     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
2050     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
2051                     xcape($room->user[$table->player[($table_pos)%PLAYERS_N]]->name),
2052                     xcape($room->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
2053                     xcape($room->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
2054                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
2055                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
2056   }
2057   /* NOTIFY FOR THE CARD MAKER */
2058   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
2059     $ret .= show_table_info(&$room, &$table, $table_pos);
2060   }
2061   if (!$is_again) 
2062     $ret .= table_wellcome($user);
2063
2064   if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
2065     $ret .= playsound("cow.mp3");
2066   }
2067
2068
2069   /* CARDS */
2070   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
2071     $ret .= "|";
2072     
2073     for ($i = 0 ; $i < 8 ; $i++) {
2074       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
2075         $ct = 0;
2076         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
2077           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
2078             $ct++;
2079             if ($ct == $i+1)
2080               break;
2081           }
2082         }
2083         log_rd("O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
2084         
2085         $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
2086                          $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
2087                               $table->card[$o]->value : -1), 
2088                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
2089       }
2090     }    
2091   }
2092   else {
2093     $taked  = array(0,0,0,0,0);
2094     $inhand = array(0,0,0,0,0);
2095     $ontabl  = array(-1,-1,-1,-1,-1);
2096     $cards  = array();
2097
2098     for ($i = 0 ; $i < 40 ; $i++) {
2099       if ($table->card[$i]->stat == 'hand') {
2100         if ($table->card[$i]->owner == $table_pos) {
2101           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
2102         }
2103         $inhand[$table->card[$i]->owner]++;
2104       }
2105       else if ($table->card[$i]->stat == 'take') {
2106         log_main("Card taked: ".$table->card[$i]->value."OWN: ".$table->card[$i]->owner);
2107         $taked[$table->card[$i]->owner]++;
2108       }
2109       else if ($table->card[$i]->stat == 'table') {
2110         $ontabl[$table->card[$i]->owner] = $i;
2111       }
2112     }
2113     $logg = "\n";
2114     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2115       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
2116     }
2117     log_main("Stat table: ".$logg);
2118
2119     /* Set ours cards. */
2120     $oursarg = "";
2121     for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
2122       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
2123     for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
2124       $oursarg .= ($i == 0 ? "" : ", ")."-1";
2125     $ret .= sprintf('card_setours(%s);', $oursarg);
2126
2127     /* Dispose all cards */
2128     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2129       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
2130       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
2131                       $inhand[$i], $taked[$i]);
2132
2133       if ($ontabl[$i] != -1) {
2134         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
2135                         $table->card[$ontabl[$i]]->value, 
2136                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
2137       }
2138     }
2139   }
2140
2141   /* Show auction */
2142   if ($user->subst == 'asta') {
2143
2144     /* show users auction status */
2145     $showst = "";
2146     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2147       $user_cur = &$room->user[$table->player[$i]];
2148       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
2149                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
2150     }
2151     if (PLAYERS_N == 3)
2152         $showst .= ",-2,-2";
2153     $ret .= sprintf('show_astat(%s);', $showst);
2154
2155     if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
2156       /* show card chooser */
2157       $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
2158                       $table->asta_card);
2159     }
2160     else {
2161       /* show auction */
2162       if ($table_pos == ($table->gstart % PLAYERS_N) &&
2163           $table->asta_win == -1) 
2164         $ret .= sprintf('dispose_asta(%d,%d, %s);', 
2165                         $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
2166       else
2167         $ret .= sprintf('dispose_asta(%d,%d, %s);',
2168                         $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
2169     }
2170
2171     /* Remark */
2172     if ($table->asta_win == -1) { // auction case
2173       if ($table_pos == ($table->gstart % PLAYERS_N)) 
2174         $ret .= "remark_on();";
2175       else
2176         $ret .= "remark_off();";
2177     }
2178     else { // chooseed case
2179       if ($table_pos == $table->asta_win) 
2180         $ret .= "remark_on();";
2181       else
2182         $ret .= "remark_off();";
2183     }
2184   }
2185   else if ($user->subst == 'game') {
2186     /* HIGHLIGHT */
2187     if (($table->gstart + $table->turn) % PLAYERS_N == $table_pos) 
2188       $ret .= "is_my_time = true; remark_on();";
2189     else
2190       $ret .= "remark_off();";
2191     
2192     /* WHO CALL AND WATH */
2193     $ret .= briscola_show($room, $table, $user);
2194     
2195   }
2196   return ($ret);
2197 } // end function show_table(...
2198
2199 function calculate_winner(&$table)
2200 {
2201   $briontab = FALSE;
2202   $ontab = array();
2203   $ontid = array();
2204   $cur_win  =  -1;
2205   $cur_val  = 100;
2206   $cur_seed = $table->briscola - ($table->briscola % 10);
2207
2208   for ($i = 0 ; $i < 40 ; $i++) {
2209     if ($table->card[$i]->stat != "table")
2210       continue;
2211
2212     log_wr(sprintf("Card On table: [%d]", $i));
2213
2214     $v = $table->card[$i]->value; 
2215     $ontab[$table->card[$i]->owner] = $v;
2216     $ontid[$table->card[$i]->owner] = $i;
2217     /* se briscola setto il flag */
2218     if (($v - ($v % 10)) == $cur_seed)
2219       $briontab = TRUE;
2220   }
2221
2222   if ($briontab == FALSE) {
2223     $cur_win  = $table->gstart;
2224     $cur_val  = $ontab[$cur_win];
2225     $cur_seed = $cur_val - ($cur_val % 10);
2226   }
2227
2228   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2229     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
2230       if ($ontab[$i] < $cur_val) {
2231         $cur_val = $ontab[$i];
2232         $cur_win = $i;
2233       }
2234     }
2235   }
2236
2237   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
2238     $table->card[$ontid[$i]]->owner = $cur_win;
2239     $table->card[$ontid[$i]]->stat =  "take"; // Card stat
2240   }
2241   return ($cur_win);
2242 }
2243
2244 function calculate_points(&$table)
2245 {
2246   GLOBAL $G_all_points; 
2247
2248   $pro = 0;
2249
2250   if ($table->asta_pnt == 60)
2251     $table->asta_pnt = 61;
2252
2253   $table->old_reason = "";
2254   $table->old_win = $table->asta_win;
2255   $table->old_friend = $table->friend;
2256   $table->old_asta_pnt = $table->asta_pnt;
2257
2258   for ($i = 0 ; $i < 40 ; $i++) {
2259     $ctt = $table->card[$i]->value % 10;
2260     $own = $table->card[$i]->owner;
2261     if ($own == $table->asta_win || $own == $table->friend) 
2262       $pro += $G_all_points[$ctt];
2263   }
2264
2265   log_wr(sprintf("PRO: [%d]", $pro));
2266
2267   
2268   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
2269     $table->points[$table->points_n % MAX_POINTS] = array();
2270     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
2271       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
2272     $table->points_n++;
2273     $table->old_pnt = $pro;
2274     $table->mult *= 2;
2275
2276     return;
2277   }
2278
2279   if ($pro >= $table->asta_pnt) 
2280     $sig = 1;
2281   else
2282     $sig = -1;
2283
2284   $table->points[$table->points_n % MAX_POINTS] = array();
2285   for ($i = 0 ; $i < 5 ; $i++) {
2286     if ($i == $table->asta_win) 
2287       $pt = ($i == $table->friend ? 4 : 2);
2288     else if ($i == $table->friend) 
2289       $pt = 1;
2290     else
2291       $pt = -1;
2292
2293     log_wr(sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
2294
2295     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
2296
2297     log_wr(sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
2298     
2299     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
2300     $table->total[$i] += $pt;
2301   }
2302   $table->points_n++;
2303   $table->old_pnt = $pro;
2304   $table->mult = 1;
2305 }
2306
2307 function validate_sess($sess) 
2308 {
2309   if (strlen($sess) == SESS_LEN) 
2310     return (TRUE);
2311   else
2312     return (FALSE);
2313 }
2314
2315 function validate_name($name) 
2316 {
2317   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
2318
2319   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2320     $c = $name_new[$i];
2321     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2322       return ($name_new);
2323   }
2324
2325   return (FALSE);
2326 }
2327
2328 function playsound($filename)
2329 {
2330   return (sprintf('playsound("flasou", "%s");', $filename));
2331 }
2332
2333 function secstoword($secs)
2334 {
2335   $mins = floor($secs / 60);
2336   $secs = $secs % 60;
2337   if ($mins > 0) 
2338     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
2339   
2340   if ($secs > 0)
2341     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
2342   
2343   return ($ret);
2344 }
2345
2346 function sharedmem_sz($tok)
2347 {
2348   if (($shm_id = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
2349     log_main("shmop_open failed");
2350     return (-1);
2351   }
2352   $shm_sz = shmop_size($shm_id);
2353   shmop_close($shm_id);
2354   
2355   log_main("shm_sz: ".$shm_sz."   SHM_DIMS: ".SHM_DIMS);
2356   return ($shm_sz);
2357 }    
2358
2359
2360 ?>