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