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