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