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