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