2aaa2bed62d177661c8289031cfb95c593214d58
[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   /*
574    *  $table_idx == -1: rimuove dal gruppo degli 'standup'
575    */
576   function room_sitdown(&$user, $table_idx)
577   {
578     log_main("room_sitdown", ($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
579
580     if ($table_idx > -1) 
581       $table = &$this->table[$table_idx];
582     
583     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
584       $ret = "";
585       $user_cur = &$this->user[$i];
586       /* solo per user nella room */
587       if ($user_cur->sess == '' || $user_cur->stat != 'room')
588       continue;
589       
590       $ret = "gst.st = ".($user_cur->step+1)."; ";
591       if ($table_idx > -1)
592       $ret .= table_content($this, $user_cur, $table_idx);
593       $ret .= standup_content($this, $user_cur);
594       
595       if ($user_cur == $user) {
596         $ret .=  'subst = "sitdown"; ';
597         // clean the action buttons in other tables
598         for ($e = 0 ; $e < TABLES_N ; $e++) {
599           $act_content = table_act_content(FALSE, 0, $e, $user_cur->table);
600           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, $act_content);
601         }
602       }
603       else if ($table_idx > -1) {
604         if ($table->player_n == PLAYERS_N) {
605           $act_content = table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table);
606           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
607         }
608       }
609       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
610       $user_cur->step++;
611     }
612   }
613
614   function chatt_send(&$user, $mesg)
615   {
616     if ($user->stat == 'table') {
617       $table = &$this->table[$user->table];
618     }
619     
620     $user_mesg = substr($mesg,6);
621     
622     $timecur = time();
623     
624     $dt = date("H:i ", $timecur);
625     if (strncmp($user_mesg, "/nick ", 6) == 0) {
626       log_main($user->sess, "chatt_send BEGIN");
627
628       if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
629           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
630           $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));
631           $user->step++;
632
633           return;
634       }
635       $user_mesg = "COMMAND ".$user_mesg;
636       // Search dup name
637       // change
638       // update local graph
639       // update remote graphs
640       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
641         $user_cur = &$this->user[$i];
642         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
643         if ($user_cur->sess == '')
644           continue;
645         if ($user_cur->name == $name_new) {
646           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
647           $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Nickname <b>%s</b> gi&agrave; in uso.");', $dt.NICKSERV, xcape($name_new));
648           $user->step++;
649           break;
650         }
651       }
652       if ($i == MAX_PLAYERS) {
653         $user->name = $name_new;
654
655       log_main($user->sess, "chatt_send start set");
656         
657
658         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
659           log_main($user->sess, "chatt_send set loop");
660           
661           $user_cur = &$this->user[$i];
662           if ($user_cur->sess == '')
663             continue;
664           if ($user_cur->stat == 'room') {
665             if ($user->stat == 'room' && $user->subst == 'standup') {
666               $this->standup_update(&$user);
667             }
668             else if ($user->stat == 'room' && $user->subst == 'sitdown' ||
669                      $user->stat == 'table') {
670               log_main($user->sess, "chatt_send pre table update");
671
672               $this->table_update(&$user);
673
674               log_main($user->sess, "chatt_send post table update");
675             }
676           }
677           else if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
678             $table = &$this->table[$user->table];
679             
680             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
681             $user_cur->comm[$user_cur->step % COMM_N] = sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
682                 xcape($this->user[$table->player[($user_cur->table_pos)%PLAYERS_N]]->name),
683                 xcape($this->user[$table->player[($user_cur->table_pos+1)%PLAYERS_N]]->name),
684                 xcape($this->user[$table->player[($user_cur->table_pos+2)%PLAYERS_N]]->name),
685                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3)%PLAYERS_N]]->name)),
686                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4)%PLAYERS_N]]->name)));
687             if ($user_cur == $user)
688               $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>";', 
689                                                                    xcape($user->name,ENT_COMPAT,"UTF-8"));
690             $user_cur->step++;
691           }
692         }
693       }
694     }
695     else {
696       for ($i = 0 ; $i < ($user->stat == 'room' ? MAX_PLAYERS : PLAYERS_N) ; $i++) {
697         if ($user->stat == 'room') {
698           $user_cur = &$this->user[$i];
699           if ($user_cur->sess == '' || $user_cur->stat != 'room')
700             continue;
701         }
702         else {
703           $user_cur = &$this->user[$table->player[$i]];
704         }
705         
706         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
707         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s","%s");',
708                                                              $dt.xcape($user->name), xcape($user_mesg));
709         $user_cur->step++;
710       }
711       log_legal($timecur, $user->sess, $user->name, 
712                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$user_mesg);
713     }
714   }
715
716   function &get_user($sess, &$idx)
717   {
718     GLOBAL $PHP_SELF;
719     
720     if (strlen($sess) == SESS_LEN) {
721       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
722         if (strcmp($sess, $this->user[$i]->sess) == 0) {
723           // find it
724           $idx = $i;
725           $ret = &$this->user[$i];
726           return ($ret);
727         }
728       }
729       log_main($sess, sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
730       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
731       // log_main($sess, sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
732     }
733     else {
734       log_main($sess, sprintf("get_user: Wrong strlen [%s]",$sess));
735     }
736     return (FALSE);
737   }
738
739   /*
740    * function &add_user(&$bri, &$sess, &$idx, $name)
741    *
742    * RETURN VALUE:
743    *   if ($idx != -1 && ret == FALSE)  =>  duplicated nick
744    *   if ($idx == -2 && ret == FALSE)  =>  invalid name
745    *   if ($idx == -1 && ret == FALSE)  =>  no space left
746    *   if (ret == TRUE)                 =>  SUCCESS
747    */
748   function &add_user(&$sess, &$idx, $name)
749   {
750     $idx = -1;
751     $idfree = -1;
752     
753     if (($name_new = validate_name($name)) == FALSE) {
754       $idx = -2;
755       return (FALSE);
756     }
757
758     log_auth("XXX", sprintf("ARRIVA: [%s]", $sess));
759     if (validate_sess($sess) == FALSE) 
760       $sess = "";
761
762     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
763       /* free user ? */
764       if (strcmp($sess, $this->user[$i]->sess) == 0) {
765         if ($idx == -1)
766           $idx = $i;
767       }
768       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
769         $idfree = $i;
770       }
771       if (strcmp($this->user[$i]->name, $name_new) == 0) {
772         $idx = $i;
773         break;
774       }
775     }
776     if ($idx == -1)
777       $idx = $idfree;
778
779     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
780
781     if ($idx != -1 && $i == MAX_PLAYERS) {
782       /* SUCCESS */
783       $curtime = time();
784       if ($sess == "") {
785         $this->user[$idx]->sess = uniqid("");
786         $sess = $this->user[$idx]->sess;
787         
788       }
789       else {
790         $this->user[$idx]->sess = $sess;
791       }
792       $this->user[$idx]->name = $name_new;
793       $this->user[$idx]->stat = "room";
794       $this->user[$idx]->subst = "standup";
795       $this->user[$idx]->lacc =   $curtime;
796       $this->user[$idx]->laccwr = $curtime;
797       $this->user[$idx]->bantime = 0;
798       
799       log_main("XXX", sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
800       
801       return ($this->user[$idx]);
802     }
803
804     return (FALSE);
805   }
806   
807   function standup_update(&$user)
808   {
809     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
810       $user_cur = &$this->user[$i];
811       if ($user_cur->sess == '')
812         continue;
813
814       log_main("STANDUP START", $user_cur->stat);
815       
816       if ($user_cur->stat == 'room') {
817         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".standup_content($this, $user_cur);
818         if ($user_cur == $user)
819           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
820         
821         log_main("FROM STANDUP", "NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
822         
823         $user_cur->step++;
824       }
825     }
826   }
827
828
829 } // end class brisco
830
831 function make_seed()
832 {
833   list($usec, $sec) = explode(' ', microtime());
834   return (float) $sec + ((float) $usec * 100000);
835 }
836
837 function log_main($sess, $log) {
838   if (BRISK_DEBUG != TRUE)
839     return;
840
841   $fp = fopen("/tmp/brisk_main.log", 'a');
842   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
843   fclose($fp);
844 }
845
846 function log_rd($sess, $log) {
847   if (BRISK_DEBUG != TRUE)
848     return;
849
850   $fp = fopen("/tmp/brisk_rd.log", 'a');
851   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
852   fclose($fp);
853 }
854
855 function log_rd2($sess, $log) {
856   if (BRISK_DEBUG != TRUE)
857     return;
858
859   $fp = fopen("/tmp/brisk_rd2.log", 'a');
860   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
861   fclose($fp);
862 }
863
864 function log_send($sess, $log) {
865   if (BRISK_DEBUG != TRUE)
866     return;
867
868   $fp = fopen("/tmp/brisk_send.log", 'a');
869   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
870   fclose($fp);
871 }
872
873 function log_auth($sess, $log) {
874   if (BRISK_DEBUG != TRUE)
875     return;
876
877   $fp = fopen("/tmp/brisk_auth.log", 'a');
878   fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
879   fclose($fp);
880 }
881
882 function log_wr($sess, $log) {
883   if (BRISK_DEBUG != TRUE)
884     return;
885
886   $fp = fopen("/tmp/brisk_wr.log", 'a');
887   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
888   fclose($fp);
889 }
890
891 function log_load($sess, $log) {
892   if (BRISK_DEBUG != TRUE)
893     return;
894
895   $fp = fopen("/tmp/brisk_load.log", 'a');
896   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
897   fclose($fp);
898 }
899
900 function log_legal($timecur, $sess, $name, $where, $mesg) 
901 {
902   GLOBAL $_SERVER;
903
904   $fp = fopen(LEGAL_PATH, 'a');
905   /* Unix time | session | nickname | IP | where was | mesg */
906   fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $timecur, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
907   fclose($fp);
908 }
909
910
911
912 function init_data()
913 {
914   $brisco =& new brisco();
915
916   return $brisco;
917 }
918
919 function lock_data()
920 {
921         //  echo "LOCK: ".FTOK_PATH."/main";
922         //  exit;
923   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
924     echo "FTOK FAILED";
925     exit;
926   }
927   // echo "FTOK ".$tok."<br>";
928   if (($res = sem_get($tok)) == FALSE) {
929     echo "SEM_GET FAILED";
930     exit;
931   }
932   if (sem_acquire($res)) 
933     return ($res);
934   else
935     return (false);
936 }
937
938 function unlock_data($res)
939 {
940   return (sem_release($res));
941 }
942
943
944 function &load_data() 
945 {
946   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
947     echo "FTOK FAILED";
948     exit;
949   }
950
951   if ($shm = shm_attach($tok,200000 * TABLES_N)) {
952     if(($bri = @shm_get_var($shm, $tok)) == false) {
953       log_main("XXX", "INIT MAIN DATA");
954
955       $bri = init_data();
956       shm_put_var($shm, $tok, $bri);
957     }
958     
959     shm_detach($shm);
960
961     $ret = &$bri;
962     return ($ret);
963   }
964
965   return (NULL);
966 }
967
968
969 function save_data(&$bri) 
970 {
971   $ret =   FALSE;
972   $shm =   FALSE;
973   $isacq = FALSE;
974
975   // var_dump($bri);
976
977   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
978     return (FALSE);
979
980   do {
981     $isacq = TRUE;
982     
983     if (($shm = shm_attach($tok,200000 * TABLES_N)) == FALSE)
984       break;
985     
986     if (shm_put_var($shm, $tok, $bri) == FALSE)
987       break;
988     // log_main("XXX", "QUI CI ARRIVA [".$bri->user[0]->name."]");
989     $ret = TRUE;
990   } while (0);
991   
992   if ($shm)
993     shm_detach($shm);
994      
995   return ($ret);
996 }
997
998 function table_act_content($isstanding, $sitted, $table, $cur_table)
999 {
1000   $ret = "";
1001
1002   if ($isstanding) {
1003     if ($sitted < PLAYERS_N) {
1004       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
1005     }
1006   }
1007   else {
1008     if ($table == $cur_table)
1009       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
1010     else
1011       $ret = "";
1012   }
1013   return ($ret);
1014 }
1015
1016 function table_content($bri, $user, $table_idx)
1017 {
1018   $content = "";
1019
1020   // TODO
1021   //
1022   //   Si possono usare i dati nella classe table
1023   //
1024
1025   $sess = $user->sess;
1026   $table = &$bri->table[$table_idx];
1027
1028   if ($user->stat != 'room')
1029     return;
1030
1031   for ($i = 0 ; $i < $table->player_n ; $i++) {
1032     $user_cur = &$bri->user[$table->player[$i]];
1033
1034     if ($user_cur == $user) 
1035         { $hilion = "<b>"; $hilioff = "</b>"; }
1036       else
1037         { $hilion = ""; $hilioff = ""; }
1038
1039     log_main($bri->user[$e]->name, sprintf("IN TABLE [%d]", $table_idx));
1040     
1041     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1042   }
1043   /*
1044   for ( ; $i < PLAYERS_N ; $i++)
1045     $content .= "<br>";
1046   */
1047
1048   $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1049   
1050   return ($ret);
1051 }
1052
1053 function standup_content(&$bri, $user)
1054 {
1055   $ret = "";
1056   $content = "";
1057
1058   if ($user->stat != 'room')
1059     return;
1060
1061   for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1062     if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
1063       continue;
1064     $ct++;
1065   }
1066
1067   $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1068
1069   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1070     if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
1071       continue;
1072
1073
1074     if ($bri->user[$e]->subst == "standup") {
1075       if (($ct % 4) == 0) {
1076         $content .= '<tr>';
1077       }
1078       if ($bri->user[$e] == $user) 
1079         { $hilion = "<b>"; $hilioff = "</b>"; }
1080       else
1081         { $hilion = ""; $hilioff = ""; }
1082
1083       $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($bri->user[$e]->name), $hilioff);
1084       if (($ct % 4) == 3) {
1085         $content .= '</tr>';
1086       }
1087       $ct++;
1088     }
1089   }
1090   $content .= '</table>';
1091         
1092   $content2 = '<input class=\\"button\\" name=\\"logout\\" value=\\"Esco.\\" onclick=\\"window.onunload = null; act_logout();\\" type=\\"button\\">';
1093   $ret .= sprintf('$("standup").innerHTML = "%s";  $("esco").innerHTML = "%s";', 
1094                   $content, $content2);
1095
1096   return ($ret);
1097 }
1098
1099
1100 function show_notify($text, $tout, $butt, $w, $h)
1101 {
1102   log_main("SHOW_NOTIFY", $text);
1103   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
1104 }
1105
1106 function briscola_show($bri, $table, $user)
1107 {
1108   $ptnadd = "";
1109   $ret = "";
1110
1111   if ($table->asta_card == 9) 
1112     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
1113   
1114   /* text of caller cell */
1115   if ($user->table_pos == $table->asta_win) 
1116     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
1117   else 
1118     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
1119                     xcape($bri->user[$table->player[$table->asta_win]]->name), $ptnadd);
1120
1121   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1122                   $table->asta_win);
1123   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1124   $ret .= sprintf('$("caller").style.visibility = "visible";');
1125   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1126   $ret .= sprintf('$("astalascio").style.visibility = "";');
1127   $ret .= sprintf('$("asta").style.visibility = "hidden";');
1128   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1129   
1130   return ($ret);
1131 }
1132
1133
1134 function game_result($asta_pnt, $pnt)
1135 {
1136   if ($asta_pnt == 61) {
1137     if ($pnt > 60)
1138       return (1);
1139     else if ($pnt == 60)
1140       return (0);
1141     else
1142       return (-1);
1143   }
1144   else {
1145     if ($pnt >= $asta_pnt)
1146       return (1);
1147     else
1148       return (-1);
1149   }
1150 }
1151
1152 function multoval($mult)
1153 {
1154   if ($mult == 2)
1155     return ("doppio");
1156   else if ($mult == 4)
1157     return ("quadruplo");
1158   else
1159     return (sprintf("%d-plo", $mult));
1160 }
1161
1162 function show_table_info(&$bri, &$table, $table_pos)
1163 {
1164   $user = &$bri->user[$table->player[$table_pos]];
1165
1166   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1167   $noty = sprintf('<table class=\"points\"><tr><th></th>');
1168   
1169   // Names.
1170   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1171     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($bri->user[$table->player[$i]]->name));
1172   $noty .= sprintf("</tr>");
1173
1174   // Points.
1175   log_main("show_table_info", "pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1176
1177   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1178     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1179     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1180       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1181     $noty .= "</tr>";
1182   }
1183
1184   // Total points.
1185   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1186   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1187     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1188   $noty .= "</tr></table>";
1189
1190   if ($table->old_reason != "") {
1191     $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1192   }
1193
1194   if ($table->old_win != -1) {
1195     $win = $table->player[$table->old_win];
1196     $fri = $table->player[$table->old_friend];
1197
1198     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1199
1200     if ($win != $fri) {
1201       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
1202                        xcape($bri->user[$win]->name),
1203                        xcape($bri->user[$fri]->name));
1204       if ($table->old_pnt == 120) {
1205         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
1206       }
1207       else {
1208         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
1209                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1210                           'pi&ugrave; di 60'), $table->old_pnt,
1211                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1212       }
1213     }
1214     else {
1215       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
1216                        xcape($bri->user[$win]->name));
1217       if ($table->old_pnt == 120) {
1218         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
1219       }
1220       else {
1221         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
1222                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1223                           'pi&ugrave; di 60'), $table->old_pnt,
1224                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1225       }
1226     }
1227   }
1228   if ($table->mazzo == $table_pos) 
1229     $noty .= "Fai <b>tu</b> il mazzo,";
1230   else {
1231     $unam = xcape($bri->user[$table->player[$table->mazzo]]->name);
1232     $noty .= "Il mazzo a <b>$unam</b>,";
1233   }
1234
1235   if ($user->subst == 'asta') {
1236     if ($table->asta_win == -1)  // auction case
1237       $curplayer = $table->gstart % PLAYERS_N;
1238     else 
1239       $curplayer = $table->asta_win;
1240   }
1241   else if ($user->subst == 'game') {
1242     $curplayer = ($table->gstart + $table->turn) % PLAYERS_N;
1243   }
1244
1245
1246   if ($curplayer == $table_pos) {
1247     $noty .= " tocca a <b>te</b> giocare.";
1248   }
1249   else {
1250     $unam = xcape($bri->user[$table->player[$curplayer]]->name);
1251     $noty .= " tocca a <b>$unam</b> giocare.";
1252   }
1253
1254   if ($table->mult > 1) {
1255     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
1256   }
1257   $noty .= "<hr><br>";
1258
1259   $ret .= show_notify($noty, 3000, "torna alla partita", 500, 400);
1260   
1261   return ($ret);
1262 }
1263
1264 function root_wellcome($user)
1265 {
1266   GLOBAL $root_wellarr;
1267
1268   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
1269     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $root_wellarr[$i]));
1270
1271   return ($ret);
1272 }
1273
1274 function table_wellcome($user)
1275 {
1276   GLOBAL $table_wellarr;
1277
1278   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
1279     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $table_wellarr[$i]));
1280
1281   return ($ret);
1282 }
1283
1284 function show_room(&$bri, &$user)
1285 {
1286   $ret .= sprintf('gst.st = %d;',  $user->step);
1287   $ret .= sprintf('stat = "%s";',  $user->stat);
1288
1289   $ret .= root_wellcome($user);
1290   $ret .= sprintf('subst = "%s";', $user->subst);
1291   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1292   for ($i = 0 ; $i < TABLES_N ; $i++) {
1293     $ret .= table_content($bri, $user, $i);
1294     $act_content = table_act_content(($user->subst == 'standup'), 
1295                                      $bri->table[$i]->player_n, $i, $user->table);
1296     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
1297   }
1298   $ret .= standup_content($bri, $user);
1299   
1300   return ($ret);
1301 }
1302
1303
1304
1305 /* show table 
1306 is_transition (is from room to table ?)
1307 is_again      (is another game)
1308
1309 Examples                    of $is_transition, $is_again:
1310   from reload of the page:              FALSE, FALSE
1311   from sitdown in room:                  TRUE, FALSE
1312   from table: asta cmd e tutti passano:  TRUE, TRUE
1313   from table: fine partita:              TRUE, TRUE
1314  */
1315 function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
1316 {
1317   $table_idx = $user->table;
1318   $table = &$bri->table[$table_idx];
1319   $table_pos = $user->table_pos;
1320
1321   $ret = "table_init();";
1322   $ret .= $table->exitlock_show(&$bri->user, $table_pos);
1323   if (!$is_again) {
1324     /* GENERAL STATUS */
1325     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1326                      $sendstep, $user->stat, $user->subst, $table_pos);
1327     /* BACKGROUND */
1328     $ret .= "background_set();";
1329     
1330     /* USERS INFO */
1331     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1332     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1333                     xcape($bri->user[$table->player[($table_pos)%PLAYERS_N]]->name),
1334                     xcape($bri->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
1335                     xcape($bri->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
1336                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
1337                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
1338   }
1339   /* NOTIFY FOR THE CARD MAKER */
1340   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1341     $ret .= show_table_info(&$bri, &$table, $table_pos);
1342   }
1343   if (!$is_again) 
1344     $ret .= table_wellcome($user);
1345
1346   if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1347     $ret .= playsound("cow.mp3");
1348   }
1349
1350
1351   /* CARDS */
1352   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1353     $ret .= "|";
1354     
1355     for ($i = 0 ; $i < 8 ; $i++) {
1356       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
1357         $ct = 0;
1358         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1359           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
1360             $ct++;
1361             if ($ct == $i+1)
1362               break;
1363           }
1364         }
1365         log_rd($sess, "O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1366         
1367         $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
1368                          $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
1369                               $table->card[$o]->value : -1), 
1370                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1371       }
1372     }    
1373   }
1374   else {
1375     $taked  = array(0,0,0,0,0);
1376     $inhand = array(0,0,0,0,0);
1377     $ontabl  = array(-1,-1,-1,-1,-1);
1378     $cards  = array();
1379
1380     for ($i = 0 ; $i < 40 ; $i++) {
1381       if ($table->card[$i]->stat == 'hand') {
1382         if ($table->card[$i]->owner == $table_pos) {
1383           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1384         }
1385         $inhand[$table->card[$i]->owner]++;
1386       }
1387       else if ($table->card[$i]->stat == 'take') {
1388         log_main("Card taked:", $table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1389         $taked[$table->card[$i]->owner]++;
1390       }
1391       else if ($table->card[$i]->stat == 'table') {
1392         $ontabl[$table->card[$i]->owner] = $i;
1393       }
1394     }
1395     $logg = "\n";
1396     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1397       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1398     }
1399     log_main("Stat table:", $logg);
1400
1401     /* Set ours cards. */
1402     $oursarg = "";
1403     for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
1404       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1405     for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
1406       $oursarg .= ($i == 0 ? "" : ", ")."-1";
1407     $ret .= sprintf('card_setours(%s);', $oursarg);
1408
1409     /* Dispose all cards */
1410     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1411       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1412       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1413                       $inhand[$i], $taked[$i]);
1414
1415       if ($ontabl[$i] != -1) {
1416         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1417                         $table->card[$ontabl[$i]]->value, 
1418                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1419       }
1420     }
1421   }
1422
1423   /* Show auction */
1424   if ($user->subst == 'asta') {
1425
1426     /* show users auction status */
1427     $showst = "";
1428     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1429       $user_cur = &$bri->user[$table->player[$i]];
1430       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1431                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1432     }
1433     if (PLAYERS_N == 3)
1434         $showst .= ",-2,-2";
1435     $ret .= sprintf('show_astat(%s);', $showst);
1436
1437     if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
1438       /* show card chooser */
1439       $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
1440                       $table->asta_card);
1441     }
1442     else {
1443       /* show auction */
1444       if ($table_pos == ($table->gstart % PLAYERS_N) &&
1445           $table->asta_win == -1) 
1446         $ret .= sprintf('dispose_asta(%d,%d, %s);', 
1447                         $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
1448       else
1449         $ret .= sprintf('dispose_asta(%d,%d, %s);',
1450                         $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
1451     }
1452
1453     /* Remark */
1454     if ($table->asta_win == -1) { // auction case
1455       if ($table_pos == ($table->gstart % PLAYERS_N)) 
1456         $ret .= "remark_on();";
1457       else
1458         $ret .= "remark_off();";
1459     }
1460     else { // chooseed case
1461       if ($table_pos == $table->asta_win) 
1462         $ret .= "remark_on();";
1463       else
1464         $ret .= "remark_off();";
1465     }
1466   }
1467   else if ($user->subst == 'game') {
1468     /* HIGHLIGHT */
1469     if (($table->gstart + $table->turn) % PLAYERS_N == $table_pos) 
1470       $ret .= "is_my_time = true; remark_on();";
1471     else
1472       $ret .= "remark_off();";
1473     
1474     /* WHO CALL AND WATH */
1475     $ret .= briscola_show($bri, $table, $user);
1476     
1477   }
1478   return ($ret);
1479   }
1480
1481 function calculate_winner(&$table)
1482 {
1483   $briontab = FALSE;
1484   $ontab = array();
1485   $ontid = array();
1486   $cur_win  =  -1;
1487   $cur_val  = 100;
1488   $cur_seed = $table->briscola - ($table->briscola % 10);
1489
1490   for ($i = 0 ; $i < 40 ; $i++) {
1491     if ($table->card[$i]->stat != "table")
1492       continue;
1493
1494     log_wr($sess, sprintf("Card On table: [%d]", $i));
1495
1496     $v = $table->card[$i]->value; 
1497     $ontab[$table->card[$i]->owner] = $v;
1498     $ontid[$table->card[$i]->owner] = $i;
1499     /* se briscola setto il flag */
1500     if (($v - ($v % 10)) == $cur_seed)
1501       $briontab = TRUE;
1502   }
1503
1504   if ($briontab == FALSE) {
1505     $cur_win  = $table->gstart;
1506     $cur_val  = $ontab[$cur_win];
1507     $cur_seed = $cur_val - ($cur_val % 10);
1508   }
1509
1510   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1511     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1512       if ($ontab[$i] < $cur_val) {
1513         $cur_val = $ontab[$i];
1514         $cur_win = $i;
1515       }
1516     }
1517   }
1518
1519   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1520     $table->card[$ontid[$i]]->owner = $cur_win;
1521     $table->card[$ontid[$i]]->stat =  "take";
1522   }
1523   return ($cur_win);
1524 }
1525
1526 function calculate_points(&$table)
1527 {
1528   GLOBAL $G_all_points; 
1529
1530   $pro = 0;
1531
1532   if ($table->asta_pnt == 60)
1533     $table->asta_pnt = 61;
1534
1535   $table->old_reason = "";
1536   $table->old_win = $table->asta_win;
1537   $table->old_friend = $table->friend;
1538   $table->old_asta_pnt = $table->asta_pnt;
1539
1540   for ($i = 0 ; $i < 40 ; $i++) {
1541     $ctt = $table->card[$i]->value % 10;
1542     $own = $table->card[$i]->owner;
1543     if ($own == $table->asta_win || $own == $table->friend) 
1544       $pro += $G_all_points[$ctt];
1545   }
1546
1547   log_wr("XXX", sprintf("PRO: [%d]", $pro));
1548
1549   
1550   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1551     $table->points[$table->points_n % MAX_POINTS] = array();
1552     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1553       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1554     $table->points_n++;
1555     $table->old_pnt = $pro;
1556     $table->mult *= 2;
1557
1558     return;
1559   }
1560
1561   if ($pro >= $table->asta_pnt) 
1562     $sig = 1;
1563   else
1564     $sig = -1;
1565
1566   $table->points[$table->points_n % MAX_POINTS] = array();
1567   for ($i = 0 ; $i < 5 ; $i++) {
1568     if ($i == $table->asta_win) 
1569       $pt = ($i == $table->friend ? 4 : 2);
1570     else if ($i == $table->friend) 
1571       $pt = 1;
1572     else
1573       $pt = -1;
1574
1575     log_wr("XXX", sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1576
1577     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
1578
1579     log_wr("XXX", sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
1580     
1581     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
1582     $table->total[$i] += $pt;
1583   }
1584   $table->points_n++;
1585   $table->old_pnt = $pro;
1586   $table->mult = 1;
1587 }
1588
1589 function validate_sess($sess) 
1590 {
1591   if (strlen($sess) == SESS_LEN) 
1592     return (TRUE);
1593   else
1594     return (FALSE);
1595 }
1596
1597 function validate_name($name) 
1598 {
1599   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
1600
1601   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
1602     $c = $name_new[$i];
1603     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
1604       return ($name_new);
1605   }
1606
1607   return (FALSE);
1608 }
1609
1610 function playsound($filename)
1611 {
1612   return (sprintf('playsound("flasou", "%s");', $filename));
1613 }
1614
1615 function secstoword($secs)
1616 {
1617   $mins = floor($secs / 60);
1618   $secs = $secs % 60;
1619   if ($mins > 0) 
1620     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
1621   
1622   if ($secs > 0)
1623     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
1624   
1625   return ($ret);
1626 }
1627
1628 ?>