room_join_wakeup func added, normalized log
[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 $the_end;    // Flag to change the end of the session
463
464   function User() {
465   }
466
467   function &create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
468     GLOBAL $G_false;
469
470     if (($thiz =& new User()) == FALSE)
471       return ($G_false);
472
473     $thiz->name  = $name;
474     $thiz->sess  = $sess;
475     $thiz->ip    = $ip;
476     $thiz->lacc   = time();
477     $thiz->laccwr = time();
478     $thiz->bantime = 0;
479     $thiz->stat  = $stat;
480     $thiz->subst  = $subst;
481     $thiz->step  = 1;
482     $thiz->trans_step  = -1;
483     $thiz->comm  = array();
484     $thiz->asta_card = -2;
485     $thiz->asta_pnt  = -1;
486     $thiz->handpt = -1;
487     $thiz->exitislock = TRUE;
488     
489     $thiz->table = $table;
490     
491     return ($thiz);
492   }
493
494   function &clone(&$from)
495   {
496     GLOBAL $G_false;
497     
498     if (($thiz = new User()) == FALSE)
499       return ($G_false);
500     
501     $thiz->name = $from->name;
502     $thiz->sess = $from->sess;
503     $thiz->ip = $from->ip;
504     $thiz->lacc = $from->lacc;
505     $thiz->laccwr = $from->laccwr;
506     $thiz->bantime = $from->bantime;
507     $thiz->stat = $from->stat;
508     $thiz->subst = $from->subst;
509     $thiz->step = $from->step;
510     $thiz->trans_step = $from->trans_step;
511     $thiz->comm = array();
512
513     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
514     for ($i = $i_start ; $i < $from->step ; $i++) {
515       $ii = $i % COMM_N;
516       $thiz->comm[$ii]   = $from->comm[$ii];
517     }
518     $thiz->asta_card = $from->asta_card;
519     $thiz->asta_pnt = $from->asta_pnt;
520     $thiz->handpt = $from->handpt;
521     $thiz->exitislock = $from->exitislock;
522     $thiz->table = $from->table;
523     $thiz->table_pos = $from->table_pos;
524     $thiz->the_end = $from->the_end;
525
526     return ($thiz);
527   }
528   
529   function &spawn(&$from, $table, $table_pos)
530   {
531     GLOBAL $G_false;
532     
533     if (($thiz =& new User()) == FALSE)
534       return ($G_false);
535     
536     $thiz->name       = $from->name;
537     $thiz->sess       = $from->sess;
538     $thiz->ip         = $from->ip;
539     $thiz->lacc       = $from->lacc;
540     $thiz->laccwr     = $from->laccwr;
541     $thiz->bantime    = $from->bantime;
542     $thiz->stat       = $from->stat;
543     $thiz->subst      = $from->subst;
544     $thiz->step       = $from->step;
545     $thiz->trans_step = $from->trans_step;
546     $thiz->comm       = array();
547
548     $i_start = (1 > ($from->step - COMM_N) ? 1 : ($from->step - COMM_N)); 
549     for ($i = $i_start ; $i < $from->step ; $i++) {
550       log_wr("XX", "TRY PUSH:".$i);
551       $ii = $i % COMM_N;
552       $thiz->comm[$ii]   = $from->comm[$ii];
553     }
554     
555     $thiz->asta_card  = $from->asta_card;
556     $thiz->asta_pnt   = $from->asta_pnt;
557     $thiz->handpt     = $from->handpt;
558     $thiz->exitislock = $from->exitislock;
559     $thiz->the_end    = $from->the_end;
560
561     $thiz->table      = $table;
562     $thiz->table_pos  = $table_pos;
563
564     return ($thiz);
565   }
566   
567   function stat_set($stat) {
568     $this->stat = "$stat";
569     
570     /*
571     if (validate_sess($this->sess)) {
572       $fp = fopen(PROXY_PATH."/".$this->sess.".stat", 'w');
573       fwrite($fp, sprintf("%s\n",$this->stat));
574       fclose($fp);
575     }
576     */
577   }
578
579   function step_set($step) {
580     $this->step = $step;
581     
582     do {
583       if (validate_sess($this->sess) == FALSE)
584         break;
585       if (($fp = @fopen(PROXY_PATH."/".$this->sess.".step", 'w')) == FALSE)
586         break;
587       fwrite($fp, pack("l",$this->step), 4);
588       fclose($fp);
589
590       return (TRUE);
591     } while (0);
592
593     return (FALSE);
594   }
595
596   function step_inc() {
597     $this->step++;
598     
599     if (validate_sess($this->sess)) {
600       $fp = fopen(PROXY_PATH."/".$this->sess.".step", 'w');
601       fwrite($fp, pack("l",$this->step), 4);
602       fclose($fp);
603
604       return (TRUE);
605     }
606     
607     return (FALSE);
608   }
609 }
610
611 function step_get($sess) {
612   $fp = FALSE;
613   $ct = 0;
614   do {
615     if (validate_sess($sess) == FALSE)
616       break;
617   $ct = 1;
618     if (($fp = @fopen(PROXY_PATH."/".$sess.".step", 'rb')) == FALSE)
619       break;
620   $ct = 2;
621     if (($s = fread($fp, 4)) == FALSE)
622       break;
623   $ct = 3;
624     if (strlen($s) != 4)
625       break;
626   $ct = 4;
627     $arr = unpack('l', $s);
628     fclose($fp);
629
630     // log_rd2($sess, "A0: ".$arr[0]."  A1: ".$arr[1]);
631     return ($arr[1]);
632   } while (0);
633
634   if ($fp != FALSE)
635     fclose($fp);
636
637   log_rd2($sess, "STEP_GET: return false ".$ct);
638   return (FALSE);
639 }
640
641 function step_unproxy($sess) {
642   log_rd2($sess, "UNPROXY: ".PROXY_PATH."/".$sess.".step");
643   @unlink(PROXY_PATH."/".$sess.".step");
644 }
645
646
647 class Room {
648   var $user;
649   var $table;
650   var $comm; // commands for many people
651   var $step; // current step of the comm array
652   var $garbage_timeout;
653
654   function Room () {
655     $this->user = array();
656
657     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
658       $this->user[$i] =& User::create("", "");
659     }
660
661     for ($i = 0 ; $i < TABLES_N ; $i++) 
662       $this->table[$i] =& Table::create();
663     $this->garbage_timeout = 0;
664   }
665
666   function garbage_manager($force)
667   {
668     
669     /* Garbage collector degli utenti in timeout */
670     $curtime = time();
671     if ($force || $this->garbage_timeout < $curtime) {
672       
673       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
674         $user_cur = &$this->user[$i];
675         if ($user_cur->sess == "")
676           continue;
677         
678         if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) { // Auto logout dell'utente
679           log_rd2($user_cur->sess, "AUTO LOGOUT.");
680
681           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
682             log_auth($user_cur->sess, "Autologout session.");
683             
684             $tmp_sess = $user_cur->sess;
685             $user_cur->sess = "";
686             step_unproxy($tmp_sess);
687             $user_cur->name = "";
688             $user_cur->the_end = FALSE;
689             
690             log_rd2($user_cur->sess, "AUTO LOGOUT.");
691             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
692               $this->room_wakeup(&$user_cur);
693             else if ($user_cur->subst == 'standup')
694               $this->room_outstandup(&$user_cur);
695             else
696               log_rd2($sess, "LOGOUT FROM WHAT ???");
697           }
698         }
699
700         if ($user_cur->laccwr + EXPIRE_TIME_SMAMMA < $curtime) { // lo rimettiamo in piedi
701           if ($user_cur->stat == 'room' && $user_cur->subst == 'sitdown') {
702             $this->room_wakeup(&$user_cur);
703             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
704             $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);
705             $user_cur->step_inc();
706           }
707         }
708       }
709       log_rd2($user_cur->sess, "GARBAGE UPDATED!");
710       
711       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
712     }
713
714     // BAN_IP_CLEAN
715
716   }
717
718
719   function room_wakeup(&$user)
720   {
721     $table_idx = $user->table;
722     $table = &$this->table[$table_idx];
723
724     log_main("WAKEUP", "begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
725
726     $curtime = time();
727
728     $from_table = ($user->stat == "table");
729     if ($from_table) {
730       log_main("WAKEUP", "from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
731
732       for ($i = 0 ; $i < $table->player_n ; $i++) {
733         $user_cur = &$this->user[$table->player[$i]];
734         log_main("PREIMPOST", "INLOOP name: ".$user_cur->name);
735
736         if ($user_cur != $user) {
737           $user_cur->stat_set("room");
738           $user_cur->subst = "sitdown";
739           $user_cur->laccwr = $curtime;
740         }
741         else if ($user->sess != "") {
742           $user_cur->stat_set("room");
743           $user_cur->subst = "standup";
744           $user_cur->laccwr = $curtime;
745           $user_cur->table = -1;
746         }
747       }
748     }
749     else {
750       $user->stat_set("room");
751       $user->subst = "standup";
752       $user->laccwr = $curtime;
753     }
754     /* aggiorna l'array dei giocatori al tavolo. */
755     $table->user_rem(&$this, &$user);
756
757     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
758       $user_cur = &$this->user[$i];
759       if ($user_cur->sess == '' || $user_cur->stat != 'room')
760         continue;
761       
762       log_main("VALORI", "name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
763
764       $ret = "gst.st = ".($user_cur->step+1)."; ";
765       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
766         $ret .= 'gst.st_loc++; the_end=true; window.onunload = null; document.location.assign("index.php");|';
767         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
768         log_main("DOCUMENT.index.php", "from table");
769       }
770       else if ($user_cur->stat == "room") {
771         log_main("DOCUMENT.index.php", "from table");
772
773         $ret .= table_content($this, $user_cur, $table_idx);
774         $ret .= standup_content($this, $user_cur);
775         
776         $act_content = table_act_content(FALSE, 0, $table_idx, $user->table);
777         $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
778         
779         
780         if ($user_cur == $user) {
781           // set the new status 
782           $ret .=  'subst = "standup"; ';
783           // clean the action buttons in other tables
784           for ($e = 0 ; $e < TABLES_N ; $e++) {
785             if ($this->table[$e]->player_n < PLAYERS_N)
786               $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, table_act_content(TRUE, 0, $e, $user->table));
787           }
788         }
789         else {
790           $act_content = table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table);
791           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
792         }
793       }
794       log_wr($user_cur->sess, "ROOM_WAKEUP: ".$ret);
795       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
796       $user_cur->step_inc();
797     }
798   }
799
800   function room_join_wakeup(&$user)
801   {
802     $table_idx = $user->table;
803     $table = &$this->table[$table_idx];
804
805     log_main("JOIN_WAKEUP", "begin function table:".$table_idx."  stat: ".$user->stat."  subst: ".$user->subst);
806
807     $curtime = time();
808     
809     log_main("JOIN WAKEUP", "from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
810     
811     for ($i = 0 ; $i < $table->player_n ; $i++) {
812       $user_cur = &$this->user[$table->player[$i]];
813       log_main("PREIMPOST", "INLOOP name: ".$user_cur->name);
814       if ($user_cur->sess != "") {
815         $user_cur->laccwr = $curtime;
816         if ($user_cur->subst == "shutdowned") {
817           $user_cur->stat_set("room");
818           $user_cur->subst = "sitdown";
819         }
820         else if ($user_cur->subst == "shutdowner") {
821           $user_cur->stat_set("room");
822           $user_cur->subst = "standup";
823           $user_cur->table = -1;
824           $user_wup = &$user_cur;
825         }
826       }
827     }
828
829     /* aggiorna l'array dei giocatori al tavolo. */
830     $table->user_rem(&$this, &$user_wup);
831
832     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
833       $user_cur = &$this->user[$i];
834       if ($user_cur->sess == '' || $user_cur->stat != 'room')
835         continue;
836       
837       log_main("VALORI", "name: ".$user_cur->name."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
838
839       $ret = "gst.st = ".($user_cur->step+1)."; ";
840       if ($user_cur->stat == "room") {
841         log_main("DOCUMENT.index.php", "from table");
842
843         $ret .= table_content($this, $user_cur, $table_idx);
844         $ret .= standup_content($this, $user_cur);
845         
846         $act_content = table_act_content(FALSE, 0, $table_idx, $user->table);
847         $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
848         
849         
850         if ($user_cur == $user_wup) {
851           // set the new status 
852           $ret .=  'subst = "standup"; ';
853           // clean the action buttons in other tables
854           for ($e = 0 ; $e < TABLES_N ; $e++) {
855             if ($this->table[$e]->player_n < PLAYERS_N)
856               $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, table_act_content(TRUE, 0, $e, $user->table));
857           }
858         }
859         else {
860           $act_content = table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table);
861           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
862         }
863       }
864       log_wr($user_cur->sess, "ROOM_JOIN_WAKEUP: ".$ret);
865       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
866       $user_cur->step_inc();
867     }
868   }
869
870   function room_outstandup(&$user)
871   {
872     $this->room_sitdown(&$user, -1);
873   }
874   
875   function table_update(&$user)
876   {
877     log_main("table_update", "pre - USER: ".$user->name);
878
879     $table_idx = $user->table;
880
881     if ($table_idx > -1) 
882       $table = &$this->table[$table_idx];
883     
884     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
885       $ret = "";
886       $user_cur = &$this->user[$i];
887       if ($user_cur->sess == '' || $user_cur->stat != 'room')
888       continue;
889       
890       $ret = "gst.st = ".($user_cur->step+1)."; ";
891       if ($table_idx > -1)
892         $ret .= table_content($this, $user_cur, $table_idx);
893       
894       if ($user_cur == $user) {
895         $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
896       }
897       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
898       $user_cur->step_inc();
899     }
900
901     log_main("table_update", "post");
902   }
903
904   function room_sitdown(&$user, $table_idx)
905   {
906     log_main("room_sitdown", ($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
907
908     if ($table_idx > -1) 
909       $table = &$this->table[$table_idx];
910     
911     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
912       $ret = "";
913       $user_cur = &$this->user[$i];
914       if ($user_cur->sess == '' || $user_cur->stat != 'room')
915       continue;
916       
917       $ret = "gst.st = ".($user_cur->step+1)."; ";
918       if ($table_idx > -1)
919       $ret .= table_content($this, $user_cur, $table_idx);
920       $ret .= standup_content($this, $user_cur);
921       
922       if ($user_cur == $user) {
923         $ret .=  'subst = "sitdown"; ';
924         // clean the action buttons in other tables
925         for ($e = 0 ; $e < TABLES_N ; $e++) {
926           $act_content = table_act_content(FALSE, 0, $e, $user_cur->table);
927           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, $act_content);
928         }
929       }
930       else if ($table_idx > -1) {
931         if ($table->player_n == PLAYERS_N) {
932           $act_content = table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table);
933           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
934         }
935       }
936       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
937       $user_cur->step_inc();
938     }
939   }
940
941   function chatt_send(&$user, $mesg)
942   {
943     if ($user->stat == 'table') {
944       $table = &$this->table[$user->table];
945     }
946     
947     $user_mesg = substr($mesg,6);
948     
949     $timecur = time();
950     
951     $dt = date("H:i ", $timecur);
952     if (strncmp($user_mesg, "/nick ", 6) == 0) {
953       log_main($user->sess, "chatt_send BEGIN");
954
955       if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
956           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
957           $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));
958           $user->step_inc();
959
960           return;
961       }
962       $user_mesg = "COMMAND ".$user_mesg;
963       // Search dup name
964       // change
965       // update local graph
966       // update remote graphs
967       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
968         $user_cur = &$this->user[$i];
969         //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
970         if ($user_cur->sess == '')
971           continue;
972         if ($user_cur->name == $name_new) {
973           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
974           $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Nickname <b>%s</b> gi&agrave; in uso.");', $dt.NICKSERV, xcape($name_new));
975           $user->step_inc();
976           break;
977         }
978       }
979       if ($i == MAX_PLAYERS) {
980         $user->name = $name_new;
981
982       log_main($user->sess, "chatt_send start set");
983         
984
985         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
986           log_main($user->sess, "chatt_send set loop");
987           
988           $user_cur = &$this->user[$i];
989           if ($user_cur->sess == '')
990             continue;
991           if ($user_cur->stat == 'room') {
992             if ($user->stat == 'room' && $user->subst == 'standup') {
993               $this->standup_update(&$user);
994             }
995             else if ($user->stat == 'room' && $user->subst == 'sitdown' ||
996                      $user->stat == 'table') {
997               log_main($user->sess, "chatt_send pre table update");
998
999               $this->table_update(&$user);
1000
1001               log_main($user->sess, "chatt_send post table update");
1002             }
1003           }
1004           else if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
1005             $table = &$this->table[$user->table];
1006             
1007             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1008             $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1009                 xcape($this->user[$table->player[($user_cur->table_pos)%PLAYERS_N]]->name),
1010                 xcape($this->user[$table->player[($user_cur->table_pos+1)%PLAYERS_N]]->name),
1011                 xcape($this->user[$table->player[($user_cur->table_pos+2)%PLAYERS_N]]->name),
1012                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3)%PLAYERS_N]]->name)),
1013                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4)%PLAYERS_N]]->name)));
1014             if ($user_cur == $user)
1015               $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>";', 
1016                                                                    xcape($user->name,ENT_COMPAT,"UTF-8"));
1017             $user_cur->step_inc();
1018           }
1019         }
1020       }
1021     }
1022     else {
1023       for ($i = 0 ; $i < ($user->stat == 'room' ? MAX_PLAYERS : PLAYERS_N) ; $i++) {
1024         if ($user->stat == 'room') {
1025           $user_cur = &$this->user[$i];
1026           if ($user_cur->sess == '' || $user_cur->stat != 'room')
1027             continue;
1028         }
1029         else {
1030           $user_cur = &$this->user[$table->player[$i]];
1031         }
1032         
1033         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1034         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s","%s");',
1035                                                              $dt.xcape($user->name), xcape($user_mesg));
1036         $user_cur->step_inc();
1037       }
1038       log_legal($timecur, $user->sess, $user->name, 
1039                 ($user->stat == 'room' ? 'room' : 'table '.$user->table),$user_mesg);
1040     }
1041   }
1042
1043   function &get_user($sess, &$idx)
1044   {
1045     GLOBAL $PHP_SELF, $G_false;
1046
1047     if (validate_sess($sess)) {
1048       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1049         if (strcmp($sess, $this->user[$i]->sess) == 0) {
1050           // find it
1051           $idx = $i;
1052           $ret = &$this->user[$i];
1053           return ($ret);
1054         }
1055       }
1056       log_main($sess, sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
1057       // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
1058       // log_main($sess, sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
1059     }
1060     else {
1061       log_main($sess, sprintf("get_user: Wrong strlen [%s]",$sess));
1062     }
1063
1064     return ($G_false);
1065   }
1066
1067   /*
1068    * function &add_user(&$room, &$sess, &$idx, $name, $ip)
1069    *
1070    * RETURN VALUE:
1071    *   if ($idx != -1 && ret == FALSE)  =>  duplicated nick
1072    *   if ($idx == -2 && ret == FALSE)  =>  invalid name
1073    *   if ($idx == -1 && ret == FALSE)  =>  no space left
1074    *   if (ret == TRUE)                 =>  SUCCESS
1075    */
1076   function &add_user(&$sess, &$idx, $name, $ip)
1077   {
1078     GLOBAL $G_false;
1079
1080     $idx = -1;
1081     $idfree = -1;
1082     
1083     if (($name_new = validate_name($name)) == FALSE) {
1084       $idx = -2;
1085       return ($G_false);
1086     }
1087
1088     log_auth("XXX", sprintf("ARRIVA: [%s]", $sess));
1089     if (validate_sess($sess) == FALSE) 
1090       $sess = "";
1091
1092     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1093       /* free user ? */
1094       if (strcmp($sess, $this->user[$i]->sess) == 0) {
1095         if ($idx == -1)
1096           $idx = $i;
1097       }
1098       if ($idfree == -1 && strcmp("", $this->user[$i]->sess) == 0) {
1099         $idfree = $i;
1100       }
1101       if (strcmp($this->user[$i]->name, $name_new) == 0) {
1102         $idx = $i;
1103         break;
1104       }
1105     }
1106     if ($idx == -1)
1107       $idx = $idfree;
1108
1109     log_auth("XXX", sprintf("TROVATO A QUESTO PUNTO [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1110
1111     if ($idx != -1 && $i == MAX_PLAYERS) {
1112       /* SUCCESS */
1113       $curtime = time();
1114       if ($sess == "") {
1115         $this->user[$idx]->sess = uniqid("");
1116         $sess = $this->user[$idx]->sess;
1117         
1118       }
1119       else {
1120         $this->user[$idx]->sess = $sess;
1121       }
1122       $this->user[$idx]->name = $name_new;
1123       $this->user[$idx]->stat_set("room");
1124       // MOP $this->user[$idx]->step_set(0);
1125       $this->user[$idx]->subst = "standup";
1126       $this->user[$idx]->lacc =   $curtime;
1127       $this->user[$idx]->laccwr = $curtime;
1128       $this->user[$idx]->bantime = 0;
1129       $this->user[$idx]->ip = $ip;
1130       log_main("XXX", sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name_new));
1131       
1132       return ($this->user[$idx]);
1133     }
1134
1135     return ($G_false);
1136   }
1137   
1138   function standup_update(&$user)
1139   {
1140     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
1141       $user_cur = &$this->user[$i];
1142       if ($user_cur->sess == '')
1143         continue;
1144
1145       log_main("STANDUP START", $user_cur->stat);
1146       
1147       if ($user_cur->stat == 'room') {
1148         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".standup_content($this, $user_cur);
1149         if ($user_cur == $user)
1150           $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
1151         
1152         log_main("FROM STANDUP", "NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
1153         
1154         $user_cur->step_inc();
1155       }
1156     }
1157   }
1158
1159   // Static functions
1160   function &init_data()
1161   {
1162     $room =& new Room();
1163     
1164     return $room;
1165   }
1166   
1167
1168   function &load_data() 
1169   {
1170     GLOBAL $G_false, $sess;
1171     
1172     if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1173       echo "FTOK FAILED";
1174       exit;
1175     }
1176     
1177     if ($shm = shm_attach($tok, SHM_DIMS)) {
1178       $room = @shm_get_var($shm, $tok);
1179       
1180       log_only($sess, "bri ==  ".($room == FALSE ?   "FALSE" : "TRUE")."  bri ===  ".($room === FALSE ? "FALSE" : "TRUE")."  bri isset ".(isset($room) ?   "TRUE" : "FALSE"));
1181       if (isset($room)) 
1182         log_only($sess, "bri count ".count($room));
1183       
1184       if ($room == FALSE) {
1185         log_only($sess, "INIT MAIN DATA");
1186         
1187         $room =& Room::init_data();
1188         if (shm_put_var($shm, $tok, $room) == FALSE) {
1189           log_only($sess, "PUT_VAR FALLITA ".strlen(serialize($room)));
1190           log_only($sess, serialize($room));
1191         }
1192       }
1193       
1194       shm_detach($shm);
1195       
1196       $ret = &$room;
1197       return ($ret);
1198     }
1199     
1200     return ($G_false);
1201   }
1202   
1203
1204   function save_data(&$room) 
1205   {
1206     GLOBAL $sess;
1207     
1208     $ret =   FALSE;
1209     $shm =   FALSE;
1210     $isacq = FALSE;
1211     
1212     // var_dump($room);
1213     
1214     if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
1215       return (FALSE);
1216     
1217     do {
1218       $isacq = TRUE;
1219       
1220       if (($shm = shm_attach($tok, SHM_DIMS)) == FALSE)
1221         break;
1222       
1223       // log_only($sess, "PUT_VAR DI ".strlen(serialize($room)));
1224       if (shm_put_var($shm, $tok, $room) == FALSE) {
1225         log_only($sess, "PUT_VAR FALLITA ".strlen(serialize($room)));
1226         log_only($sess, serialize($room));
1227         break;
1228       }
1229       // log_main("XXX", "QUI CI ARRIVA [".$room->user[0]->name."]");
1230       $ret = TRUE;
1231     } while (0);
1232     
1233     if ($shm)
1234       shm_detach($shm);
1235     
1236     return ($ret);
1237   }
1238
1239   function lock_data()
1240   {
1241     GLOBAL $sess; 
1242     
1243     //  echo "LOCK: ".FTOK_PATH."/main";
1244     //  exit;
1245     if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
1246       echo "FTOK FAILED";
1247       exit;
1248     }
1249     // echo "FTOK ".$tok."<br>";
1250     if (($res = sem_get($tok)) == FALSE) {
1251       echo "SEM_GET FAILED";
1252       exit;
1253     }
1254     if (sem_acquire($res)) {   
1255       log_only($sess, "LOCK");
1256       return ($res);
1257     }
1258     else
1259       return (FALSE);
1260   }
1261   
1262   function unlock_data($res)
1263   {
1264     GLOBAL $sess; 
1265     
1266     log_only($sess, "UNLOCK");
1267
1268     return (sem_release($res));
1269   }
1270 } // end class Room
1271
1272 function make_seed()
1273 {
1274   list($usec, $sec) = explode(' ', microtime());
1275   return (float) $sec + ((float) $usec * 100000);
1276 }
1277
1278 function log_only2($sess, $log) {
1279   if (BRISK_DEBUG != TRUE)
1280     return;
1281   
1282
1283   if (($fp = @fopen("/tmp/brisk_only2.log", 'a')) != FALSE) {
1284     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1285     fclose($fp);
1286   }
1287 }
1288
1289 function log_only($sess, $log) {
1290   if (BRISK_DEBUG != TRUE)
1291     return;
1292   
1293
1294   if (($fp = @fopen("/tmp/brisk_only.log", 'a')) != FALSE) {
1295     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1296     fclose($fp);
1297   }
1298 }
1299
1300 function log_main($sess, $log) {
1301   if (BRISK_DEBUG != TRUE)
1302     return;
1303
1304   if (($fp = @fopen("/tmp/brisk_main.log", 'a')) != FALSE) {
1305     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1306     fclose($fp);
1307   }
1308 }
1309
1310 function log_rd($sess, $log) {
1311   if (BRISK_DEBUG != TRUE)
1312     return;
1313
1314   if (($fp = @fopen("/tmp/brisk_rd.log", 'a')) != FALSE) {
1315     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1316     fclose($fp);
1317   }
1318 }
1319
1320 function log_rd2($sess, $log) {
1321   if (BRISK_DEBUG != TRUE)
1322     return;
1323
1324   if (($fp = @fopen("/tmp/brisk_rd2.log", 'a')) != FALSE) {
1325     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1326     fclose($fp);
1327   }
1328 }
1329
1330 function log_send($sess, $log) {
1331   if (BRISK_DEBUG != TRUE)
1332     return;
1333
1334   if (($fp = @fopen("/tmp/brisk_send.log", 'a')) != FALSE) {
1335     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1336     fclose($fp);
1337   }
1338 }
1339
1340 function log_auth($sess, $log) {
1341   if (BRISK_DEBUG != TRUE)
1342     return;
1343
1344   if (($fp = @fopen("/tmp/brisk_auth.log", 'a')) != FALSE) {
1345     fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
1346     fclose($fp);
1347   }
1348 }
1349
1350 function log_lock($sess, $log) {
1351   if (BRISK_DEBUG != TRUE)
1352     return;
1353
1354   if (($fp = @fopen("/tmp/brisk_lock.log", 'a')) != FALSE) {
1355     fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
1356     fclose($fp);
1357   }
1358 }
1359
1360 function log_wr($sess, $log) {
1361   if (BRISK_DEBUG != TRUE)
1362     return;
1363
1364   if (($fp = @fopen("/tmp/brisk_wr.log", 'a')) != FALSE) {
1365     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1366     fclose($fp);
1367   }
1368 }
1369
1370 function log_load($sess, $log) {
1371   if (BRISK_DEBUG != TRUE)
1372     return;
1373
1374   if (($fp = @fopen("/tmp/brisk_load.log", 'a')) != FALSE) {
1375     fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
1376     fclose($fp);
1377   }
1378 }
1379
1380 function log_legal($timecur, $sess, $name, $where, $mesg) 
1381 {
1382   GLOBAL $_SERVER;
1383
1384   if (($fp = @fopen(LEGAL_PATH, 'a')) != FALSE) {
1385     /* Unix time | session | nickname | IP | where was | mesg */
1386     fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|\n", $timecur, $sess, $name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
1387     fclose($fp);
1388   }
1389 }
1390
1391
1392
1393
1394 function lock_banlist()
1395 {
1396   if (($tok = ftok(FTOK_PATH."/main", "L")) == -1) {
1397     echo "FTOK FAILED";
1398     exit;
1399   }
1400   if (($res = sem_get($tok)) == FALSE) {
1401     echo "SEM_GET FAILED";
1402     exit;
1403   }
1404   if (sem_acquire($res)) 
1405     return ($res);
1406   else
1407     return (FALSE);
1408 }
1409
1410 function unlock_banlist($res)
1411 {
1412   return (sem_release($res));
1413 }
1414
1415 function table_act_content($isstanding, $sitted, $table, $cur_table)
1416 {
1417   $ret = "";
1418
1419   if ($isstanding) {
1420     if ($sitted < PLAYERS_N) {
1421       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
1422     }
1423   }
1424   else {
1425     if ($table == $cur_table)
1426       $ret = sprintf('<input type=\\"button\\" class=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
1427     else
1428       $ret = "";
1429   }
1430   return ($ret);
1431 }
1432
1433 function table_content($room, $user, $table_idx)
1434 {
1435   $content = "";
1436   $ret = "";
1437   // TODO
1438   //
1439   //   Si possono usare i dati nella classe table
1440   //
1441
1442   $sess = $user->sess;
1443   $table = &$room->table[$table_idx];
1444
1445   if ($user->stat != 'room')
1446     return;
1447
1448   for ($i = 0 ; $i < $table->player_n ; $i++) {
1449     $user_cur = &$room->user[$table->player[$i]];
1450
1451     if ($user_cur == $user) 
1452         { $hilion = "<b>"; $hilioff = "</b>"; }
1453       else
1454         { $hilion = ""; $hilioff = ""; }
1455
1456     log_main($user_cur->name, sprintf("IN TABLE [%d]", $table_idx));
1457     
1458     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
1459   }
1460   /*
1461   for ( ; $i < PLAYERS_N ; $i++)
1462     $content .= "<br>";
1463   */
1464
1465   $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
1466   
1467   return ($ret);
1468 }
1469
1470 function standup_content(&$room, $user)
1471 {
1472   $ret = "";
1473   $content = "";
1474
1475   if ($user->stat != 'room')
1476     return;
1477
1478   for ($e = 0 , $ct = 0 ; $ct < 4 && $e < MAX_PLAYERS ; $e++) {
1479     if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
1480       continue;
1481     $ct++;
1482   }
1483
1484   $content .= sprintf('<table cols=\\"%d\\" class=\\"table_standup\\">', $ct);
1485
1486   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
1487     if ($room->user[$e]->sess == "" || $room->user[$e]->stat != "room" || $room->user[$e]->name == "")
1488       continue;
1489
1490
1491     if ($room->user[$e]->subst == "standup") {
1492       if (($ct % 4) == 0) {
1493         $content .= '<tr>';
1494       }
1495       if ($room->user[$e] == $user) 
1496         { $hilion = "<b>"; $hilioff = "</b>"; }
1497       else
1498         { $hilion = ""; $hilioff = ""; }
1499
1500       $content .= sprintf('<td class=\\"room_standup\\">%s%s%s</td>',$hilion, xcape($room->user[$e]->name), $hilioff);
1501       if (($ct % 4) == 3) {
1502         $content .= '</tr>';
1503       }
1504       $ct++;
1505     }
1506   }
1507   $content .= '</table>';
1508         
1509   $content2 = '<input class=\\"button\\" name=\\"logout\\" value=\\"Esco.\\" onclick=\\"window.onunload = null; act_logout();\\" type=\\"button\\">';
1510   $ret .= sprintf('$("standup").innerHTML = "%s";  $("esco").innerHTML = "%s";', 
1511                   $content, $content2);
1512
1513   return ($ret);
1514 }
1515
1516
1517 function show_notify($text, $tout, $butt, $w, $h)
1518 {
1519   log_main("SHOW_NOTIFY", $text);
1520   return sprintf('var noti = new notify(gst,"%s",%d,"%s",%d,%d);', $text, $tout, $butt, $w, $h);
1521 }
1522
1523 function briscola_show($room, $table, $user)
1524 {
1525   $ptnadd = "";
1526   $ret = "";
1527
1528   if ($table->asta_card == 9) 
1529     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
1530   
1531   /* text of caller cell */
1532   if ($user->table_pos == $table->asta_win) 
1533     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
1534   else 
1535     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
1536                     xcape($room->user[$table->player[$table->asta_win]]->name), $ptnadd);
1537
1538   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1539                   $table->asta_win);
1540   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1541   $ret .= sprintf('$("caller").style.visibility = "visible";');
1542   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1543   $ret .= sprintf('$("astalascio").style.visibility = "";');
1544   $ret .= sprintf('$("asta").style.visibility = "hidden";');
1545   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1546   
1547   return ($ret);
1548 }
1549
1550
1551 function game_result($asta_pnt, $pnt)
1552 {
1553   if ($asta_pnt == 61) {
1554     if ($pnt > 60)
1555       return (1);
1556     else if ($pnt == 60)
1557       return (0);
1558     else
1559       return (-1);
1560   }
1561   else {
1562     if ($pnt >= $asta_pnt)
1563       return (1);
1564     else
1565       return (-1);
1566   }
1567 }
1568
1569 function multoval($mult)
1570 {
1571   if ($mult == 2)
1572     return ("doppio");
1573   else if ($mult == 4)
1574     return ("quadruplo");
1575   else
1576     return (sprintf("%d-plo", $mult));
1577 }
1578
1579 function show_table_info(&$room, &$table, $table_pos)
1580 {
1581   $ret = "";
1582   $user = &$room->user[$table->player[$table_pos]];
1583
1584   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1585   $noty = sprintf('<table class=\"points\"><tr><th></th>');
1586   
1587   // Names.
1588   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1589     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($room->user[$table->player[$i]]->name));
1590   $noty .= sprintf("</tr>");
1591
1592   // Points.
1593   log_main("show_table_info", "pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1594
1595   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1596     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1597     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1598       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1599     $noty .= "</tr>";
1600   }
1601
1602   // Total points.
1603   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1604   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
1605     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1606   $noty .= "</tr></table>";
1607
1608   if ($table->old_reason != "") {
1609     $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1610   }
1611
1612   if ($table->old_win != -1) {
1613     $win = $table->player[$table->old_win];
1614     $fri = $table->player[$table->old_friend];
1615
1616     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1617
1618     if ($win != $fri) {
1619       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
1620                        xcape($room->user[$win]->name),
1621                        xcape($room->user[$fri]->name));
1622       if ($table->old_pnt == 120) {
1623         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
1624       }
1625       else {
1626         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
1627                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1628                           'pi&ugrave; di 60'), $table->old_pnt,
1629                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1630       }
1631     }
1632     else {
1633       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
1634                        xcape($room->user[$win]->name));
1635       if ($table->old_pnt == 120) {
1636         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
1637       }
1638       else {
1639         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
1640                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
1641                           'pi&ugrave; di 60'), $table->old_pnt,
1642                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
1643       }
1644     }
1645   }
1646   if ($table->mazzo == $table_pos) 
1647     $noty .= "Fai <b>tu</b> il mazzo,";
1648   else {
1649     $unam = xcape($room->user[$table->player[$table->mazzo]]->name);
1650     $noty .= "Il mazzo a <b>$unam</b>,";
1651   }
1652
1653   if ($user->subst == 'asta') {
1654     if ($table->asta_win == -1)  // auction case
1655       $curplayer = $table->gstart % PLAYERS_N;
1656     else 
1657       $curplayer = $table->asta_win;
1658   }
1659   else if ($user->subst == 'game') {
1660     $curplayer = ($table->gstart + $table->turn) % PLAYERS_N;
1661   }
1662
1663
1664   if ($curplayer == $table_pos) {
1665     $noty .= " tocca a <b>te</b> giocare.";
1666   }
1667   else {
1668     $unam = xcape($room->user[$table->player[$curplayer]]->name);
1669     $noty .= " tocca a <b>$unam</b> giocare.";
1670   }
1671
1672   if ($table->mult > 1) {
1673     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
1674   }
1675   $noty .= "<hr><br>";
1676
1677   $ret .= show_notify($noty, 3000, "torna alla partita", 500, 400);
1678   
1679   return ($ret);
1680 }
1681
1682 function root_wellcome($user)
1683 {
1684   GLOBAL $root_wellarr;
1685   $ret = "";
1686
1687   for ($i = 0 ; $i < count($root_wellarr) ; $i++)
1688     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $root_wellarr[$i]));
1689
1690   return ($ret);
1691 }
1692
1693 function table_wellcome($user)
1694 {
1695   GLOBAL $table_wellarr;
1696   $ret = "";
1697
1698   for ($i = 0 ; $i < count($table_wellarr) ; $i++)
1699     $ret .= sprintf('chatt_sub("ChanServ: ","%s");', str_replace('"', '\"', $table_wellarr[$i]));
1700
1701   return ($ret);
1702 }
1703
1704 function show_room(&$room, &$user)
1705 {
1706   $ret = sprintf('gst.st = %d;',  $user->step);
1707   $ret .= sprintf('stat = "%s";',  $user->stat);
1708
1709   $ret .= root_wellcome($user);
1710   $ret .= sprintf('subst = "%s";', $user->subst);
1711   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1712   for ($i = 0 ; $i < TABLES_N ; $i++) {
1713     $ret .= table_content($room, $user, $i);
1714     $act_content = table_act_content(($user->subst == 'standup'), 
1715                                      $room->table[$i]->player_n, $i, $user->table);
1716     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
1717   }
1718   $ret .= standup_content($room, $user);
1719   
1720   return ($ret);
1721 }
1722
1723
1724
1725 /* show table 
1726 is_transition (is from room to table ?)
1727 is_again      (is another game)
1728
1729 Examples                    of $is_transition, $is_again:
1730   from reload of the page:              FALSE, FALSE
1731   from sitdown in room:                  TRUE, FALSE
1732   from table: asta cmd e tutti passano:  TRUE, TRUE
1733   from table: fine partita:              TRUE, TRUE
1734  */
1735 function show_table(&$room, &$user, $sendstep, $is_transition, $is_again)
1736 {
1737   $table_idx = $user->table;
1738   $table = &$room->table[$table_idx];
1739   $table_pos = $user->table_pos;
1740
1741   $ret = "table_init();";
1742   $ret .= $table->exitlock_show(&$room->user, $table_pos);
1743   if (!$is_again) {
1744     /* GENERAL STATUS */
1745     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1746                      $sendstep, $user->stat, $user->subst, $table_pos);
1747     /* BACKGROUND */
1748     $ret .= "background_set();";
1749     
1750     /* USERS INFO */
1751     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1752     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1753                     xcape($room->user[$table->player[($table_pos)%PLAYERS_N]]->name),
1754                     xcape($room->user[$table->player[($table_pos+1)%PLAYERS_N]]->name),
1755                     xcape($room->user[$table->player[($table_pos+2)%PLAYERS_N]]->name),
1756                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+3)%PLAYERS_N]]->name)),
1757                     (PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+4)%PLAYERS_N]]->name)));
1758   }
1759   /* NOTIFY FOR THE CARD MAKER */
1760   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1761     $ret .= show_table_info(&$room, &$table, $table_pos);
1762   }
1763   if (!$is_again) 
1764     $ret .= table_wellcome($user);
1765
1766   if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1767     $ret .= playsound("cow.mp3");
1768   }
1769
1770
1771   /* CARDS */
1772   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1773     $ret .= "|";
1774     
1775     for ($i = 0 ; $i < 8 ; $i++) {
1776       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
1777         $ct = 0;
1778         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1779           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
1780             $ct++;
1781             if ($ct == $i+1)
1782               break;
1783           }
1784         }
1785         log_rd($user->sess, "O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1786         
1787         $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
1788                          $i, ((($e + PLAYERS_N - $table_pos + $table->gstart) % PLAYERS_N) == 0 ?
1789                               $table->card[$o]->value : -1), 
1790                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1791       }
1792     }    
1793   }
1794   else {
1795     $taked  = array(0,0,0,0,0);
1796     $inhand = array(0,0,0,0,0);
1797     $ontabl  = array(-1,-1,-1,-1,-1);
1798     $cards  = array();
1799
1800     for ($i = 0 ; $i < 40 ; $i++) {
1801       if ($table->card[$i]->stat == 'hand') {
1802         if ($table->card[$i]->owner == $table_pos) {
1803           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1804         }
1805         $inhand[$table->card[$i]->owner]++;
1806       }
1807       else if ($table->card[$i]->stat == 'take') {
1808         log_main("Card taked:", $table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1809         $taked[$table->card[$i]->owner]++;
1810       }
1811       else if ($table->card[$i]->stat == 'table') {
1812         $ontabl[$table->card[$i]->owner] = $i;
1813       }
1814     }
1815     $logg = "\n";
1816     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1817       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1818     }
1819     log_main("Stat table:", $logg);
1820
1821     /* Set ours cards. */
1822     $oursarg = "";
1823     for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
1824       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1825     for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
1826       $oursarg .= ($i == 0 ? "" : ", ")."-1";
1827     $ret .= sprintf('card_setours(%s);', $oursarg);
1828
1829     /* Dispose all cards */
1830     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1831       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1832       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1833                       $inhand[$i], $taked[$i]);
1834
1835       if ($ontabl[$i] != -1) {
1836         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1837                         $table->card[$ontabl[$i]]->value, 
1838                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1839       }
1840     }
1841   }
1842
1843   /* Show auction */
1844   if ($user->subst == 'asta') {
1845
1846     /* show users auction status */
1847     $showst = "";
1848     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1849       $user_cur = &$room->user[$table->player[$i]];
1850       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1851                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1852     }
1853     if (PLAYERS_N == 3)
1854         $showst .= ",-2,-2";
1855     $ret .= sprintf('show_astat(%s);', $showst);
1856
1857     if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
1858       /* show card chooser */
1859       $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
1860                       $table->asta_card);
1861     }
1862     else {
1863       /* show auction */
1864       if ($table_pos == ($table->gstart % PLAYERS_N) &&
1865           $table->asta_win == -1) 
1866         $ret .= sprintf('dispose_asta(%d,%d, %s);', 
1867                         $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
1868       else
1869         $ret .= sprintf('dispose_asta(%d,%d, %s);',
1870                         $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
1871     }
1872
1873     /* Remark */
1874     if ($table->asta_win == -1) { // auction case
1875       if ($table_pos == ($table->gstart % PLAYERS_N)) 
1876         $ret .= "remark_on();";
1877       else
1878         $ret .= "remark_off();";
1879     }
1880     else { // chooseed case
1881       if ($table_pos == $table->asta_win) 
1882         $ret .= "remark_on();";
1883       else
1884         $ret .= "remark_off();";
1885     }
1886   }
1887   else if ($user->subst == 'game') {
1888     /* HIGHLIGHT */
1889     if (($table->gstart + $table->turn) % PLAYERS_N == $table_pos) 
1890       $ret .= "is_my_time = true; remark_on();";
1891     else
1892       $ret .= "remark_off();";
1893     
1894     /* WHO CALL AND WATH */
1895     $ret .= briscola_show($room, $table, $user);
1896     
1897   }
1898   return ($ret);
1899 } // end function show_table(...
1900
1901 function calculate_winner(&$table)
1902 {
1903   $briontab = FALSE;
1904   $ontab = array();
1905   $ontid = array();
1906   $cur_win  =  -1;
1907   $cur_val  = 100;
1908   $cur_seed = $table->briscola - ($table->briscola % 10);
1909
1910   for ($i = 0 ; $i < 40 ; $i++) {
1911     if ($table->card[$i]->stat != "table")
1912       continue;
1913
1914     log_wr($sess, sprintf("Card On table: [%d]", $i));
1915
1916     $v = $table->card[$i]->value; 
1917     $ontab[$table->card[$i]->owner] = $v;
1918     $ontid[$table->card[$i]->owner] = $i;
1919     /* se briscola setto il flag */
1920     if (($v - ($v % 10)) == $cur_seed)
1921       $briontab = TRUE;
1922   }
1923
1924   if ($briontab == FALSE) {
1925     $cur_win  = $table->gstart;
1926     $cur_val  = $ontab[$cur_win];
1927     $cur_seed = $cur_val - ($cur_val % 10);
1928   }
1929
1930   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1931     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1932       if ($ontab[$i] < $cur_val) {
1933         $cur_val = $ontab[$i];
1934         $cur_win = $i;
1935       }
1936     }
1937   }
1938
1939   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1940     $table->card[$ontid[$i]]->owner = $cur_win;
1941     $table->card[$ontid[$i]]->stat =  "take"; // Card stat
1942   }
1943   return ($cur_win);
1944 }
1945
1946 function calculate_points(&$table)
1947 {
1948   GLOBAL $G_all_points; 
1949
1950   $pro = 0;
1951
1952   if ($table->asta_pnt == 60)
1953     $table->asta_pnt = 61;
1954
1955   $table->old_reason = "";
1956   $table->old_win = $table->asta_win;
1957   $table->old_friend = $table->friend;
1958   $table->old_asta_pnt = $table->asta_pnt;
1959
1960   for ($i = 0 ; $i < 40 ; $i++) {
1961     $ctt = $table->card[$i]->value % 10;
1962     $own = $table->card[$i]->owner;
1963     if ($own == $table->asta_win || $own == $table->friend) 
1964       $pro += $G_all_points[$ctt];
1965   }
1966
1967   log_wr("XXX", sprintf("PRO: [%d]", $pro));
1968
1969   
1970   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1971     $table->points[$table->points_n % MAX_POINTS] = array();
1972     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1973       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1974     $table->points_n++;
1975     $table->old_pnt = $pro;
1976     $table->mult *= 2;
1977
1978     return;
1979   }
1980
1981   if ($pro >= $table->asta_pnt) 
1982     $sig = 1;
1983   else
1984     $sig = -1;
1985
1986   $table->points[$table->points_n % MAX_POINTS] = array();
1987   for ($i = 0 ; $i < 5 ; $i++) {
1988     if ($i == $table->asta_win) 
1989       $pt = ($i == $table->friend ? 4 : 2);
1990     else if ($i == $table->friend) 
1991       $pt = 1;
1992     else
1993       $pt = -1;
1994
1995     log_wr("XXX", sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1996
1997     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
1998
1999     log_wr("XXX", sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
2000     
2001     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
2002     $table->total[$i] += $pt;
2003   }
2004   $table->points_n++;
2005   $table->old_pnt = $pro;
2006   $table->mult = 1;
2007 }
2008
2009 function validate_sess($sess) 
2010 {
2011   if (strlen($sess) == SESS_LEN) 
2012     return (TRUE);
2013   else
2014     return (FALSE);
2015 }
2016
2017 function validate_name($name) 
2018 {
2019   $name_new = str_replace(' ', '_', substr(trim($name),0,12));
2020
2021   for ($i = 0 ; $i < strlen($name_new) ; $i++) {
2022     $c = $name_new[$i];
2023     if (($c >= "a" && $c <= "z") || ($c >= "A" && $c <= "Z") || ($c >= "0" && $c <= "9"))
2024       return ($name_new);
2025   }
2026
2027   return (FALSE);
2028 }
2029
2030 function playsound($filename)
2031 {
2032   return (sprintf('playsound("flasou", "%s");', $filename));
2033 }
2034
2035 function secstoword($secs)
2036 {
2037   $mins = floor($secs / 60);
2038   $secs = $secs % 60;
2039   if ($mins > 0) 
2040     $ret = sprintf("%d minut%s%s", $mins, ($mins > 1 ? "i" : "o"), ($secs > 0 ? " e " : ""));
2041   
2042   if ($secs > 0)
2043     $ret .= sprintf("%d second%s", $secs, ($secs > 1 ? "i" : "o"));
2044   
2045   return ($ret);
2046 }
2047
2048 ?>