corretto HELP
[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 -> opzioni internet -> etichetta \\"Generale\\" -> 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_lock($sess, $log) {
963   if (BRISK_DEBUG != TRUE)
964     return;
965
966   if (($fp = @fopen("/tmp/brisk_lock.log", 'a')) != FALSE) {
967     fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
968     fclose($fp);
969   }
970 }
971
972 function log_wr($sess, $log) {
973   if (BRISK_DEBUG != TRUE)
974     return;
975
976   if (($fp = @fopen("/tmp/brisk_wr.log", 'a')) != FALSE) {
977     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
978     fclose($fp);
979   }
980 }
981
982 function log_load($sess, $log) {
983   if (BRISK_DEBUG != TRUE)
984     return;
985
986   if (($fp = @fopen("/tmp/brisk_load.log", 'a')) != FALSE) {
987     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
988     fclose($fp);
989   }
990 }
991
992 function log_legal($timecur, $sess, $name, $where, $mesg) 
993 {
994   GLOBAL $_SERVER;
995
996   if (($fp = @fopen(LEGAL_PATH, 'a')) != FALSE) {
997     /* Unix time | session | nickname | IP | where was | mesg */
998     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $timecur, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
999     fclose($fp);
1000   }
1001 }
1002
1003
1004
1005 function init_data()
1006 {
1007   $brisco =& new brisco();
1008
1009   return $brisco;
1010 }
1011
1012 function lock_data()
1013 {
1014         //  echo "LOCK: ".FTOK_PATH."/main";
1015         //  exit;
1016   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1017     echo "FTOK FAILED";
1018     exit;
1019   }
1020   // echo "FTOK ".$tok."<br>";
1021   if (($res = sem_get($tok)) == FALSE) {
1022     echo "SEM_GET FAILED";
1023     exit;
1024   }
1025   if (sem_acquire($res)) {
1026     log_lock($sess, "LOCK");
1027     return ($res);
1028   }
1029   else
1030     return (false);
1031 }
1032
1033 function unlock_data($res)
1034 {
1035   log_lock($sess, "UNLOCK");
1036   return (sem_release($res));
1037 }
1038
1039
1040 function lock_banlist()
1041 {
1042   if (($tok = ftok(FTOK_PATH."/main", "L")) == -1) {
1043     echo "FTOK FAILED";
1044     exit;
1045   }
1046   if (($res = sem_get($tok)) == FALSE) {
1047     echo "SEM_GET FAILED";
1048     exit;
1049   }
1050   if (sem_acquire($res)) 
1051     return ($res);
1052   else
1053     return (false);
1054 }
1055
1056 function unlock_banlist($res)
1057 {
1058   return (sem_release($res));
1059 }
1060
1061
1062 function &load_data() 
1063 {
1064   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1065     echo "FTOK FAILED";
1066     exit;
1067   }
1068
1069   if ($shm = shm_attach($tok,200000 * TABLES_N)) {
1070     if(($bri = @shm_get_var($shm, $tok)) == false) {
1071       log_main("XXX", "INIT MAIN DATA");
1072
1073       $bri = init_data();
1074       shm_put_var($shm, $tok, $bri);
1075     }
1076     
1077     shm_detach($shm);
1078
1079     $ret = &$bri;
1080     return ($ret);
1081   }
1082
1083   return (NULL);
1084 }
1085
1086
1087 function save_data(&$bri) 
1088 {
1089   $ret =   FALSE;
1090   $shm =   FALSE;
1091   $isacq = FALSE;
1092
1093   // var_dump($bri);
1094
1095   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
1096     return (FALSE);
1097
1098   do {
1099     $isacq = TRUE;
1100     
1101     if (($shm = shm_attach($tok,200000 * TABLES_N)) == FALSE)
1102       break;
1103     
1104     if (shm_put_var($shm, $tok, $bri) == FALSE) {
1105       echo "DANNO: ".strlen(serialize($bri));
1106       break;
1107     }
1108     // log_main("XXX", "QUI CI ARRIVA [".$bri->user[0]->name."]");
1109     $ret = TRUE;
1110   } while (0);
1111   
1112   if ($shm)
1113     shm_detach($shm);
1114      
1115   return ($ret);
1116 }
1117
1118 function table_act_content($isstanding, $sitted, $table, $cur_table)
1119 {
1120   $ret = "";
1121
1122   if ($isstanding) {
1123     if ($sitted < PLAYERS_N) {
1124       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
1125     }
1126   }
1127   else {
1128     if ($table == $cur_table)
1129       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
1130     else
1131       $ret = "";
1132   }
1133   return ($ret);
1134 }
1135
1136 function table_content($bri, $user, $table_idx)
1137 {
1138   $content = "";
1139
1140   // TODO
1141   //
1142   //   Si possono usare i dati nella classe table
1143   //
1144
1145   $sess = $user->sess;
1146   $table = &$bri->table[$table_idx];
1147
1148   if ($user->stat != 'room')
1149     return;
1150
1151   for ($i = 0 ; $i < $table->player_n ; $i++) {
1152     $user_cur = &$bri->user[$table->player[$i]];
1153
1154     if ($user_cur == $user) 
1155         { $hilion = "<b>"; $hilioff = "</b>"; }
1156       else
1157         { $hilion = ""; $hilioff = ""; }
1158
1159     log_main($bri->user[$e]->name, sprintf("IN TABLE [%d]", $table_idx));
1160     
1161     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1162   }
1163   /*
1164   for ( ; $i < PLAYERS_N ; $i++)
1165     $content .= "<br>";
1166   */
1167
1168   $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1169   
1170   return ($ret);
1171 }
1172
1173 function standup_content(&$bri, $user)
1174 {
1175   $ret = "";
1176   $content = "";
1177
1178   if ($user->stat != 'room')
1179     return;
1180
1181   for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1182     if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
1183       continue;
1184     $ct++;
1185   }
1186
1187   $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1188
1189   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1190     if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
1191       continue;
1192
1193
1194     if ($bri->user[$e]->subst == "standup") {
1195       if (($ct % 4) == 0) {
1196         $content .= '<tr>';
1197       }
1198       if ($bri->user[$e] == $user) 
1199         { $hilion = "<b>"; $hilioff = "</b>"; }
1200       else
1201         { $hilion = ""; $hilioff = ""; }
1202
1203       $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($bri->user[$e]->name), $hilioff);
1204       if (($ct % 4) == 3) {
1205         $content .= '</tr>';
1206       }
1207       $ct++;
1208     }
1209   }
1210   $content .= '</table>';
1211         
1212   $content2 = '<input class=\\"button\\" name=\\"logout\\" value=\\"Esco.\\" onclick=\\"window.onunload = null; act_logout();\\" type=\\"button\\">';
1213   $ret .= sprintf('$("standup").innerHTML = "%s";  $("esco").innerHTML = "%s";', 
1214                   $content, $content2);
1215
1216   return ($ret);
1217 }
1218
1219
1220 function show_notify($text, $tout, $butt, $w, $h)
1221 {
1222   log_main("SHOW_NOTIFY", $text);
1223   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
1224 }
1225
1226 function briscola_show($bri, $table, $user)
1227 {
1228   $ptnadd = "";
1229   $ret = "";
1230
1231   if ($table->asta_card == 9) 
1232     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
1233   
1234   /* text of caller cell */
1235   if ($user->table_pos == $table->asta_win) 
1236     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
1237   else 
1238     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
1239                     xcape($bri->user[$table->player[$table->asta_win]]->name), $ptnadd);
1240
1241   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1242                   $table->asta_win);
1243   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1244   $ret .= sprintf('$("caller").style.visibility = "visible";');
1245   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1246   $ret .= sprintf('$("astalascio").style.visibility = "";');
1247   $ret .= sprintf('$("asta").style.visibility = "hidden";');
1248   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1249   
1250   return ($ret);
1251 }
1252
1253
1254 function game_result($asta_pnt, $pnt)
1255 {
1256   if ($asta_pnt == 61) {
1257     if ($pnt > 60)
1258       return (1);
1259     else if ($pnt == 60)
1260       return (0);
1261     else
1262       return (-1);
1263   }
1264   else {
1265     if ($pnt >= $asta_pnt)
1266       return (1);
1267     else
1268       return (-1);
1269   }
1270 }
1271
1272 function multoval($mult)
1273 {
1274   if ($mult == 2)
1275     return ("doppio");
1276   else if ($mult == 4)
1277     return ("quadruplo");
1278   else
1279     return (sprintf("%d-plo", $mult));
1280 }
1281
1282 function show_table_info(&$bri, &$table, $table_pos)
1283 {
1284   $user = &$bri->user[$table->player[$table_pos]];
1285
1286   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1287   $noty = sprintf('<table class=\"points\"><tr><th></th>');
1288   
1289   // Names.
1290   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1291     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($bri->user[$table->player[$i]]->name));
1292   $noty .= sprintf("</tr>");
1293
1294   // Points.
1295   log_main("show_table_info", "pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1296
1297   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1298     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1299     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1300       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1301     $noty .= "</tr>";
1302   }
1303
1304   // Total points.
1305   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1306   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1307     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1308   $noty .= "</tr></table>";
1309
1310   if ($table->old_reason != "") {
1311     $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1312   }
1313
1314   if ($table->old_win != -1) {
1315     $win = $table->player[$table->old_win];
1316     $fri = $table->player[$table->old_friend];
1317
1318     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1319
1320     if ($win != $fri) {
1321       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
1322                        xcape($bri->user[$win]->name),
1323                        xcape($bri->user[$fri]->name));
1324       if ($table->old_pnt == 120) {
1325         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
1326       }
1327       else {
1328         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
1329                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1330                           'pi&ugrave; di 60'), $table->old_pnt,
1331                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1332       }
1333     }
1334     else {
1335       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
1336                        xcape($bri->user[$win]->name));
1337       if ($table->old_pnt == 120) {
1338         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
1339       }
1340       else {
1341         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
1342                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1343                           'pi&ugrave; di 60'), $table->old_pnt,
1344                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1345       }
1346     }
1347   }
1348   if ($table->mazzo == $table_pos) 
1349     $noty .= "Fai <b>tu</b> il mazzo,";
1350   else {
1351     $unam = xcape($bri->user[$table->player[$table->mazzo]]->name);
1352     $noty .= "Il mazzo a <b>$unam</b>,";
1353   }
1354
1355   if ($user->subst == 'asta') {
1356     if ($table->asta_win == -1)  // auction case
1357       $curplayer = $table->gstart % PLAYERS_N;
1358     else 
1359       $curplayer = $table->asta_win;
1360   }
1361   else if ($user->subst == 'game') {
1362     $curplayer = ($table->gstart + $table->turn) % PLAYERS_N;
1363   }
1364
1365
1366   if ($curplayer == $table_pos) {
1367     $noty .= " tocca a <b>te</b> giocare.";
1368   }
1369   else {
1370     $unam = xcape($bri->user[$table->player[$curplayer]]->name);
1371     $noty .= " tocca a <b>$unam</b> giocare.";
1372   }
1373
1374   if ($table->mult > 1) {
1375     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
1376   }
1377   $noty .= "<hr><br>";
1378
1379   $ret .= show_notify($noty, 3000, "torna alla partita", 500, 400);
1380   
1381   return ($ret);
1382 }
1383
1384 function root_wellcome($user)
1385 {
1386   GLOBAL $root_wellarr;
1387
1388   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
1389     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $root_wellarr[$i]));
1390
1391   return ($ret);
1392 }
1393
1394 function table_wellcome($user)
1395 {
1396   GLOBAL $table_wellarr;
1397
1398   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
1399     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $table_wellarr[$i]));
1400
1401   return ($ret);
1402 }
1403
1404 function show_room(&$bri, &$user)
1405 {
1406   $ret .= sprintf('gst.st = %d;',  $user->step);
1407   $ret .= sprintf('stat = "%s";',  $user->stat);
1408
1409   $ret .= root_wellcome($user);
1410   $ret .= sprintf('subst = "%s";', $user->subst);
1411   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1412   for ($i = 0 ; $i < TABLES_N ; $i++) {
1413     $ret .= table_content($bri, $user, $i);
1414     $act_content = table_act_content(($user->subst == 'standup'), 
1415                                      $bri->table[$i]->player_n, $i, $user->table);
1416     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
1417   }
1418   $ret .= standup_content($bri, $user);
1419   
1420   return ($ret);
1421 }
1422
1423
1424
1425 /* show table 
1426 is_transition (is from room to table ?)
1427 is_again      (is another game)
1428
1429 Examples                    of $is_transition, $is_again:
1430   from reload of the page:              FALSE, FALSE
1431   from sitdown in room:                  TRUE, FALSE
1432   from table: asta cmd e tutti passano:  TRUE, TRUE
1433   from table: fine partita:              TRUE, TRUE
1434  */
1435 function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
1436 {
1437   $table_idx = $user->table;
1438   $table = &$bri->table[$table_idx];
1439   $table_pos = $user->table_pos;
1440
1441   $ret = "table_init();";
1442   $ret .= $table->exitlock_show(&$bri->user, $table_pos);
1443   if (!$is_again) {
1444     /* GENERAL STATUS */
1445     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1446                      $sendstep, $user->stat, $user->subst, $table_pos);
1447     /* BACKGROUND */
1448     $ret .= "background_set();";
1449     
1450     /* USERS INFO */
1451     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1452     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1453                     xcape($bri->user[$table->player[($table_pos)%PLAYERS_N]]->name),
1454                     xcape($bri->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
1455                     xcape($bri->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
1456                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
1457                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
1458   }
1459   /* NOTIFY FOR THE CARD MAKER */
1460   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1461     $ret .= show_table_info(&$bri, &$table, $table_pos);
1462   }
1463   if (!$is_again) 
1464     $ret .= table_wellcome($user);
1465
1466   if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1467     $ret .= playsound("cow.mp3");
1468   }
1469
1470
1471   /* CARDS */
1472   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1473     $ret .= "|";
1474     
1475     for ($i = 0 ; $i < 8 ; $i++) {
1476       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
1477         $ct = 0;
1478         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1479           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
1480             $ct++;
1481             if ($ct == $i+1)
1482               break;
1483           }
1484         }
1485         log_rd($sess, "O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1486         
1487         $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
1488                          $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
1489                               $table->card[$o]->value : -1), 
1490                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1491       }
1492     }    
1493   }
1494   else {
1495     $taked  = array(0,0,0,0,0);
1496     $inhand = array(0,0,0,0,0);
1497     $ontabl  = array(-1,-1,-1,-1,-1);
1498     $cards  = array();
1499
1500     for ($i = 0 ; $i < 40 ; $i++) {
1501       if ($table->card[$i]->stat == 'hand') {
1502         if ($table->card[$i]->owner == $table_pos) {
1503           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1504         }
1505         $inhand[$table->card[$i]->owner]++;
1506       }
1507       else if ($table->card[$i]->stat == 'take') {
1508         log_main("Card taked:", $table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1509         $taked[$table->card[$i]->owner]++;
1510       }
1511       else if ($table->card[$i]->stat == 'table') {
1512         $ontabl[$table->card[$i]->owner] = $i;
1513       }
1514     }
1515     $logg = "\n";
1516     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1517       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1518     }
1519     log_main("Stat table:", $logg);
1520
1521     /* Set ours cards. */
1522     $oursarg = "";
1523     for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
1524       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1525     for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
1526       $oursarg .= ($i == 0 ? "" : ", ")."-1";
1527     $ret .= sprintf('card_setours(%s);', $oursarg);
1528
1529     /* Dispose all cards */
1530     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1531       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1532       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1533                       $inhand[$i], $taked[$i]);
1534
1535       if ($ontabl[$i] != -1) {
1536         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1537                         $table->card[$ontabl[$i]]->value, 
1538                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1539       }
1540     }
1541   }
1542
1543   /* Show auction */
1544   if ($user->subst == 'asta') {
1545
1546     /* show users auction status */
1547     $showst = "";
1548     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1549       $user_cur = &$bri->user[$table->player[$i]];
1550       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1551                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1552     }
1553     if (PLAYERS_N == 3)
1554         $showst .= ",-2,-2";
1555     $ret .= sprintf('show_astat(%s);', $showst);
1556
1557     if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
1558       /* show card chooser */
1559       $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
1560                       $table->asta_card);
1561     }
1562     else {
1563       /* show auction */
1564       if ($table_pos == ($table->gstart % PLAYERS_N) &&
1565           $table->asta_win == -1) 
1566         $ret .= sprintf('dispose_asta(%d,%d, %s);', 
1567                         $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
1568       else
1569         $ret .= sprintf('dispose_asta(%d,%d, %s);',
1570                         $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
1571     }
1572
1573     /* Remark */
1574     if ($table->asta_win == -1) { // auction case
1575       if ($table_pos == ($table->gstart % PLAYERS_N)) 
1576         $ret .= "remark_on();";
1577       else
1578         $ret .= "remark_off();";
1579     }
1580     else { // chooseed case
1581       if ($table_pos == $table->asta_win) 
1582         $ret .= "remark_on();";
1583       else
1584         $ret .= "remark_off();";
1585     }
1586   }
1587   else if ($user->subst == 'game') {
1588     /* HIGHLIGHT */
1589     if (($table->gstart + $table->turn) % PLAYERS_N == $table_pos) 
1590       $ret .= "is_my_time = true; remark_on();";
1591     else
1592       $ret .= "remark_off();";
1593     
1594     /* WHO CALL AND WATH */
1595     $ret .= briscola_show($bri, $table, $user);
1596     
1597   }
1598   return ($ret);
1599   }
1600
1601 function calculate_winner(&$table)
1602 {
1603   $briontab = FALSE;
1604   $ontab = array();
1605   $ontid = array();
1606   $cur_win  =  -1;
1607   $cur_val  = 100;
1608   $cur_seed = $table->briscola - ($table->briscola % 10);
1609
1610   for ($i = 0 ; $i < 40 ; $i++) {
1611     if ($table->card[$i]->stat != "table")
1612       continue;
1613
1614     log_wr($sess, sprintf("Card On table: [%d]", $i));
1615
1616     $v = $table->card[$i]->value; 
1617     $ontab[$table->card[$i]->owner] = $v;
1618     $ontid[$table->card[$i]->owner] = $i;
1619     /* se briscola setto il flag */
1620     if (($v - ($v % 10)) == $cur_seed)
1621       $briontab = TRUE;
1622   }
1623
1624   if ($briontab == FALSE) {
1625     $cur_win  = $table->gstart;
1626     $cur_val  = $ontab[$cur_win];
1627     $cur_seed = $cur_val - ($cur_val % 10);
1628   }
1629
1630   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1631     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1632       if ($ontab[$i] < $cur_val) {
1633         $cur_val = $ontab[$i];
1634         $cur_win = $i;
1635       }
1636     }
1637   }
1638
1639   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1640     $table->card[$ontid[$i]]->owner = $cur_win;
1641     $table->card[$ontid[$i]]->stat =  "take"; // Card stat
1642   }
1643   return ($cur_win);
1644 }
1645
1646 function calculate_points(&$table)
1647 {
1648   GLOBAL $G_all_points; 
1649
1650   $pro = 0;
1651
1652   if ($table->asta_pnt == 60)
1653     $table->asta_pnt = 61;
1654
1655   $table->old_reason = "";
1656   $table->old_win = $table->asta_win;
1657   $table->old_friend = $table->friend;
1658   $table->old_asta_pnt = $table->asta_pnt;
1659
1660   for ($i = 0 ; $i < 40 ; $i++) {
1661     $ctt = $table->card[$i]->value % 10;
1662     $own = $table->card[$i]->owner;
1663     if ($own == $table->asta_win || $own == $table->friend) 
1664       $pro += $G_all_points[$ctt];
1665   }
1666
1667   log_wr("XXX", sprintf("PRO: [%d]", $pro));
1668
1669   
1670   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1671     $table->points[$table->points_n % MAX_POINTS] = array();
1672     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1673       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1674     $table->points_n++;
1675     $table->old_pnt = $pro;
1676     $table->mult *= 2;
1677
1678     return;
1679   }
1680
1681   if ($pro >= $table->asta_pnt) 
1682     $sig = 1;
1683   else
1684     $sig = -1;
1685
1686   $table->points[$table->points_n % MAX_POINTS] = array();
1687   for ($i = 0 ; $i < 5 ; $i++) {
1688     if ($i == $table->asta_win) 
1689       $pt = ($i == $table->friend ? 4 : 2);
1690     else if ($i == $table->friend) 
1691       $pt = 1;
1692     else
1693       $pt = -1;
1694
1695     log_wr("XXX", sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1696
1697     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
1698
1699     log_wr("XXX", sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
1700     
1701     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
1702     $table->total[$i] += $pt;
1703   }
1704   $table->points_n++;
1705   $table->old_pnt = $pro;
1706   $table->mult = 1;
1707 }
1708
1709 function validate_sess($sess) 
1710 {
1711   if (strlen($sess) == SESS_LEN) 
1712     return (TRUE);
1713   else
1714     return (FALSE);
1715 }
1716
1717 function validate_name($name) 
1718 {
1719   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
1720
1721   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
1722     $c = $name_new[$i];
1723     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
1724       return ($name_new);
1725   }
1726
1727   return (FALSE);
1728 }
1729
1730 function playsound($filename)
1731 {
1732   return (sprintf('playsound("flasou", "%s");', $filename));
1733 }
1734
1735 function secstoword($secs)
1736 {
1737   $mins = floor($secs / 60);
1738   $secs = $secs % 60;
1739   if ($mins > 0) 
1740     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
1741   
1742   if ($secs > 0)
1743     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
1744   
1745   return ($ret);
1746 }
1747
1748 ?>