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