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