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