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