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