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