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