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