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