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