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