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