protette tutte le fclose
[brisk.git] / web / brisk.phh
1 <?php
2 /*
3  *  brisk - brisk.phh
4  *
5  *  Copyright (C) 2006-2007 matteo.nastasi@milug.org
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details. You should have received a
16  * copy of the GNU General Public License along with this program; if
17  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
18  * Suite 330, Boston, MA 02111-1307, USA.
19  *
20  */
21
22 define(FTOK_PATH, "/var/lib/brisk");
23 define(LEGAL_PATH, "/tmp/legal_brisk");
24 define(PROXY_PATH, "/var/lib/brisk_proxy");
25 define(TABLES_N, 8);
26 define(PLAYERS_N, 3);
27 define(MAX_POINTS, 5);
28 define(MAX_PLAYERS, (PLAYERS_N * TABLES_N));
29 define(COMM_N, 12);
30 define(COMM_GEN_N, 50);
31 define(SESS_LEN, 13);
32 define(STREAM_TIMEOUT, 20);
33 define(EXPIRE_TIME_RD, 180);
34 define(EXPIRE_TIME_SMAMMA, 360); 
35 // BAN_TIME da allineare anche in commons.js
36 define(BAN_TIME, 900); 
37 define(GARBAGE_TIMEOUT, 10);
38 define(NICKSERV, "<i>SERVER</i>");
39 define(BRISK_DEBUG, FALSE);
40 // define(DEBUGGING, "local");
41
42 $G_all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
43 $G_brisk_version = "0.7.0";
44
45 $root_wellarr = Array ( 'Benvenuto in brisk (Ver. '.$G_brisk_version.'), <b>NOVITA\'</b>: "donate" e piccole rifiniture.',
46                         'Se vuoi iscriverti alla <a target="_blank" href="http://www.milug.org/cgi-bin/mailman/listinfo/ml-briscola">Mailing List</a>, cliccala!' );
47 $table_wellarr = Array ( 'Benvenuto al tavolo. Se almeno tre giocatori non sbloccano l\'uscita cliccando il lucchetto, chi esce non pu&ograve; risedersi a un qualunque tavolo per '.floor(BAN_TIME/60).' minuti.');
48
49
50 $G_room_help= '
51 <div style=\\"text-align: left; padding: 8px;\\">
52 <b>Descrizione</b><br>
53 Questa &egrave; un\'implementazione della briscola in cinque, cos&igrave; come &egrave; spiegata su
54 <a target=\\"_blank\\" href=\\"http://it.wikipedia.org/wiki/Briscola#Gioco_a_5\\">Wikipedia</a>; in breve &egrave; la variante con l\'asta prima sulla carta e poi sui punti.<br><br>
55 <b>Configurazione del browser.</b><br>
56 Occorre abilitare i cookies.<br>
57 Se usate Internet Explorer dovete anche settare: strumenti->cronologia_esplorazioni->impostazioni ad \\"apertura alla pagina web\\".<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) {
371     $this->name  = $name;
372     $this->sess  = $sess;
373     $this->lacc   = time();
374     $this->laccwr = time();
375     $this->bantime = 0;
376     $this->stat  = $stat;
377     $this->subst  = $subst;
378     $this->step  = 1;
379     $this->trans_step  = -1;
380     $this->comm  = array();
381     $this->asta_card = -2;
382     $this->asta_pnt  = -1;
383     $this->handpt = -1;
384     $this->exitislock = TRUE;
385     
386     $this->table = $table;
387   }
388
389   function stat_set($stat) {
390     $this->stat = "$stat";
391     
392     /*
393     if (validate_sess($this->sess)) {
394       $fp = fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
395       fwrite($fp, sprintf("%s\n",$this->stat));
396       fclose($fp);
397     }
398     */
399   }
400
401   function step_set($step) {
402     $this->step = $step;
403     
404     do {
405       if (validate_sess($this->sess) == FALSE)
406         break;
407       if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
408         break;
409       fwrite($fp, pack("l",$this->step), 4);
410       fclose($fp);
411     } while (0);
412   }
413
414   function step_inc() {
415     $this->step++;
416     
417     if (validate_sess($this->sess)) {
418       $fp = fopen(PROXY_PATH."/".$this->sess.".step", 'w');
419       fwrite($fp, pack("l",$this->step), 4);
420       fclose($fp);
421     }
422   }
423 }
424
425 function step_get($sess) {
426   $fp = FALSE;
427   $ct = 0;
428   do {
429     if (validate_sess($sess) == FALSE)
430       break;
431   $ct = 1;
432     if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
433       break;
434   $ct = 2;
435     if (($s = fread($fp, 4)) == FALSE)
436       break;
437   $ct = 3;
438     if (strlen($s) != 4)
439       break;
440   $ct = 4;
441     $arr = unpack('l', $s);
442     fclose($fp);
443
444     // log_rd2($sess, "A0: ".$arr[0]."  A1: ".$arr[1]);
445     return ($arr[1]);
446   } while (0);
447
448   if ($fp != FALSE)
449     fclose($fp);
450
451   log_rd2($sess, "STEP_GET: return false ".$ct);
452   return (FALSE);
453 }
454
455 function step_unproxy($sess) {
456   log_rd2($sess, "UNPROXY: ".PROXY_PATH."/".$sess.".step");
457   unlink(PROXY_PATH."/".$sess.".step");
458 }
459
460
461 class brisco {
462   var $user;
463   var $table;
464   var $comm; // commands for many people
465   var $step; // current step of the comm array
466   var $garbage_timeout;
467
468   function brisco () {
469     $this->user = array();
470
471     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
472       $this->user[$i] =& new User("", "");
473     }
474     for ($i = 0 ; $i < TABLES_N ; $i++) 
475       $this->table[$i] =& new Table();
476     $this->garbage_timeout = 0;
477   }
478
479   function garbage_manager($force)
480   {
481     
482     /* Garbage collector degli utenti in timeout */
483     $curtime = time();
484     if ($force || $this->garbage_timeout < $curtime) {
485       
486       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
487         $user_cur = &$this->user[$i];
488         if ($user_cur->sess == "")
489           continue;
490         
491         if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) { // Auto logout dell'utente
492           log_rd2($user_cur->sess, "AUTO LOGOUT.");
493
494           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
495             log_auth($user_cur->sess, "Autologout session.");
496             
497             $tmp_sess = $user_cur->sess;
498             $user_cur->sess = "";
499             step_unproxy($tmp_sess);
500             $user_cur->name = "";
501             $user_cur->the_end = FALSE;
502             
503             log_rd2($user_cur->sess, "AUTO LOGOUT.");
504             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
505               $this->room_wakeup(&$user_cur);
506             else if ($user_cur->subst == 'standup')
507               $this->room_outstandup(&$user_cur);
508             else
509               log_rd2($sess, "LOGOUT FROM WHAT ???");
510           }
511         }
512
513         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < $curtime) { // lo rimettiamo in piedi
514           if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
515             $this->room_wakeup(&$user_cur);
516             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
517             $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);
518             $user_cur->step_inc();
519           }
520         }
521       }
522       log_rd2($user_cur->sess, "GARBAGE UPDATED!");
523       
524       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
525     }
526
527     // BAN_IP_CLEAN
528
529   }
530
531
532   function room_wakeup(&$user)
533   {
534     $table_idx = $user->table;
535     $table = &$this->table[$table_idx];
536
537     log_main("WAKEUP", "begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
538
539     $curtime = time();
540
541     $from_table = ($user->stat == "table");
542     if ($from_table) {
543       log_main("WAKEUP", "from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
544
545       for ($i = 0 ; $i < $table->player_n ; $i++) {
546         $user_cur = &$this->user[$table->player[$i]];
547         log_main("PREIMPOST", "INLOOP name: ".$user_cur->name);
548
549         if ($user_cur != $user) {
550           $user_cur->stat_set("room");
551           $user_cur->subst = "sitdown";
552           $user_cur->laccwr = $curtime;
553         }
554         else if ($user->sess != "") {
555           $user_cur->stat_set("room");
556           $user_cur->subst = "standup";
557           $user_cur->laccwr = $curtime;
558           $user_cur->table = -1;
559         }
560       }
561     }
562     else {
563       $user->stat_set("room");
564       $user->subst = "standup";
565       $user->laccwr = $curtime;
566     }
567     /* aggiorna l'array dei giocatori al tavolo. */
568     $table->user_rem(&$this, &$user);
569
570     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
571       $user_cur = &$this->user[$i];
572       if ($user_cur->sess == '' || $user_cur->stat != 'room')
573         continue;
574       
575       log_main("VALORI", "name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
576
577       $ret = "gst.st = ".($user_cur->step+1)."; ";
578       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
579         $ret .= 'gst.st_loc++; the_end=true; window.onunload = null; document.location.assign("index.php");|';
580         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
581         log_main("DOCUMENT.index.php", "from table");
582       }
583       else if ($user_cur->stat == "room") {
584         log_main("DOCUMENT.index.php", "from table");
585
586         $ret .= table_content($this, $user_cur, $table_idx);
587         $ret .= standup_content($this, $user_cur);
588         
589         $act_content = table_act_content(FALSE, 0, $e, $user->table);
590         $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
591         
592         
593         if ($user_cur == $user) {
594           // set the new status 
595           $ret .=  'subst = "standup"; ';
596           // clean the action buttons in other tables
597           for ($e = 0 ; $e < TABLES_N ; $e++) {
598             if ($this->table[$e]->player_n < PLAYERS_N)
599               $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, table_act_content(TRUE, 0, $e, $user->table));
600           }
601         }
602         else {
603           $act_content = table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table);
604           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
605         }
606       }
607       log_wr($user_cur->sess, "ROOM_WAKEUP: ".$ret);
608       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
609       $user_cur->step_inc();
610     }
611   }
612   
613
614
615
616   function room_outstandup(&$user)
617   {
618     $this->room_sitdown(&$user, -1);
619   }
620   
621   function table_update(&$user)
622   {
623     log_main("table_update", "pre - USER: ".$user->name);
624
625     $table_idx = $user->table;
626
627     if ($table_idx > -1) 
628       $table = &$this->table[$table_idx];
629     
630     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
631       $ret = "";
632       $user_cur = &$this->user[$i];
633       if ($user_cur->sess == '' || $user_cur->stat != 'room')
634       continue;
635       
636       $ret = "gst.st = ".($user_cur->step+1)."; ";
637       if ($table_idx > -1)
638         $ret .= table_content($this, $user_cur, $table_idx);
639       
640       if ($user_cur == $user) {
641         $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
642       }
643       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
644       $user_cur->step_inc();
645     }
646
647     log_main("table_update", "post");
648   }
649
650   function room_sitdown(&$user, $table_idx)
651   {
652     log_main("room_sitdown", ($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
653
654     if ($table_idx > -1) 
655       $table = &$this->table[$table_idx];
656     
657     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
658       $ret = "";
659       $user_cur = &$this->user[$i];
660       if ($user_cur->sess == '' || $user_cur->stat != 'room')
661       continue;
662       
663       $ret = "gst.st = ".($user_cur->step+1)."; ";
664       if ($table_idx > -1)
665       $ret .= table_content($this, $user_cur, $table_idx);
666       $ret .= standup_content($this, $user_cur);
667       
668       if ($user_cur == $user) {
669         $ret .=  'subst = "sitdown"; ';
670         // clean the action buttons in other tables
671         for ($e = 0 ; $e < TABLES_N ; $e++) {
672           $act_content = table_act_content(FALSE, 0, $e, $user_cur->table);
673           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, $act_content);
674         }
675       }
676       else if ($table_idx > -1) {
677         if ($table->player_n == PLAYERS_N) {
678           $act_content = table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table);
679           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
680         }
681       }
682       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
683       $user_cur->step_inc();
684     }
685   }
686
687   function chatt_send(&$user, $mesg)
688   {
689     if ($user->stat == 'table') {
690       $table = &$this->table[$user->table];
691     }
692     
693     $user_mesg = substr($mesg,6);
694     
695     $timecur = time();
696     
697     $dt = date("H:i ", $timecur);
698     if (strncmp($user_mesg, "/nick ", 6) == 0) {
699       log_main($user->sess, "chatt_send BEGIN");
700
701       if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
702           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
703           $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));
704           $user->step_inc();
705
706           return;
707       }
708       $user_mesg = "COMMAND ".$user_mesg;
709       // Search dup name
710       // change
711       // update local graph
712       // update remote graphs
713       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
714         $user_cur = &$this->user[$i];
715         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
716         if ($user_cur->sess == '')
717           continue;
718         if ($user_cur->name == $name_new) {
719           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
720           $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Nickname <b>%s</b> gi&agrave; in uso.");', $dt.NICKSERV, xcape($name_new));
721           $user->step_inc();
722           break;
723         }
724       }
725       if ($i == MAX_PLAYERS) {
726         $user->name = $name_new;
727
728       log_main($user->sess, "chatt_send start set");
729         
730
731         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
732           log_main($user->sess, "chatt_send set loop");
733           
734           $user_cur = &$this->user[$i];
735           if ($user_cur->sess == '')
736             continue;
737           if ($user_cur->stat == 'room') {
738             if ($user->stat == 'room' && $user->subst == 'standup') {
739               $this->standup_update(&$user);
740             }
741             else if ($user->stat == 'room' && $user->subst == 'sitdown' ||
742                      $user->stat == 'table') {
743               log_main($user->sess, "chatt_send pre table update");
744
745               $this->table_update(&$user);
746
747               log_main($user->sess, "chatt_send post table update");
748             }
749           }
750           else if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
751             $table = &$this->table[$user->table];
752             
753             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
754             $user_cur->comm[$user_cur->step % COMM_N] = sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
755                 xcape($this->user[$table->player[($user_cur->table_pos)%PLAYERS_N]]->name),
756                 xcape($this->user[$table->player[($user_cur->table_pos+1)%PLAYERS_N]]->name),
757                 xcape($this->user[$table->player[($user_cur->table_pos+2)%PLAYERS_N]]->name),
758                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3)%PLAYERS_N]]->name)),
759                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4)%PLAYERS_N]]->name)));
760             if ($user_cur == $user)
761               $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>";', 
762                                                                    xcape($user->name,ENT_COMPAT,"UTF-8"));
763             $user_cur->step_inc();
764           }
765         }
766       }
767     }
768     else {
769       for ($i = 0 ; $i < ($user->stat == 'room' ? MAX_PLAYERS : PLAYERS_N) ; $i++) {
770         if ($user->stat == 'room') {
771           $user_cur = &$this->user[$i];
772           if ($user_cur->sess == '' || $user_cur->stat != 'room')
773             continue;
774         }
775         else {
776           $user_cur = &$this->user[$table->player[$i]];
777         }
778         
779         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
780         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s","%s");',
781                                                              $dt.xcape($user->name), xcape($user_mesg));
782         $user_cur->step_inc();
783       }
784       log_legal($timecur, $user->sess, $user->name, 
785                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$user_mesg);
786     }
787   }
788
789   function &get_user($sess, &$idx)
790   {
791     GLOBAL $PHP_SELF;
792
793     if (validate_sess($sess)) {
794       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
795         if (strcmp($sess, $this->user[$i]->sess) == 0) {
796           // find it
797           $idx = $i;
798           $ret = &$this->user[$i];
799           return ($ret);
800         }
801       }
802       log_main($sess, sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
803       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
804       // log_main($sess, sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
805     }
806     else {
807       log_main($sess, sprintf("get_user: Wrong strlen [%s]",$sess));
808     }
809     return (FALSE);
810   }
811
812   /*
813    * function &add_user(&$bri, &$sess, &$idx, $name, $ip)
814    *
815    * RETURN VALUE:
816    *   if ($idx != -1 && ret == FALSE)  =>  duplicated nick
817    *   if ($idx == -2 && ret == FALSE)  =>  invalid name
818    *   if ($idx == -1 && ret == FALSE)  =>  no space left
819    *   if (ret == TRUE)                 =>  SUCCESS
820    */
821   function &add_user(&$sess, &$idx, $name, $ip)
822   {
823     $idx = -1;
824     $idfree = -1;
825     
826     if (($name_new = validate_name($name)) == FALSE) {
827       $idx = -2;
828       return (FALSE);
829     }
830
831     log_auth("XXX", sprintf("ARRIVA: [%s]", $sess));
832     if (validate_sess($sess) == FALSE) 
833       $sess = "";
834
835     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
836       /* free user ? */
837       if (strcmp($sess, $this->user[$i]->sess) == 0) {
838         if ($idx == -1)
839           $idx = $i;
840       }
841       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
842         $idfree = $i;
843       }
844       if (strcmp($this->user[$i]->name, $name_new) == 0) {
845         $idx = $i;
846         break;
847       }
848     }
849     if ($idx == -1)
850       $idx = $idfree;
851
852     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
853
854     if ($idx != -1 && $i == MAX_PLAYERS) {
855       /* SUCCESS */
856       $curtime = time();
857       if ($sess == "") {
858         $this->user[$idx]->sess = uniqid("");
859         $sess = $this->user[$idx]->sess;
860         
861       }
862       else {
863         $this->user[$idx]->sess = $sess;
864       }
865       $this->user[$idx]->name = $name_new;
866       $this->user[$idx]->stat_set("room");
867       $this->user[$idx]->subst = "standup";
868       $this->user[$idx]->lacc =   $curtime;
869       $this->user[$idx]->laccwr = $curtime;
870       $this->user[$idx]->bantime = 0;
871       $this->user[$idx]->ip = $ip;
872       log_main("XXX", sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
873       
874       return ($this->user[$idx]);
875     }
876
877     return (FALSE);
878   }
879   
880   function standup_update(&$user)
881   {
882     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
883       $user_cur = &$this->user[$i];
884       if ($user_cur->sess == '')
885         continue;
886
887       log_main("STANDUP START", $user_cur->stat);
888       
889       if ($user_cur->stat == 'room') {
890         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".standup_content($this, $user_cur);
891         if ($user_cur == $user)
892           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
893         
894         log_main("FROM STANDUP", "NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
895         
896         $user_cur->step_inc();
897       }
898     }
899   }
900
901
902 } // end class brisco
903
904 function make_seed()
905 {
906   list($usec, $sec) = explode(' ', microtime());
907   return (float) $sec + ((float) $usec * 100000);
908 }
909
910 function log_main($sess, $log) {
911   if (BRISK_DEBUG != TRUE)
912     return;
913
914   if (($fp = @fopen("/tmp/brisk_main.log", 'a')) != FALSE) {
915     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
916     fclose($fp);
917   }
918 }
919
920 function log_rd($sess, $log) {
921   if (BRISK_DEBUG != TRUE)
922     return;
923
924   if (($fp = @fopen("/tmp/brisk_rd.log", 'a')) != FALSE) {
925     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
926     fclose($fp);
927   }
928 }
929
930 function log_rd2($sess, $log) {
931   if (BRISK_DEBUG != TRUE)
932     return;
933
934   if (($fp = @fopen("/tmp/brisk_rd2.log", 'a')) != FALSE) {
935     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
936     fclose($fp);
937   }
938 }
939
940 function log_send($sess, $log) {
941   if (BRISK_DEBUG != TRUE)
942     return;
943
944   if (($fp = @fopen("/tmp/brisk_send.log", 'a')) != FALSE) {
945     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
946     fclose($fp);
947   }
948 }
949
950 function log_auth($sess, $log) {
951   if (BRISK_DEBUG != TRUE)
952     return;
953
954   if (($fp = @fopen("/tmp/brisk_auth.log", 'a')) != FALSE) {
955     fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
956     fclose($fp);
957   }
958 }
959
960 function log_wr($sess, $log) {
961   if (BRISK_DEBUG != TRUE)
962     return;
963
964   if (($fp = @fopen("/tmp/brisk_wr.log", 'a')) != FALSE) {
965     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
966     fclose($fp);
967   }
968 }
969
970 function log_load($sess, $log) {
971   if (BRISK_DEBUG != TRUE)
972     return;
973
974   if (($fp = @fopen("/tmp/brisk_load.log", 'a')) != FALSE) {
975     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
976     fclose($fp);
977   }
978 }
979
980 function log_legal($timecur, $sess, $name, $where, $mesg) 
981 {
982   GLOBAL $_SERVER;
983
984   if (($fp = @fopen(LEGAL_PATH, 'a')) != FALSE) {
985     /* Unix time | session | nickname | IP | where was | mesg */
986     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $timecur, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
987     fclose($fp);
988   }
989 }
990
991
992
993 function init_data()
994 {
995   $brisco =& new brisco();
996
997   return $brisco;
998 }
999
1000 function lock_data()
1001 {
1002         //  echo "LOCK: ".FTOK_PATH."/main";
1003         //  exit;
1004   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1005     echo "FTOK FAILED";
1006     exit;
1007   }
1008   // echo "FTOK ".$tok."<br>";
1009   if (($res = sem_get($tok)) == FALSE) {
1010     echo "SEM_GET FAILED";
1011     exit;
1012   }
1013   if (sem_acquire($res)) 
1014     return ($res);
1015   else
1016     return (false);
1017 }
1018
1019 function unlock_data($res)
1020 {
1021   return (sem_release($res));
1022 }
1023
1024
1025 function lock_banlist()
1026 {
1027   if (($tok = ftok(FTOK_PATH."/main", "L")) == -1) {
1028     echo "FTOK FAILED";
1029     exit;
1030   }
1031   if (($res = sem_get($tok)) == FALSE) {
1032     echo "SEM_GET FAILED";
1033     exit;
1034   }
1035   if (sem_acquire($res)) 
1036     return ($res);
1037   else
1038     return (false);
1039 }
1040
1041 function unlock_banlist($res)
1042 {
1043   return (sem_release($res));
1044 }
1045
1046
1047 function &load_data() 
1048 {
1049   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1050     echo "FTOK FAILED";
1051     exit;
1052   }
1053
1054   if ($shm = shm_attach($tok,100000 * TABLES_N)) {
1055     if(($bri = @shm_get_var($shm, $tok)) == false) {
1056       log_main("XXX", "INIT MAIN DATA");
1057
1058       $bri = init_data();
1059       shm_put_var($shm, $tok, $bri);
1060     }
1061     
1062     shm_detach($shm);
1063
1064     $ret = &$bri;
1065     return ($ret);
1066   }
1067
1068   return (NULL);
1069 }
1070
1071
1072 function save_data(&$bri) 
1073 {
1074   $ret =   FALSE;
1075   $shm =   FALSE;
1076   $isacq = FALSE;
1077
1078   // var_dump($bri);
1079
1080   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
1081     return (FALSE);
1082
1083   do {
1084     $isacq = TRUE;
1085     
1086     if (($shm = shm_attach($tok,100000 * TABLES_N)) == FALSE)
1087       break;
1088     
1089     if (shm_put_var($shm, $tok, $bri) == FALSE)
1090       break;
1091     // log_main("XXX", "QUI CI ARRIVA [".$bri->user[0]->name."]");
1092     $ret = TRUE;
1093   } while (0);
1094   
1095   if ($shm)
1096     shm_detach($shm);
1097      
1098   return ($ret);
1099 }
1100
1101 function table_act_content($isstanding, $sitted, $table, $cur_table)
1102 {
1103   $ret = "";
1104
1105   if ($isstanding) {
1106     if ($sitted < PLAYERS_N) {
1107       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
1108     }
1109   }
1110   else {
1111     if ($table == $cur_table)
1112       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
1113     else
1114       $ret = "";
1115   }
1116   return ($ret);
1117 }
1118
1119 function table_content($bri, $user, $table_idx)
1120 {
1121   $content = "";
1122
1123   // TODO
1124   //
1125   //   Si possono usare i dati nella classe table
1126   //
1127
1128   $sess = $user->sess;
1129   $table = &$bri->table[$table_idx];
1130
1131   if ($user->stat != 'room')
1132     return;
1133
1134   for ($i = 0 ; $i < $table->player_n ; $i++) {
1135     $user_cur = &$bri->user[$table->player[$i]];
1136
1137     if ($user_cur == $user) 
1138         { $hilion = "<b>"; $hilioff = "</b>"; }
1139       else
1140         { $hilion = ""; $hilioff = ""; }
1141
1142     log_main($bri->user[$e]->name, sprintf("IN TABLE [%d]", $table_idx));
1143     
1144     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1145   }
1146   /*
1147   for ( ; $i < PLAYERS_N ; $i++)
1148     $content .= "<br>";
1149   */
1150
1151   $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1152   
1153   return ($ret);
1154 }
1155
1156 function standup_content(&$bri, $user)
1157 {
1158   $ret = "";
1159   $content = "";
1160
1161   if ($user->stat != 'room')
1162     return;
1163
1164   for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1165     if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
1166       continue;
1167     $ct++;
1168   }
1169
1170   $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1171
1172   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1173     if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
1174       continue;
1175
1176
1177     if ($bri->user[$e]->subst == "standup") {
1178       if (($ct % 4) == 0) {
1179         $content .= '<tr>';
1180       }
1181       if ($bri->user[$e] == $user) 
1182         { $hilion = "<b>"; $hilioff = "</b>"; }
1183       else
1184         { $hilion = ""; $hilioff = ""; }
1185
1186       $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($bri->user[$e]->name), $hilioff);
1187       if (($ct % 4) == 3) {
1188         $content .= '</tr>';
1189       }
1190       $ct++;
1191     }
1192   }
1193   $content .= '</table>';
1194         
1195   $content2 = '<input class=\\"button\\" name=\\"logout\\" value=\\"Esco.\\" onclick=\\"window.onunload = null; act_logout();\\" type=\\"button\\">';
1196   $ret .= sprintf('$("standup").innerHTML = "%s";  $("esco").innerHTML = "%s";', 
1197                   $content, $content2);
1198
1199   return ($ret);
1200 }
1201
1202
1203 function show_notify($text, $tout, $butt, $w, $h)
1204 {
1205   log_main("SHOW_NOTIFY", $text);
1206   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
1207 }
1208
1209 function briscola_show($bri, $table, $user)
1210 {
1211   $ptnadd = "";
1212   $ret = "";
1213
1214   if ($table->asta_card == 9) 
1215     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
1216   
1217   /* text of caller cell */
1218   if ($user->table_pos == $table->asta_win) 
1219     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
1220   else 
1221     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
1222                     xcape($bri->user[$table->player[$table->asta_win]]->name), $ptnadd);
1223
1224   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1225                   $table->asta_win);
1226   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1227   $ret .= sprintf('$("caller").style.visibility = "visible";');
1228   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1229   $ret .= sprintf('$("astalascio").style.visibility = "";');
1230   $ret .= sprintf('$("asta").style.visibility = "hidden";');
1231   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1232   
1233   return ($ret);
1234 }
1235
1236
1237 function game_result($asta_pnt, $pnt)
1238 {
1239   if ($asta_pnt == 61) {
1240     if ($pnt > 60)
1241       return (1);
1242     else if ($pnt == 60)
1243       return (0);
1244     else
1245       return (-1);
1246   }
1247   else {
1248     if ($pnt >= $asta_pnt)
1249       return (1);
1250     else
1251       return (-1);
1252   }
1253 }
1254
1255 function multoval($mult)
1256 {
1257   if ($mult == 2)
1258     return ("doppio");
1259   else if ($mult == 4)
1260     return ("quadruplo");
1261   else
1262     return (sprintf("%d-plo", $mult));
1263 }
1264
1265 function show_table_info(&$bri, &$table, $table_pos)
1266 {
1267   $user = &$bri->user[$table->player[$table_pos]];
1268
1269   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1270   $noty = sprintf('<table class=\"points\"><tr><th></th>');
1271   
1272   // Names.
1273   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1274     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($bri->user[$table->player[$i]]->name));
1275   $noty .= sprintf("</tr>");
1276
1277   // Points.
1278   log_main("show_table_info", "pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1279
1280   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1281     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1282     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1283       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1284     $noty .= "</tr>";
1285   }
1286
1287   // Total points.
1288   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1289   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1290     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1291   $noty .= "</tr></table>";
1292
1293   if ($table->old_reason != "") {
1294     $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1295   }
1296
1297   if ($table->old_win != -1) {
1298     $win = $table->player[$table->old_win];
1299     $fri = $table->player[$table->old_friend];
1300
1301     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1302
1303     if ($win != $fri) {
1304       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
1305                        xcape($bri->user[$win]->name),
1306                        xcape($bri->user[$fri]->name));
1307       if ($table->old_pnt == 120) {
1308         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
1309       }
1310       else {
1311         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
1312                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1313                           'pi&ugrave; di 60'), $table->old_pnt,
1314                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1315       }
1316     }
1317     else {
1318       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
1319                        xcape($bri->user[$win]->name));
1320       if ($table->old_pnt == 120) {
1321         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
1322       }
1323       else {
1324         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
1325                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1326                           'pi&ugrave; di 60'), $table->old_pnt,
1327                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1328       }
1329     }
1330   }
1331   if ($table->mazzo == $table_pos) 
1332     $noty .= "Fai <b>tu</b> il mazzo,";
1333   else {
1334     $unam = xcape($bri->user[$table->player[$table->mazzo]]->name);
1335     $noty .= "Il mazzo a <b>$unam</b>,";
1336   }
1337
1338   if ($user->subst == 'asta') {
1339     if ($table->asta_win == -1)  // auction case
1340       $curplayer = $table->gstart % PLAYERS_N;
1341     else 
1342       $curplayer = $table->asta_win;
1343   }
1344   else if ($user->subst == 'game') {
1345     $curplayer = ($table->gstart + $table->turn) % PLAYERS_N;
1346   }
1347
1348
1349   if ($curplayer == $table_pos) {
1350     $noty .= " tocca a <b>te</b> giocare.";
1351   }
1352   else {
1353     $unam = xcape($bri->user[$table->player[$curplayer]]->name);
1354     $noty .= " tocca a <b>$unam</b> giocare.";
1355   }
1356
1357   if ($table->mult > 1) {
1358     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
1359   }
1360   $noty .= "<hr><br>";
1361
1362   $ret .= show_notify($noty, 3000, "torna alla partita", 500, 400);
1363   
1364   return ($ret);
1365 }
1366
1367 function root_wellcome($user)
1368 {
1369   GLOBAL $root_wellarr;
1370
1371   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
1372     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $root_wellarr[$i]));
1373
1374   return ($ret);
1375 }
1376
1377 function table_wellcome($user)
1378 {
1379   GLOBAL $table_wellarr;
1380
1381   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
1382     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $table_wellarr[$i]));
1383
1384   return ($ret);
1385 }
1386
1387 function show_room(&$bri, &$user)
1388 {
1389   $ret .= sprintf('gst.st = %d;',  $user->step);
1390   $ret .= sprintf('stat = "%s";',  $user->stat);
1391
1392   $ret .= root_wellcome($user);
1393   $ret .= sprintf('subst = "%s";', $user->subst);
1394   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1395   for ($i = 0 ; $i < TABLES_N ; $i++) {
1396     $ret .= table_content($bri, $user, $i);
1397     $act_content = table_act_content(($user->subst == 'standup'), 
1398                                      $bri->table[$i]->player_n, $i, $user->table);
1399     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
1400   }
1401   $ret .= standup_content($bri, $user);
1402   
1403   return ($ret);
1404 }
1405
1406
1407
1408 /* show table 
1409 is_transition (is from room to table ?)
1410 is_again      (is another game)
1411
1412 Examples                    of $is_transition, $is_again:
1413   from reload of the page:              FALSE, FALSE
1414   from sitdown in room:                  TRUE, FALSE
1415   from table: asta cmd e tutti passano:  TRUE, TRUE
1416   from table: fine partita:              TRUE, TRUE
1417  */
1418 function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
1419 {
1420   $table_idx = $user->table;
1421   $table = &$bri->table[$table_idx];
1422   $table_pos = $user->table_pos;
1423
1424   $ret = "table_init();";
1425   $ret .= $table->exitlock_show(&$bri->user, $table_pos);
1426   if (!$is_again) {
1427     /* GENERAL STATUS */
1428     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1429                      $sendstep, $user->stat, $user->subst, $table_pos);
1430     /* BACKGROUND */
1431     $ret .= "background_set();";
1432     
1433     /* USERS INFO */
1434     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1435     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1436                     xcape($bri->user[$table->player[($table_pos)%PLAYERS_N]]->name),
1437                     xcape($bri->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
1438                     xcape($bri->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
1439                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
1440                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
1441   }
1442   /* NOTIFY FOR THE CARD MAKER */
1443   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1444     $ret .= show_table_info(&$bri, &$table, $table_pos);
1445   }
1446   if (!$is_again) 
1447     $ret .= table_wellcome($user);
1448
1449   if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1450     $ret .= playsound("cow.mp3");
1451   }
1452
1453
1454   /* CARDS */
1455   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1456     $ret .= "|";
1457     
1458     for ($i = 0 ; $i < 8 ; $i++) {
1459       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
1460         $ct = 0;
1461         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1462           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
1463             $ct++;
1464             if ($ct == $i+1)
1465               break;
1466           }
1467         }
1468         log_rd($sess, "O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1469         
1470         $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
1471                          $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
1472                               $table->card[$o]->value : -1), 
1473                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1474       }
1475     }    
1476   }
1477   else {
1478     $taked  = array(0,0,0,0,0);
1479     $inhand = array(0,0,0,0,0);
1480     $ontabl  = array(-1,-1,-1,-1,-1);
1481     $cards  = array();
1482
1483     for ($i = 0 ; $i < 40 ; $i++) {
1484       if ($table->card[$i]->stat == 'hand') {
1485         if ($table->card[$i]->owner == $table_pos) {
1486           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1487         }
1488         $inhand[$table->card[$i]->owner]++;
1489       }
1490       else if ($table->card[$i]->stat == 'take') {
1491         log_main("Card taked:", $table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1492         $taked[$table->card[$i]->owner]++;
1493       }
1494       else if ($table->card[$i]->stat == 'table') {
1495         $ontabl[$table->card[$i]->owner] = $i;
1496       }
1497     }
1498     $logg = "\n";
1499     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1500       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1501     }
1502     log_main("Stat table:", $logg);
1503
1504     /* Set ours cards. */
1505     $oursarg = "";
1506     for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
1507       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1508     for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
1509       $oursarg .= ($i == 0 ? "" : ", ")."-1";
1510     $ret .= sprintf('card_setours(%s);', $oursarg);
1511
1512     /* Dispose all cards */
1513     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1514       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1515       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1516                       $inhand[$i], $taked[$i]);
1517
1518       if ($ontabl[$i] != -1) {
1519         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1520                         $table->card[$ontabl[$i]]->value, 
1521                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1522       }
1523     }
1524   }
1525
1526   /* Show auction */
1527   if ($user->subst == 'asta') {
1528
1529     /* show users auction status */
1530     $showst = "";
1531     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1532       $user_cur = &$bri->user[$table->player[$i]];
1533       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1534                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1535     }
1536     if (PLAYERS_N == 3)
1537         $showst .= ",-2,-2";
1538     $ret .= sprintf('show_astat(%s);', $showst);
1539
1540     if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
1541       /* show card chooser */
1542       $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
1543                       $table->asta_card);
1544     }
1545     else {
1546       /* show auction */
1547       if ($table_pos == ($table->gstart % PLAYERS_N) &&
1548           $table->asta_win == -1) 
1549         $ret .= sprintf('dispose_asta(%d,%d, %s);', 
1550                         $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
1551       else
1552         $ret .= sprintf('dispose_asta(%d,%d, %s);',
1553                         $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
1554     }
1555
1556     /* Remark */
1557     if ($table->asta_win == -1) { // auction case
1558       if ($table_pos == ($table->gstart % PLAYERS_N)) 
1559         $ret .= "remark_on();";
1560       else
1561         $ret .= "remark_off();";
1562     }
1563     else { // chooseed case
1564       if ($table_pos == $table->asta_win) 
1565         $ret .= "remark_on();";
1566       else
1567         $ret .= "remark_off();";
1568     }
1569   }
1570   else if ($user->subst == 'game') {
1571     /* HIGHLIGHT */
1572     if (($table->gstart + $table->turn) % PLAYERS_N == $table_pos) 
1573       $ret .= "is_my_time = true; remark_on();";
1574     else
1575       $ret .= "remark_off();";
1576     
1577     /* WHO CALL AND WATH */
1578     $ret .= briscola_show($bri, $table, $user);
1579     
1580   }
1581   return ($ret);
1582   }
1583
1584 function calculate_winner(&$table)
1585 {
1586   $briontab = FALSE;
1587   $ontab = array();
1588   $ontid = array();
1589   $cur_win  =  -1;
1590   $cur_val  = 100;
1591   $cur_seed = $table->briscola - ($table->briscola % 10);
1592
1593   for ($i = 0 ; $i < 40 ; $i++) {
1594     if ($table->card[$i]->stat != "table")
1595       continue;
1596
1597     log_wr($sess, sprintf("Card On table: [%d]", $i));
1598
1599     $v = $table->card[$i]->value; 
1600     $ontab[$table->card[$i]->owner] = $v;
1601     $ontid[$table->card[$i]->owner] = $i;
1602     /* se briscola setto il flag */
1603     if (($v - ($v % 10)) == $cur_seed)
1604       $briontab = TRUE;
1605   }
1606
1607   if ($briontab == FALSE) {
1608     $cur_win  = $table->gstart;
1609     $cur_val  = $ontab[$cur_win];
1610     $cur_seed = $cur_val - ($cur_val % 10);
1611   }
1612
1613   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1614     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1615       if ($ontab[$i] < $cur_val) {
1616         $cur_val = $ontab[$i];
1617         $cur_win = $i;
1618       }
1619     }
1620   }
1621
1622   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1623     $table->card[$ontid[$i]]->owner = $cur_win;
1624     $table->card[$ontid[$i]]->stat =  "take"; // Card stat
1625   }
1626   return ($cur_win);
1627 }
1628
1629 function calculate_points(&$table)
1630 {
1631   GLOBAL $G_all_points; 
1632
1633   $pro = 0;
1634
1635   if ($table->asta_pnt == 60)
1636     $table->asta_pnt = 61;
1637
1638   $table->old_reason = "";
1639   $table->old_win = $table->asta_win;
1640   $table->old_friend = $table->friend;
1641   $table->old_asta_pnt = $table->asta_pnt;
1642
1643   for ($i = 0 ; $i < 40 ; $i++) {
1644     $ctt = $table->card[$i]->value % 10;
1645     $own = $table->card[$i]->owner;
1646     if ($own == $table->asta_win || $own == $table->friend) 
1647       $pro += $G_all_points[$ctt];
1648   }
1649
1650   log_wr("XXX", sprintf("PRO: [%d]", $pro));
1651
1652   
1653   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1654     $table->points[$table->points_n % MAX_POINTS] = array();
1655     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1656       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1657     $table->points_n++;
1658     $table->old_pnt = $pro;
1659     $table->mult *= 2;
1660
1661     return;
1662   }
1663
1664   if ($pro >= $table->asta_pnt) 
1665     $sig = 1;
1666   else
1667     $sig = -1;
1668
1669   $table->points[$table->points_n % MAX_POINTS] = array();
1670   for ($i = 0 ; $i < 5 ; $i++) {
1671     if ($i == $table->asta_win) 
1672       $pt = ($i == $table->friend ? 4 : 2);
1673     else if ($i == $table->friend) 
1674       $pt = 1;
1675     else
1676       $pt = -1;
1677
1678     log_wr("XXX", sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1679
1680     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
1681
1682     log_wr("XXX", sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
1683     
1684     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
1685     $table->total[$i] += $pt;
1686   }
1687   $table->points_n++;
1688   $table->old_pnt = $pro;
1689   $table->mult = 1;
1690 }
1691
1692 function validate_sess($sess) 
1693 {
1694   if (strlen($sess) == SESS_LEN) 
1695     return (TRUE);
1696   else
1697     return (FALSE);
1698 }
1699
1700 function validate_name($name) 
1701 {
1702   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
1703
1704   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
1705     $c = $name_new[$i];
1706     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
1707       return ($name_new);
1708   }
1709
1710   return (FALSE);
1711 }
1712
1713 function playsound($filename)
1714 {
1715   return (sprintf('playsound("flasou", "%s");', $filename));
1716 }
1717
1718 function secstoword($secs)
1719 {
1720   $mins = floor($secs / 60);
1721   $secs = $secs % 60;
1722   if ($mins > 0) 
1723     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
1724   
1725   if ($secs > 0)
1726     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
1727   
1728   return ($ret);
1729 }
1730
1731 ?>