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