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