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