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