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