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