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