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