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