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