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