garbage_timeout variable replaces file storaged value
[brisk.git] / web / briskin5 / Obj / briskin5.phh
1 <?php
2 /*
3  *  brisk - briskin5.phh
4  *
5  *  Copyright (C) 2006-2012 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 define('BIN5_PLAYERS_N', 3);
25 define('BIN5_MAX_PLAYERS', BIN5_PLAYERS_N);
26 // define(BIN5_SHM_MIN', (50000 * BIN5_MAX_PLAYERS));
27 define('BIN5_SHM_MIN', 32768);
28 define('BIN5_SHM_MAX', (BIN5_SHM_MIN + 1048576));
29 define('BIN5_SHM_DLT', 32768);
30 define('BIN5_PROXY_PATH', PROXY_PATH."/bin5");
31
32 $mlang_bin5_bin5 = array( 
33                          'info_part' => array( 'it' => '<hr>Nell\'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>',
34                                                'en' => '<hr>In the last hand the declarer was <b>%s</b>, the partner was <b>%s</b>,<br>'),
35                          'info_capp' => array( 'it' => 'hanno fatto <b>cappotto</b> EBBRAVI!.<br>',
36                                                'en' => 'and they made <b>capot</b> WELL DONE!.<br>'),
37                          'info_pnt'  => array( 'it' => 'dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno %s.<br>',
38                                                'en' => 'they had to do <b>%s</b> points and they had made <b>%d</b>: they have %s.<br>'),
39                          'info_alea' => array( 'it' => 'almeno ',
40                                                'en' => 'at least '),
41                          'info_more' => array( 'it' => 'pi&ugrave; di 60',
42                                                'en' => 'over 60'),
43                          'info_win'  => array( 'it' => '<b>vinto</b>',
44                                                'en' => '<b>win</b>'),
45                          'info_peer' => array( 'it' => '<b>pareggiato</b>',
46                                                'en' => '<b>drew</b>'),
47                          'info_lost' => array( 'it' => '<b>perso</b>',
48                                                'en' => '<b>lost</b>'),
49
50                          'info_alon' => array( 'it' => '<hr>Nell\'ultima partita <b>%s</b> si &egrave; chiamato in mano,<br>',
51                                                'en' => '<hr>In the last hand <b>%s</b> play alone against each other,<br>'),
52                          'info_apnt' => array( 'it' => 'doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha %s.<br>',
53                                                'en' => 'he/she had to do <b>%s</b> points and they had made <b>%d</b>: he/she had %s.<br>'),
54                          'info_acap' => array( 'it' => 'ha fatto <b>cappotto</b> EBBRAVO!.<hr>',
55                                                'en' => 'and he/she made <b>capot</b> WELL DONE!.<hr>'),
56                          
57                          'info_omul' => array( 'it' => ' La partita valeva <b>%s</b>.',
58                                                'en' => ' EN: The game was worth <b>%s</b>.' ),
59
60                          'info_yturn'=> array( 'it' => ' tocca a <b>te</b> giocare.',
61                                                'en' => ' it\'s <b>your</b> turn.'),
62                          'info_turn' => array( 'it' => 'tocca a <b>%s</b> giocare.',
63                                                'en' => 'it\'s the <b>%s</b>\'s turn.'),
64                          'info_mult' => array( 'it' => ' La partita vale <b>%s</b>.',
65                                                'en' => ' The game worth <b>%s</b>.' ),
66                          'info_yshuf'=> array( 'it' => 'Fai <b>tu</b> il mazzo, ',
67                                                'en' => 'It\'s <b>your</b> shuffled the cards, '),
68                          'info_shuf' => array( 'it' => 'Il mazzo a <b>%s</b>, ',
69                                                'en' => '<b>%s</b> shuffled the cards, '),
70                          'btn_bkgame'=> array( 'it' => 'torna alla partita',
71                                                'en' => 'back to the game'),
72                          'call_wptn' => array( 'it' => '<br>con %d punti',
73                                                'en' => '<br>with %d points'),
74                          'call_ycall'=> array( 'it' => 'Chiami%s:',
75                                                'en' => 'Call%s:'),
76                          'call_call' => array( 'it' => 'Chiama %s%s:',
77                                                'en' => 'The declarer is %s%s:')
78
79                          
80                           );
81
82 // MLANG
83 $table_wellarr = Array( 'it' => 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.'),
84                         'en' => Array ( 'EN 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.') );
85
86 function multoval($mult)
87 {
88     GLOBAL $G_lang;
89
90     if ($mult == 2)
91         return ($G_lang == 'en' ? 'double' : 'doppio');
92     if ($mult == 3)
93         return ($G_lang == 'en' ? 'triple' : 'triplo');
94     else if ($mult == 4)
95         return ($G_lang == 'en' ? 'quadruple' : 'quadruplo');
96     else
97         return (sprintf(($G_lang == 'en' ? "%d-ple" : "%d-plo"), $mult));
98 }
99
100
101 class Card {
102     var $value; /* 0 - 39 card value */
103     var $stat;  /* 'bunch', 'hand', 'table', 'take' */
104     var $owner; /* (table position 0-4) */
105     // var $pos;   /* Pos in hand. */
106     var $x;     /* When played the X position on the table of the owner. */
107     var $y;     /* When played the Y position on the table of the owner. */
108
109     function Card($value, $stat, $owner)
110     {
111         $this->value = $value;
112         $this->stat  = $stat; // Card stat
113         $this->owner = $owner;
114     }
115
116     function assign($stat,$owner)
117     {
118         $this->stat  = $stat; // Card stat
119         $this->owner = $owner;
120     }
121
122     function setpos($pos)
123     {
124         $this->pos   = $pos;
125     }
126
127     function play($x,$y)
128     {
129         $this->stat = 'table'; // Card stat
130         $this->x = $x;
131         $this->y = $y;
132     }
133
134     function take($newown)
135     {
136         $this->stat = 'take'; // Card stat
137         $this->owner = $newown;
138     }
139 } // end class Card
140
141 class Bin5_table extends Table {
142     var $card;       // il mazzo di carte
143     var $mazzo;      // chi e' di mazzo
144     var $gstart;
145     var $turn;
146
147     var $asta_pla;
148     var $asta_pla_n;
149     var $asta_card;
150     var $asta_pnt;
151   
152     var $mult;
153     var $points;    // points array
154     var $points_n;  // number of row of points
155     var $total;
156
157     var $asta_win;
158     var $briscola;
159     var $friend;
160   
161     var $old_reason;
162     var $old_asta_pnt;
163     var $old_mult;
164     var $old_pnt;
165     var $old_win;
166     var $old_friend;
167
168     function Bin5_table() 
169     {
170     }
171
172
173     /* CREATE() NOT USED
174        function create($idx) 
175        {
176        if (($thiz =& new Bin5_table()) == FALSE)
177        return (FALSE);
178
179        $thiz->create($idx);
180
181        $thiz->card      =   FALSE;
182        $thiz->asta_pla  =   array(); // TRUE: in auction, FALSE: out of the auction
183        $thiz->asta_pla_n=  -1;
184        $thiz->asta_card =  -1;
185        $thiz->asta_pnt  =  -1;
186        $thiz->mult      =   1;
187     
188        $thiz->points    =   array( );
189        $thiz->points_n  =   0;
190        $thiz->total     =   array( 0, 0, 0, 0, 0);
191        $thiz->asta_win  =  -1;
192        $thiz->briscola  =  -1;
193        $thiz->friend    =  -1;
194        $thiz->turn      =   0;
195
196        $thiz->old_reason   = "";
197        $thiz->old_asta_pnt = -1;
198        $thiz->old_mult     = -1;
199        $thiz->old_pnt      = -1;
200        $thiz->old_win      = -1;
201        $thiz->old_friend   = -1;
202
203        return ($thiz);
204        }
205     */
206
207     /* CLONE() NOT USED
208        function myclone(&$from)
209        {
210        if (($thiz =& new Bin5_table()) == FALSE)
211        return (FALSE);
212     
213        parent::copy($from);
214
215        $thiz->card = $from->card;
216        $thiz->mazzo = $from->mazzo; // REVIEW
217        $thiz->gstart = $from->gstart;
218        $thiz->turn = $from->turn;
219
220        $thiz->asta_pla = $from->asta_pla;
221        $thiz->asta_pla_n = $from->asta_pla_n;
222        $thiz->asta_card = $from->asta_card;
223        $thiz->asta_pnt = $from->asta_pnt;
224     
225        $thiz->mult = $from->mult;
226        $thiz->points = $from->points;
227        $thiz->points_n = $from->points_n;
228        $thiz->total = $from->total;
229     
230        $thiz->asta_win = $from->asta_win;
231        $thiz->briscola = $from->briscola;
232        $thiz->friend = $from->friend;
233     
234        $thiz->old_reason = $from->old_reason;
235        $thiz->old_asta_pnt = $from->old_asta_pnt;
236        $thiz->old_mult = $from->mult;
237        $thiz->old_pnt = $from->old_pnt;
238        $thiz->old_win = $from->old_win;
239        $thiz->old_friend = $from->old_friend;
240
241        return ($thiz);
242        }
243     */
244
245     function parentcopy(&$from)
246     {
247         parent::copy($from);
248     }
249
250     function spawn(&$from)
251     {
252         if (($thiz =& new Bin5_table()) == FALSE)
253             return (FALSE);
254     
255         $thiz->parentcopy($from);
256
257         log_main("PLAYER_N - spawn.".$thiz->player_n);
258
259         $thiz->card = array();
260         $thiz->bunch_create();
261         $thiz->mazzo    = rand(0,PLAYERS_N-1);
262         $thiz->points_n = 0;
263         $thiz->mult     = 1;
264         $thiz->old_win    = -1;
265         $thiz->old_reason = "";
266
267         // players are rearranged in an dedicated array
268         $thiz->player = array();
269         for ($i = 0 ; $i < $from->player_n ; $i++)
270             $thiz->player[$i] = $i;
271
272         log_main("TABLE_OLD_WIN - spawn:".$thiz->old_win);
273
274         return ($thiz);
275     }
276
277
278     //   function bunch_create_old() function AND 
279     //   {
280     //     $ret = array();
281     // 
282     //     for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
283     //       // for ($i = 0 ; $i < 40 ; $i++) {
284     //       $ret[$i] =& new Card($i, 'bunch', 'no_owner');
285     //     }
286     // 
287     //     $oret = &$ret;
288     //     return ($oret);
289     //   }
290
291     function bunch_create()
292     {
293         $ret = array();
294       
295         for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
296             $this->card[$i] = new Card($i, 'bunch', 'no_owner');
297         }
298     }
299
300     function bunch_make()
301     {
302         log_main("bunch_make start");
303         $ct = array(0,0,0,0,0);
304     
305         mt_srand(make_seed());
306     
307         for ($i = (BIN5_PLAYERS_N == 5 ? 40 : 24) - 1 ; $i >= 0 ; $i--) 
308             $rest[$i] = $i;
309
310         for ($i = (BIN5_PLAYERS_N == 5 ? 40 : 24) - 1 ; $i >= 0 ; $i--) {
311             $rn = rand(0, $i);
312       
313             if ($rn == 0)
314                 log_main("RND ZERO");
315       
316             $id = $rest[$rn];
317
318             $owner = $i % BIN5_PLAYERS_N;
319             $this->card[$id]->assign('hand', $owner);
320
321             $rest[$rn] = $rest[$i];
322             // $pubbpos[$rn2] = $pubbpos[$i];
323         }
324         log_main("bunch_make end");
325     }
326
327     function init($userarr)
328     {
329         /* MOVED INTO SPAWN
330            $this->mazzo    =  rand(0,PLAYERS_N-1);
331            $this->points_n =  0;
332            $this->mult     =  1;
333            $this->old_win  = -1;
334            $this->old_reason = "";
335         */
336         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
337             $this->total[$i] = 0;
338             $user_cur = $userarr[$this->player[$i]];
339             $user_cur->exitislock = TRUE;
340         }
341
342         log_main("table::init: ci siamo");
343     }
344
345     function game_init($userarr)
346     {
347         log_rd2("GSTART 4");
348
349         $this->gstart = ($this->mazzo+1) % BIN5_PLAYERS_N;
350         $this->bunch_make();
351     
352     
353         $this->asta_pla_n = BIN5_PLAYERS_N;
354         $this->asta_card = -1;
355         $this->asta_pnt  = 60;
356         $this->asta_win  = -1;
357         $this->briscola  = -1;
358         $this->friend    = -1;
359         $this->turn      =  0;
360     
361         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
362             $this->asta_pla[$i] = TRUE;
363             $user_cur = $userarr[$this->player[$i]];
364             $user_cur->subst = 'asta';
365             $user_cur->asta_card = -2;
366             $user_cur->asta_pnt  = -1;
367             $user_cur->handpt = $this->hand_points($i);
368             // SEE function calculate_points(&$table)
369         }
370         log_rd2("GEND 4");
371     }
372
373     function game_next()
374     {
375         $this->mazzo  = ($this->mazzo + 1) % BIN5_PLAYERS_N;
376     }
377
378
379     function hand_points($idx)
380     {
381         GLOBAL $G_all_points; 
382     
383         $tot = 0;
384     
385         for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
386             // for ($i = 0 ; $i < 40 ; $i++) {
387             if ($this->card[$i]->owner != $idx)
388                 continue;
389
390             $ctt = $this->card[$i]->value % 10;
391             $tot += $G_all_points[$ctt];
392         }
393
394         return ($tot);
395     }
396
397
398     function exitlock_show($userarr, $table_pos)
399     {
400         $ct = $this->exitlock_calc($userarr, $table_pos);
401
402         $ret = sprintf('exitlock_show(%d, %s);', $ct, 
403                        ($userarr[$this->player[$table_pos]]->exitislock ? 'true' : 'false'));
404         return ($ret);
405     }
406
407     function exitlock_calc(&$userarr, $table_pos)
408     {
409         $ct = 0;
410
411         for ($i = 0 , $ct = 0 ; $i < PLAYERS_N ; $i++) {        
412             if ($userarr[$this->player[$i]]->exitislock == FALSE)
413                 $ct++;
414         }
415
416         return ($ct);
417     }
418 } // end class Bin5_table
419
420
421
422
423 define('BIN5_USER_FLAG_RING_ENDAUCT', 0x01);
424
425 class Bin5_user extends User {
426     var $asta_card;  // 
427     var $asta_pnt;   //
428     var $handpt;     // Total card points at the beginning of the current hand.
429     var $exitislock; // Player can exit from the table ?
430     var $privflags;  // Flags for briskin5 only 
431
432     const BASE = "../";
433     
434     function User() {
435     }
436     
437     /* CREATE NOT USED
438        function create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
439        if (($thiz =& new User()) == FALSE)
440        return (FALSE);
441      
442        $thiz->asta_card = -2;
443        $thiz->asta_pnt  = -1;
444        $thiz->handpt = -1;
445        $thiz->exitislock = TRUE;
446        $thiz->privflags = 0;
447      
448        return ($thiz);
449        }
450     */
451     
452     function parentcopy(&$from)
453     {
454         parent::copy($from);
455     }
456     
457     function copy(&$from)
458     {
459         $this->parentcopy($from);
460         
461         $this->asta_card  = $from->asta_card;
462         $this->asta_pnt   = $from->asta_pnt;
463         $this->handpt     = $from->handpt;
464         $this->exitislock = $from->exitislock;
465         $this->privflags  = $from->privflags;
466     }
467     
468     /* CLONE NOT USED
469        function myclone(&$from)
470        {
471        if (($thiz =& new User()) == FALSE)
472        return (FALSE);
473      
474        $thiz->copy($from);
475      
476        return ($thiz);
477        } 
478     */
479     
480     function spawn($from, &$bri, $table, $table_pos, $get, $post, $cookie)
481     {
482         if (($thiz = new Bin5_user()) == FALSE)
483             return (FALSE);
484
485         if (($CO_bin5_pref_ring_endauct = gpcs_var("CO_bin5_pref_ring_endauct", $get, $post, $cookie)) === FALSE) {
486             $CO_bin5_pref_ring_endauct = "";
487         }
488
489         $thiz->parentcopy($from);
490         
491         /* NOTE: at this moment idx and table_pos fields have the same value 
492            but diffentent functions, we keep them separated for a while */
493         $thiz->room       = $bri;
494         $thiz->idx        = $table_pos;
495         $thiz->asta_card  = -2;
496         $thiz->asta_pnt   = -1;
497         $thiz->handpt     = -1;
498         $thiz->exitislock = TRUE;
499         
500         log_wr("Bin5 constructor");
501         
502         $this->privflags  = ($CO_bin5_pref_ring_endauct == "true" ? BIN5_USER_FLAG_RING_ENDAUCT : 0) | 0;
503
504         $thiz->table_orig = $table;
505         $thiz->table      = 0;
506         $thiz->table_pos  = $table_pos;
507         
508         $thiz->step_inc();
509
510         return ($thiz);
511     }
512
513     function step_set($step) 
514     {
515         $this->step = $step & 0x7fffffff;
516         
517         return TRUE;
518     }
519     
520     function step_inc($delta = 1) {
521         $this->step += $delta;
522         /* modularization because unpack() not manage unsigned 32bit int correctly */
523         $this->step &= 0x7fffffff;
524         
525         return (TRUE);
526     }
527
528     static function load_step($tab_id, $sess)
529     {
530         $fp = FALSE;
531         do {
532             if (validate_sess($sess) == FALSE)
533                 break;
534             
535             if (file_exists(BIN5_PROXY_PATH."/table".$tab_id) == FALSE)
536                 mkdir(BIN5_PROXY_PATH."/table".$tab_id, 0775, TRUE);
537             if (($fp = @fopen(BIN5_PROXY_PATH."/table".$tab_id."/".$sess.".step", 'rb')) == FALSE)
538                 break;
539             if (($s = fread($fp, 8)) == FALSE)
540                 break;
541             if (mb_strlen($s, "ASCII") != 8)
542                 break;
543             $arr = unpack('Ls/Li', $s);
544             fclose($fp);
545             
546             // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
547             return ($arr);
548         } while (0);
549         
550         if ($fp != FALSE)
551             fclose($fp);
552         
553         log_rd2("STEP_GET [".$sess."]: return false ");
554         
555         return (FALSE);
556     }
557
558     function save_step() 
559     {
560         do {
561             if (validate_sess($this->sess) == FALSE)
562                 break;
563             if (file_exists(BIN5_PROXY_PATH."/table".$this->table_orig) == FALSE)
564                 mkdir(BIN5_PROXY_PATH."/table".$this->table_orig, 0775, TRUE);
565             if (($fp = @fopen(BIN5_PROXY_PATH."/table".$this->table_orig."/".$this->sess.".step", 'w')) == FALSE)
566                 break;
567             fwrite($fp, pack("LL",$this->step, $this->idx));
568             fclose($fp);
569             
570             log_main("step_set [".$this->sess. "] [".$this->step."]"); 
571             
572             return (TRUE);
573         } while (0);
574         
575         return (FALSE);
576     }
577     
578     static function unproxy_step($tab_id, $sess)
579     {
580         log_rd2("UNPROXY: ".BIN5_PROXY_PATH."/table".$tab_id."/".$sess.".step");
581         if (file_exists(BIN5_PROXY_PATH."/table".$tab_id) == FALSE)
582             return;
583
584         @unlink(BIN5_PROXY_PATH."/table".$tab_id."/".$sess.".step");
585     }
586     
587     static function load_data($tab_id, $id, $sess) 
588     {
589         log_load("Bin5_user::load_data: tab_id [".$tab_id."] id [".$id."] sess [".($sess == FALSE ? "FALSE" : $sess)."] ");
590         
591         do {
592             if (($tok = @ftok(FTOK_PATH."/bin5/table".$tab_id."/user".$id, "B")) == -1) {
593                 log_main("ftok failed");
594                 break;
595             }
596             
597             if (($shm_sz = sharedmem_sz($tok)) == -1) {
598                 log_main("shmop_open failed");
599             }
600             
601             if ($shm_sz == -1)
602                 $shm_sz = SHM_DIMS_U_MIN;
603             
604             if ($shm = shm_attach($tok, $shm_sz)) {
605                 if (($user = @shm_get_var($shm, $tok)) == FALSE) {
606                     break;
607                 }
608                 
609                 if ($sess != FALSE && $user->sess != $sess) {
610                     break;
611                 }
612                 log_only("user ==  ".($user == FALSE ?   "FALSE" : "TRUE")."  user ===  ".($user === FALSE ? "FALSE" : "TRUE")."  user isset ".(isset($user) ?   "TRUE" : "FALSE"));
613                 
614                 if ($user == FALSE) {
615                     log_only("INIT MAIN DATA");
616                     
617                     // SHSPLIT FIXME: init_data for User class ??
618                     $user = User::create($id, "", "");
619                     if (@shm_put_var($shm, $tok, $user) == FALSE) {
620                         log_shme("Bin5_user::save_data2");
621
622                         log_only("PUT_VAR FALLITA ".strlen(serialize($user)));
623                         log_only(serialize($user));
624                     }
625                 }
626                 else {
627                     if ($sess != FALSE) {
628                         // This part isn't strictly required but is good to verify
629                         // the coerence of cached and User class saved value of step field.
630                         $old_step = $user->step;
631                         $arr = Bin5_user::load_step($tab_id, $sess);
632                         $user->step = $arr['s'];
633                         if ($old_step != $user->step) {
634                             log_crit("Bin5:: steps are diffetents User->step ".$user->step." Old_step: ".$old_step);
635                         }
636
637                     }
638                 }
639                 
640                 $user->shm_sz = $shm_sz;
641                 
642                 shm_detach($shm);
643             }
644             
645             //  
646             // SHSPLIT: load users from the shared memory
647             //
648             return ($user);
649         } while (0);
650         
651         log_crit("Bin5_user::load_data:ret FALSE");
652         
653         return (FALSE);
654     }
655
656     static function save_data($user, $tab_id, $id) 
657     {
658         GLOBAL $sess;
659       
660         $shm =   FALSE;
661       
662         if (($tok = @ftok(FTOK_PATH."/bin5/table".$tab_id."/user".$id, "B")) == -1) {
663             return (FALSE);
664         }
665         while ($user->shm_sz < SHM_DIMS_U_MAX) {
666             if (($shm = shm_attach($tok, $user->shm_sz)) == FALSE)
667                 break;
668           
669             // log_only("PUT_VAR DI ".strlen(serialize($user)));
670             if (@shm_put_var($shm, $tok, $user) != FALSE) {
671                 shm_detach($shm);
672                 $user->save_step();
673                 log_main("User[".$id."] saved.");
674
675                 log_shme("Bin5_user::save_data");
676
677                 return (TRUE);
678             }
679             if (shm_remove($shm) === FALSE) {
680                 log_only("REMOVE FALLITA");
681                 break;
682             }
683             shm_detach($shm);
684             $user->shm_sz += SHM_DIMS_U_DLT;
685         } 
686       
687         if ($shm)
688             shm_detach($shm);
689       
690         return (FALSE);
691     }
692
693     function destroy_data($tab_id) 
694     {
695         do {
696             if (($tok = @ftok(FTOK_PATH."/bin5/table".$tab_id."/user".$this->table_pos, "B")) == -1) {
697                 log_crit("BIN5 USER DATA REMOVE FAILED 1 [".FTOK_PATH."/bin5/table".$tab_id."/user".$this->table_pos."]");
698                 break;
699             }
700           
701             if (($shm = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
702                 log_crit("BIN5 USER DATA REMOVE FAILED 2");
703                 break;
704             }
705             if (shmop_delete($shm) == 0) {
706                 log_crit("BIN5 USER DATA REMOVE FAILED 3");
707                 break;
708             }
709             $shm = FALSE;
710
711             log_main("BIN5 USER DATA DESTROY SUCCESS");
712           
713             // log_main("QUI CI ARRIVA [".$bri->user[0]->name."]");
714             $ret = TRUE;
715         } while (0);
716       
717         if ($shm)
718             shm_detach($shm);
719       
720         return ($ret);
721     }
722
723 public static function stream_fini($is_unrecoverable)
724 {
725     GLOBAL $G_four_rnd_string;
726
727     printf("xXx user::stream_fini\n");
728
729     // IF IFRAME THEN:
730     $body = "";
731     $body .= sprintf("<html>
732 <head>
733 <script type=\"text/javascript\" src=\"%scommons.js\"></script>
734 <script type=\"text/javascript\" src=\"%sxynt-http-streaming-ifra.js\"></script>
735 <script type=\"text/javascript\">
736 var http_streaming = \"ready\";", self::base_get(), self::base_get());
737     $body .= sprintf("
738 window.onload = function () { if (http_streaming != \"ready\") { http_streaming.reload(); } };
739 </script>
740 </head>
741 <body>");
742     $body .= sprintf("<!-- \n%s -->\n", $G_four_rnd_string);
743     $body .= sprintf("<script id='hs%d' type='text/javascript'><!--
744 push(\"%s\");
745 // -->
746 </script>", 0, escpush(self::blocking_error($is_unrecoverable)) );
747     // ELSE IF XHR THEN:
748     // return (self::blocking_error($is_unrecoverable));
749     return ($body);
750 }
751
752
753     protected function blocking_error($is_unrecoverable)
754     {
755         GLOBAL $is_page_streaming;
756         
757         $is_page_streaming = TRUE;
758         log_crit("BLOCKING_ERROR UNREC: ".($is_unrecoverable ? "TRUE" : "FALSE"));
759         return (sprintf(($is_unrecoverable ? 'hstm.stop(); ' : '').'window.onbeforeunload = null; window.onunload = null; document.location.assign("../index.php");'));
760     }
761     
762     protected function page_sync($sess, $page)
763     {
764         GLOBAL $is_page_streaming;
765         
766         $is_page_streaming = TRUE;
767         log_rd2("PAGE_SYNC");
768         printf("xXx BIN5_USER::PAGE_SYNC\n");
769         return (sprintf('hstm.stop(); window.onbeforeunload = null; window.onunload = null; document.location.assign("%s");', $page));
770     }
771
772     protected function maincheck($cur_stat, $cur_subst, $cur_step, &$new_stat, &$new_subst, &$new_step, $splashdate, $table_idx, $table_token)
773     {
774         GLOBAL $G_lang, $mlang_indrd, $is_page_streaming;
775         GLOBAL $G_with_splash, $G_splash_content, $G_splash_interval, $G_splash_idx;
776         GLOBAL $G_splash_w, $G_splash_h, $G_splash_timeout;
777         $CO_splashdate = "CO_splashdate".$G_splash_idx;
778         $$CO_splashdate = $splashdate;
779         
780         GLOBAL $S_load_stat;
781         
782         log_rd("maincheck begin");
783         
784         $ret = FALSE;
785         $curtime = time();
786         
787       /* Nothing changed, return. */
788       if ($cur_step == $this->step) 
789           return (FALSE);
790       
791       log_rd2("do other cur_stat[".$cur_stat."] user->stat[".$this->stat."] cur_step[".$cur_step."] user_step[".$this->step."]");
792       
793       if ($cur_step == -1) {
794           /*
795            *  if $cur_step == -1 load the current state from the main struct
796            */
797           
798           $S_load_stat['wR_minusone']++;
799           
800           if ($this->the_end == TRUE) { 
801               log_rd2("main_check: the end".var_export(debug_backtrace()));
802               $is_page_streaming = TRUE;
803           }
804           
805           if ($this->trans_step != -1) {
806               log_rd2("TRANS USATO ".$this->trans_step);
807               $cur_step = $this->trans_step;
808               $this->trans_step = -1;
809           }
810           else {
811               log_rd2("TRANS NON ATTIVATO");
812           }
813       }
814       
815       
816       /* this part I suppose is read only on $this->room structure */
817       if ($cur_step == -1) {
818           log_rd2("PRE-NEWSTAT");
819               
820           /***************
821            *             *
822            *    TABLE    *
823            *             *
824            ***************/
825           if ($this->stat == 'table') {
826               log_load("RESYNC");
827               /* NOTE: $this->room is associated with the current $bri object */
828               printf("xXx CLASS NAME [%s]\n", get_class($this->room));
829               $ret = show_table(&$this->room, $this, $this->step, FALSE, FALSE);
830           }
831           log_rd2("NEWSTAT: ".$this->stat);
832
833           $new_stat =  $this->stat;
834           $new_subst = $this->subst;
835           $new_step =  $this->step;
836       } /* if ($cur_step == -1) { */
837       else {
838           /* $sem = Room::lock_data(FALSE); */
839           $S_load_stat['rU_heavy']++;
840           
841           if ($cur_step < $this->step) {
842               do {
843                   if ($cur_step + COMM_N < $this->step) {
844                       if (($cur_stat != $this->stat)) {
845                           $to_stat = $this->stat;
846                           /* Room::unlock_data($sem); */
847                           log_load("RESYNC");
848                           printf("xXx BIN5_USER::MAINCHECK\n");
849                           return ($this->page_sync($this->sess, ($to_stat == "table" ? "index.php" : "../index.php"), $this->table, $this->table_token));
850                       }
851                       log_rd2("lost history, refresh from scratch");
852                       printf("xXx LOST HISTORY!\n");
853                       $new_step = -1;
854                       break;
855                   } 
856                   for ($i = $cur_step ; $i < $this->step ; $i++) {
857                       $ii = $i % COMM_N;
858                       log_rd2("ADDED TO THE STREAM: ".$this->comm[$ii]);
859                       $ret .= $this->comm[$ii];
860                   }
861                   $new_stat =  $this->stat;
862                   $new_subst = $this->subst;
863                   $new_step =  $this->step;
864               } while (0);
865               
866               log_rd2($this->step, 'index_rd.php: after ret set');
867               
868               if ($this->the_end == TRUE) {
869                   log_rd2("LOGOUT BYE BYE!!");
870                   log_auth($this->sess, "Explicit logout.");
871                   
872                   if ($this->the_end == TRUE) {
873                       $this->reset();
874                       
875                       // FIXME !!! 
876                       /* if ($this->subst == 'sitdown') { */
877                       /*     log_load("ROOM WAKEUP"); */
878                       /*     $this->room->room_wakeup($this); */
879                       /* } */
880                       /* else if ($this->subst == 'standup') */
881                       /*     $this->room->room_outstandup($this); */
882                       /* else */
883                       /*     log_rd2("LOGOUT FROM WHAT ???"); */
884                       
885                   } /* if ($this->the_end == TRUE) { ... */
886               } /* if ($this->the_end == TRUE) { ... */
887           } /* if ($cur_step < $this->step) { */
888           
889           /* Room::unlock_data($sem); */
890       }  /* else of if ($cur_step == -1) { */
891       
892     
893       return ($ret);
894   }  //   function maincheck (...
895
896
897
898
899
900
901 } // end class Bin5_user
902
903
904
905 class Bin5 {
906     static $delta_t = array();
907
908     var $user;
909     var $table;
910     var $comm; // commands for many people
911     var $step; // current step of the comm array
912     var $garbage_timeout;
913     var $shm_sz;
914     
915     var $table_idx;
916     var $table_token;
917     
918     var $the_end;
919     var $tok;
920
921     static function page_manager($room, $header_out, $path, $method, $addr, $get, $post, $cookie) 
922     {
923         switch ($path) {
924         case "":
925         case "index.php":
926             ob_start();
927             bin5_index_main($room, $header_out, $addr, $get, $post, $cookie);
928             $content = ob_get_contents();
929             ob_end_clean();
930             
931             force_no_cache($header_out);
932
933             $pgflush = new PageFlush($new_socket, $curtime, 20, $header_out, $content);
934             
935             if ($pgflush->try_flush($curtime) == FALSE) {
936                 // Add $pgflush to the pgflush array
937                 array_push($pages_flush, $pgflush);
938             }
939             break;
940         }
941         return TRUE;
942     }
943
944     function Bin5 ($room, $table_idx, $table_token, $get, $post, $cookie) {
945         $this->user = array();
946         $this->table = array();
947         
948         $this->the_end = FALSE;
949         $this->shm_sz = BIN5_SHM_MIN;
950         if (($this->tok = @ftok(FTOK_PATH."/bin5/table".$table_idx."/table", "B")) == -1) {
951             echo "FTOK FAILED";
952             exit;
953         }
954         
955         $user  = $room->user;
956         $table = $room->table[$table_idx];
957         
958         log_wr("Bin5 constructor");
959         
960         for ($i = 0 ; $i < $table->player_n ; $i++) {
961             $user[$table->player[$i]]->table_token = $table_token;
962             $this->user[$i] = Bin5_user::spawn($user[$table->player[$i]], $this, $table_idx, $i, $get, $post, $cookie);
963         }
964         $this->table[0] = Bin5_table::spawn(&$table);
965         
966         log_main("TABLE_OLD_WIN - Bin5:".$this->table[0]->old_win);
967         
968         $this->table_idx = $table_idx;
969         $this->table_token = $table_token;
970         $this->garbage_timeout = 0;
971         
972         log_wr("Bin5 constructor end");
973     }
974     
975
976     function get_user($sess, &$idx)
977     {
978         GLOBAL $PHP_SELF;
979         
980         if (validate_sess($sess)) {
981             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
982                 if (strcmp($sess, $this->user[$i]->sess) == 0) {
983                     // find it
984                     $idx = $i;
985                     $ret = &$this->user[$i];
986                     return ($ret);
987                 }
988             }
989             log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
990             // for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) 
991             // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
992         }
993         else {
994             log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
995         }
996         
997         return (FALSE);
998     }
999     
1000     
1001     function garbage_manager($force)
1002     {
1003         GLOBAL $G_base;
1004         
1005         /* Garbage collector degli utenti in timeout */
1006         $ismod = FALSE;
1007         $curtime = time();
1008         if ($force || $this->garbage_timeout < $curtime) {
1009             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1010                 $user_cur = $this->user[$i];
1011                 if ($user_cur->sess == "" || 
1012                     ($user_cur->stat == 'table' && ($user_cur->subst == 'shutdowned' || $user_cur->subst == 'shutdowner')))
1013                     continue;
1014                 
1015                 if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) { // Auto logout dell'utente
1016                     log_rd2($user_cur->sess." bin5 AUTO LOGOUT.");
1017                     
1018                     if ($user_cur->stat == 'table') {
1019                         log_auth($user_cur->sess," bin5 Autologout session.");
1020                         
1021                         /* SI DELEGA AL garbage_manager principale LA RIMOZIONE DELL'UTENTE 
1022                            
1023                            $tmp_sess = $user_cur->sess;
1024                            $user_cur->sess = "";
1025                            Bin5_user::step_unproxy($tmp_sess);
1026                            $user_cur->name = "";
1027                            $user_cur->the_end = FALSE;
1028                            
1029                         */
1030                         
1031                         /* se gli altri utenti non erano d'accordo questo utente viene bannato */
1032                         $remcalc = $this->table[0]->exitlock_calc(&$this->user, $user_cur->table_pos);
1033                         if ($remcalc < 3) {
1034                             require_once("${G_base}Obj/hardban.phh");
1035                             Hardbans::add(($user_cur->flags & USER_FLAG_AUTH ? $user_cur->name : FALSE),
1036                                           $user_cur->ip, $user_cur->sess, $user_cur->laccwr + BAN_TIME);
1037                         }
1038                         //      $user->bantime = $user->laccwr + BAN_TIME;
1039                         
1040                         $this->table_wakeup($user_cur);
1041                     }
1042                 }
1043             }
1044             log_rd2($user_cur->sess." GARBAGE UPDATED!");
1045             
1046             $this->garbage_timeout = $curtime + GARBAGE_TIMEOUT;
1047             
1048             $ismod = TRUE;
1049         }
1050         
1051         return ($ismod);
1052     }
1053     
1054     // Bin5::load_data
1055     static function load_data($table_idx, $table_token = "") 
1056     {
1057         $shm = FALSE;
1058         
1059         log_wr("TABLE_FTOK ".FTOK_PATH."/bin5/table".$table_idx."/table");
1060         
1061         do {
1062             if (($tok = @ftok(FTOK_PATH."/bin5/table".$table_idx."/table", "B")) == -1) {
1063                 log_main("ftok failed");
1064                 break;
1065             }
1066             
1067             if (($shm_sz = sharedmem_sz($tok)) == -1) {
1068                 log_main("shmop_open failed");
1069                 break;
1070             }
1071         
1072             if (($shm = shm_attach($tok, $shm_sz)) == FALSE)
1073                 break;
1074
1075             if (($bri = @shm_get_var($shm, $tok)) == FALSE) 
1076                 break;
1077
1078             if ($table_token != "" && $bri->table_token != $table_token) {
1079                 log_wr("bri->table_token: ".$bri->table_token."table_token: ".$table_token);
1080                 break;
1081             }
1082             $bri->tok = $tok;
1083
1084             shm_detach($shm);
1085       
1086             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1087                 if (($bri->user[$i] = Bin5_user::load_data($table_idx, $i, FALSE)) == FALSE) {
1088                     log_crit("Bin5_user::load_data failed");
1089                     break;
1090                 }
1091             }
1092             if ($i < BIN5_MAX_PLAYERS) {
1093                 break;
1094             }
1095       
1096             return ($bri); 
1097         } while (FALSE);
1098
1099         if ($shm != FALSE)
1100             shm_detach($shm);
1101
1102         log_wr("briskin5 load_data failed");
1103     
1104         return (FALSE);
1105     }
1106   
1107
1108
1109     function save_data($bri) 
1110     {
1111         GLOBAL $sess;
1112       
1113         $ret =   FALSE;
1114         $shm =   FALSE;
1115       
1116         log_main("SAVE BRISKIN5 DATA");
1117       
1118         if (!isset($bri->tok))
1119             return (FALSE);
1120       
1121         $user_park = array();
1122         for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1123             $user_park[$i] = $bri->user[$i];
1124             $bri->user[$i] = FALSE;
1125         }
1126       
1127         while ($bri->shm_sz < BIN5_SHM_MAX) {
1128             if (($shm = shm_attach($bri->tok, $bri->shm_sz)) == FALSE)
1129                 break;
1130           
1131             if (@shm_put_var($shm, $bri->tok, $bri) != FALSE) {
1132
1133                 log_shme("Bin5::save_data");
1134
1135                 $ret = TRUE;
1136                 break;
1137             }
1138             if (shm_remove($shm) === FALSE) {
1139                 log_only("REMOVE FALLITA");
1140                 break;
1141             }
1142             shm_detach($shm);
1143             $bri->shm_sz += BIN5_SHM_DLT;
1144         } 
1145       
1146         if ($shm)
1147             shm_detach($shm);
1148       
1149         // SHSPLIT: reattach users to the room class
1150         for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1151             Bin5_user::save_data($user_park[$i], $bri->table_idx, $i);
1152             $bri->user[$i] = $user_park[$i];
1153         }
1154         log_load("FINISH: ".($ret == TRUE ? "TRUE" : "FALSE"));
1155       
1156         return ($ret);
1157     }
1158   
1159
1160
1161     function destroy_data() 
1162     {
1163         GLOBAL $sess;
1164
1165         $ret =   FALSE;
1166         $shm =   FALSE;
1167         log_main("DESTROY BRISKIN5 DATA");
1168     
1169         do {
1170             log_main("DESTROY2 BRISKIN5 DATA [".$this->table_idx."]");
1171             for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1172                 $this->user[$i]->destroy_data($this->table_idx);
1173                 Bin5_user::unproxy_step($this->table_idx, $this->user[$i]->sess);
1174             }
1175             if (($tok = @ftok(FTOK_PATH."/bin5/table".$this->table_idx."/table", "B")) == -1) 
1176                 break;
1177
1178             if (($shm = @shmop_open($tok, 'a', 0, 0)) == FALSE)
1179                 break;
1180       
1181             if (shmop_delete($shm) == 0) {
1182                 log_only("REMOVE FALLITA ");
1183                 break;
1184             }
1185    
1186             $shm = FALSE;
1187             log_main("DESTROY2 BRISKIN5 DATA SUCCESS");
1188       
1189             // log_main("QUI CI ARRIVA [".$bri->user[0]->name."]");
1190             $ret = TRUE;
1191         } while (0);
1192     
1193         if ($shm)
1194             shm_detach($shm);
1195     
1196         return ($ret);
1197     }
1198
1199     static function lock_data($is_exclusive, $table_idx)
1200     {
1201         if (($res = file_lock(FTOK_PATH."/bin5/table".$table_idx."/table", $is_exclusive)) != FALSE) {
1202             self::$delta_t = microtime(TRUE);
1203             log_lock("LOCK   table [".$table_idx."]         [".self::$delta_t[$table_idx]."]");
1204           
1205             return (new Vect(array('res' => $res, 'tab' => $table_idx)));
1206         }
1207       
1208         return (FALSE);
1209     }
1210
1211   
1212     static function unlock_data($res_vect)
1213     {
1214         GLOBAL $sess; 
1215
1216         $res = $res_vect->getbyid('res');
1217         $tab = $res_vect->getbyid('tab');
1218
1219         log_lock("UNLOCK table [".$tab."]         [".(microtime(TRUE) - (self::$delta_t[$tab]))."]");
1220
1221         file_unlock($res);
1222     }
1223
1224
1225     function chatt_send($user, $mesg)
1226     {
1227         GLOBAL $mlang_brisk, $G_lang;
1228
1229         if ($user->stat == 'table') {
1230             $table = &$this->table[$user->table];
1231         }
1232     
1233         $user_mesg = substr($mesg,6);
1234     
1235         $curtime = time();
1236     
1237         $dt = date("H:i ", $curtime);
1238         if (strncmp($user_mesg, "/nick ", 6) == 0) {
1239             log_main($user->sess." chatt_send BEGIN");
1240
1241             if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
1242                 $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1243                 $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['nickmust'][$G_lang]);
1244                 $user->step_inc();
1245
1246                 return;
1247             }
1248             $user_mesg = "COMMAND ".$user_mesg;
1249             // Search dup name
1250             // change
1251             // update local graph
1252             // update remote graphs
1253             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1254                 $user_cur = $this->user[$i];
1255                 //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1256                 if ($user_cur->sess == '')
1257                     continue;
1258                 if (strcasecmp($user_cur->name, $name_new) == 0) {
1259                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1260
1261                     $premsg = sprintf($mlang_brisk['nickdupl'][$G_lang], xcape($name_new));
1262                     $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, $premsg);
1263                     $user->step_inc();
1264                     break;
1265                 }
1266             }
1267             if ($i == BIN5_MAX_PLAYERS) {
1268                 if ($user->flags & USER_FLAG_AUTH && strcasecmp($user->name,$name_new) != 0) {
1269                     if ($this->table[$user->table]->auth_only == TRUE) {
1270                         $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1271                         $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"<b>%s</b>");', $dt, NICKSERV, $mlang_brisk['authchan'][$G_lang]);
1272                         $user->step_inc();
1273                         return;
1274                     }
1275                     else {
1276                         $user->flags &= ~USER_FLAG_AUTH; // Remove auth if name changed
1277                     }
1278                 }
1279     
1280                 $user->name = $name_new;
1281
1282                 log_main($user->sess." chatt_send start set");
1283         
1284
1285                 for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1286                     log_main($user->sess." chatt_send set loop");
1287           
1288                     $user_cur = &$this->user[$i];
1289                     if ($user_cur->sess == '')
1290                         continue;
1291           
1292                     if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
1293                         $table = &$this->table[$user->table];
1294             
1295                         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1296                         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('set_names([%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"]); ',
1297                                                                              $this->user[$table->player[($user_cur->table_pos) % BIN5_PLAYERS_N]]->flags,
1298                                                                              xcape($this->user[$table->player[($user_cur->table_pos) % BIN5_PLAYERS_N]]->name),
1299
1300                                                                              $this->user[$table->player[($user_cur->table_pos+1) % BIN5_PLAYERS_N]]->flags,
1301                                                                              xcape($this->user[$table->player[($user_cur->table_pos+1) % BIN5_PLAYERS_N]]->name),
1302
1303                                                                              $this->user[$table->player[($user_cur->table_pos+2) % BIN5_PLAYERS_N]]->flags,
1304                                                                              xcape($this->user[$table->player[($user_cur->table_pos+2) % BIN5_PLAYERS_N]]->name),
1305
1306                                                                              (BIN5_PLAYERS_N == 3 ? 0:  $this->user[$table->player[($user_cur->table_pos+3) % BIN5_PLAYERS_N]]->flags),
1307                                                                              (BIN5_PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3) % BIN5_PLAYERS_N]]->name)),
1308
1309                                                                              (BIN5_PLAYERS_N == 3 ? 0:  $this->user[$table->player[($user_cur->table_pos+4) % BIN5_PLAYERS_N]]->flags),
1310                                                                              (BIN5_PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4) % BIN5_PLAYERS_N]]->name)));
1311                         if ($user_cur == $user) {
1312                             $user_cur->comm[$user_cur->step % COMM_N] .= $user_cur->myname_innerHTML();
1313                         }
1314                         $user_cur->step_inc();
1315                     }
1316                 }
1317             }
1318         }
1319         else {
1320             for ($i = 0 ; $i < ($user->stat == 'room' ? BIN5_MAX_PLAYERS : BIN5_PLAYERS_N) ; $i++) {
1321                 if ($user->stat == 'room') {
1322                     $user_cur = &$this->user[$i];
1323                     if ($user_cur->sess == '' || $user_cur->stat != 'room')
1324                         continue;
1325                 }
1326                 else {
1327                     $user_cur = &$this->user[$table->player[$i]];
1328                 }
1329         
1330                 $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1331                 $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s", [%d, "%s"],"%s");',
1332                                                                      $dt, $user->flags, xcape($user->name), xcape($user_mesg));
1333                 $user_cur->step_inc();
1334             }
1335             log_legal($curtime, 'xxx', $user, ($user->stat == 'room' ? 'room' : 'table '.$user->table_orig),$user_mesg);
1336         }
1337     }
1338
1339     function table_wakeup($user)
1340     {
1341         $table = &$this->table[0];
1342
1343         log_main("BIN5_WAKEUP begin function table  stat: ".$user->stat."  subst: ".$user->subst);
1344
1345         $curtime = time();
1346
1347         log_main("BIN5_WAKEUP from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1348     
1349         for ($i = 0 ; $i < $table->player_n ; $i++) {
1350             $user_cur = &$this->user[$i];
1351             log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1352       
1353             if ($user_cur == $user)
1354                 $user_cur->subst = "shutdowner";
1355             else
1356                 $user_cur->subst = "shutdowned";
1357             $user_cur->laccwr = $curtime;
1358
1359             $ret = "gst.st = ".($user_cur->step+1)."; ";
1360             $ret .= 'gst.st_loc++; hstm.stop(); window.onbeforeunload = null; window.onunload = null; document.location.assign("../index.php");|';
1361
1362             log_wr($user_cur->sess." BIN5_WAKEUP: ".$ret);
1363             $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1364             $user_cur->step_inc();
1365         }
1366
1367         $this->the_end = TRUE;
1368     }
1369   
1370     /*
1371      *  If all players are freezed the room garbage_manager clean up table and users.
1372      */ 
1373     function is_abandoned() 
1374     {
1375         $is_ab = TRUE;
1376         $curtime = time();
1377
1378         $table = &$this->table[0];
1379
1380         for ($i = 0 ; $i < $table->player_n ; $i++) {
1381             $user_cur = &$this->user[$i];
1382
1383             if ($user_cur->lacc + (EXPIRE_TIME_RD * 2) >= $curtime) { 
1384                 $is_ab = FALSE;
1385                 break;
1386             }
1387         }
1388
1389         return ($is_ab);
1390     }
1391
1392     static function request_mgr(&$s_a_p, &$header_out, &$new_socket, $path, $addr, $get, $post, $cookie)
1393     {
1394         printf("NEW_SOCKET (root): %d\n", intval($new_socket));
1395         
1396         if (($table_idx = gpcs_var('table_idx', $get, $post, $cookie)) === FALSE) 
1397             unset($table_idx);
1398         
1399         if (($table_token = gpcs_var('table_token', $get, $post, $cookie)) === FALSE) 
1400             unset($table_token);
1401
1402         force_no_cache($header_out);
1403
1404         switch ($path) {
1405         case "":
1406         case "index.php":
1407             ob_start();
1408             bin5_index_main($header_out, $addr, $get, $post, $cookie);
1409             $content = ob_get_contents();
1410             ob_end_clean();
1411         
1412             $s_a_p->pgflush_try_add($new_socket, 20, $header_out, $content);
1413             return TRUE;
1414         
1415         break;
1416         case "index_wr.php":
1417             $bri = $s_a_p->app->match_get($table_idx, $table_token);
1418             ob_start();
1419             bin5_index_wr_main($bri, $addr, $get, $post, $cookie);
1420             $content = ob_get_contents();
1421             ob_end_clean();
1422             
1423             $s_a_p->pgflush_try_add($new_socket, 20, $header_out, $content);
1424             return TRUE;
1425             
1426             break;
1427         case "index_rd_ifra.php":
1428             do {
1429                 if (($bri = $s_a_p->app->match_get($table_idx, $table_token)) == NULL
1430                     || !isset($cookie['sess'])
1431                     || (($user = $bri->get_user($cookie['sess'], $idx)) == FALSE)) {
1432
1433                     $content = Bin5_user::stream_fini(TRUE);                    
1434                     $s_a_p->pgflush_try_add($new_socket, 20, $header_out, $content);
1435
1436                     return TRUE;                    
1437                     break;
1438                 }
1439                 // close a previous opened index_read_ifra socket, if exists
1440                 if (($prev = $user->rd_socket_get()) != NULL) {
1441                     $s_a_p->socks_unset($user->rd_socket_get());
1442                     fclose($user->rd_socket_get());
1443                     printf("CLOSE AND OPEN AGAIN ON IFRA2\n");
1444                     $user->rd_socket_set(NULL);
1445                 }
1446                 
1447                 $content = "";
1448                 $user->stream_init($header_out, $content, $get, $post, $cookie);
1449                 $response = headers_render($header_out, -1).chunked_content($content);
1450                 $response_l = mb_strlen($response, "ASCII");
1451                 
1452                 $wret = @fwrite($new_socket, $response, $response_l);
1453                 if ($wret < $response_l) {
1454                     printf("TROUBLES WITH FWRITE: %d\n", $wret);
1455                     $user->rd_cache_set(mb_substr($content, $wret, $response_l - $wret, "ASCII"));
1456                 }
1457                 else {
1458                     $user->rd_cache_set("");
1459                 }
1460                 fflush($new_socket);
1461                 
1462                 
1463                 $s_a_p->socks_set($new_socket, $user);
1464                 $user->rd_socket_set($new_socket);
1465                 printf(" - qui ci siamo - ");
1466                 return TRUE;
1467             } while (FALSE);
1468             
1469             return FALSE;
1470             break;
1471             
1472         default:
1473             return FALSE;
1474             break;
1475       }
1476
1477       return (FALSE);
1478   }
1479
1480
1481
1482 } // end class Bin5
1483
1484 function locshm_exists($tok)
1485 {
1486     // return (TRUE);
1487
1488     if (($id = @shmop_open($tok,"a", 0, 0)) == FALSE) {
1489         log_main($tok." SHM NOT exists");
1490
1491         return (FALSE);
1492     }
1493     else {
1494         shmop_close($id);
1495         log_main($tok." SHM exists");
1496
1497         return (TRUE);
1498     }
1499     
1500 }
1501
1502 function asta2mult($asta_pnt)
1503
1504     if ($asta_pnt > 110) 
1505         return (5);
1506     else if ($asta_pnt > 100) 
1507         return (4);
1508     else if ($asta_pnt > 90) 
1509         return (3);
1510     else if ($asta_pnt > 80) 
1511         return (2);
1512     else if ($asta_pnt > 70) 
1513         return (1);
1514     else
1515         return (0);
1516 }
1517
1518 // rendiamo qui l'elenco dei punti come return della func
1519 function calculate_points(&$table)
1520 {
1521     GLOBAL $G_all_points; 
1522
1523     $ret = array();
1524     $pro = 0;
1525
1526     if ($table->asta_pnt == 60)
1527         $table->asta_pnt = 61;
1528
1529     $table->old_reason = "";
1530     $table->old_win = $table->asta_win;
1531     $table->old_friend = $table->friend;
1532     $table->old_asta_pnt = $table->asta_pnt;
1533     $table->old_mult = $table->mult;
1534
1535     for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1536         // for ($i = 0 ; $i < 40 ; $i++) {
1537         $ctt = $table->card[$i]->value % 10;
1538         $own = $table->card[$i]->owner;
1539         if ($own == $table->asta_win || $own == $table->friend) 
1540             $pro += $G_all_points[$ctt];
1541     }
1542
1543     log_wr(sprintf("PRO: [%d]", $pro));
1544
1545   
1546     if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1547         $table->points[$table->points_n % MAX_POINTS] = array();
1548         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1549             $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1550             $ret[$i] = 0;
1551         }
1552         $table->points_n++;
1553         $table->old_pnt = $pro;
1554         $table->mult += 1;
1555
1556         return($ret);
1557     }
1558
1559     if ($pro >= $table->asta_pnt) 
1560         $sig = 1;
1561     else
1562         $sig = -1;
1563
1564     $gamult = asta2mult($table->asta_pnt);
1565   
1566     $table->points[$table->points_n % MAX_POINTS] = array();
1567     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1568         if ($i == $table->asta_win) 
1569             $pt = ($i == $table->friend ? 4 : 2);
1570         else if ($i == $table->friend) 
1571             $pt = 1;
1572         else
1573             $pt = -1;
1574     
1575     
1576
1577         log_wr(sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1578
1579         $pt = $pt * $sig * ($gamult + $table->mult) * ($pro == 120 ? 2 : 1);
1580
1581         log_wr(sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
1582     
1583         $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
1584         $table->total[$i] += $pt;
1585         $ret[$i] = $pt;
1586     }
1587     $table->points_n++;
1588     $table->old_pnt = $pro;
1589     $table->mult = 1;
1590   
1591     return($ret);
1592 }
1593
1594 /* show table 
1595    is_transition (is from room to table ?)
1596    is_again      (is another game)
1597
1598    Examples                    of $is_transition, $is_again:
1599    from reload of the page:              FALSE, FALSE
1600    from sitdown in room:                  TRUE, FALSE
1601    from table: asta cmd e tutti passano:  TRUE, TRUE
1602    from table: fine partita:              TRUE, TRUE
1603 */
1604 function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
1605 {
1606     $table_idx = $user->table;
1607     $table     = $bri->table[$table_idx];
1608     $table_pos = $user->table_pos;
1609
1610     $ret = "table_init();";
1611     $ret .= $table->exitlock_show(&$bri->user, $table_pos);
1612     if (!$is_again) {
1613         /* GENERAL STATUS */
1614         $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1615                          $sendstep, $user->stat, $user->subst, $table_pos);
1616
1617         log_rd(sprintf( 'SHOW_TABLE: gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;', $sendstep, $user->stat, $user->subst, $table_pos));
1618
1619         /* BACKGROUND */
1620         $ret .= "background_set();";
1621     
1622         /* USERS INFO */
1623         $ret .= $user->myname_innerHTML();
1624         $ret .= sprintf('set_names([%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"]); ',
1625                         $bri->user[$table->player[($table_pos) % BIN5_PLAYERS_N]]->flags,
1626                         xcape($bri->user[$table->player[($table_pos) % BIN5_PLAYERS_N]]->name),
1627
1628                         $bri->user[$table->player[($table_pos+1) % BIN5_PLAYERS_N]]->flags,
1629                         xcape($bri->user[$table->player[($table_pos+1) % BIN5_PLAYERS_N]]->name),
1630
1631                         $bri->user[$table->player[($table_pos+2) % BIN5_PLAYERS_N]]->flags,
1632                         xcape($bri->user[$table->player[($table_pos+2) % BIN5_PLAYERS_N]]->name),
1633
1634                         (BIN5_PLAYERS_N == 3 ? 0 : $bri->user[$table->player[($table_pos+3) % BIN5_PLAYERS_N]]->flags),
1635                         (BIN5_PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+3) % BIN5_PLAYERS_N]]->name)),
1636
1637                         (BIN5_PLAYERS_N == 3 ? 0 : $bri->user[$table->player[($table_pos+4) % BIN5_PLAYERS_N]]->flags),
1638                         (BIN5_PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+4) % BIN5_PLAYERS_N]]->name)));
1639     }
1640     /* NOTIFY FOR THE CARD MAKER */
1641     if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1642         $ret .= show_table_info(&$bri, &$table, $table_pos);
1643     }
1644     if (!$is_again) 
1645         $ret .= table_wellcome($user);
1646
1647     if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1648         $ret .= playsound("cow.mp3");
1649     }
1650
1651
1652     /* CARDS */
1653     if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1654         $ret .= "|";
1655     
1656         for ($i = 0 ; $i < 8 ; $i++) {
1657             for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) {
1658                 $ct = 0;
1659                 for ($o = 0 ; $o < (BIN5_PLAYERS_N == 5 ? 40 : 24) && $ct < $i+1 ; $o++) {
1660                     // for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1661                     if ($table->card[$o]->owner == (($e + $table->gstart) % BIN5_PLAYERS_N)) {
1662                         $ct++;
1663                         if ($ct == $i+1)
1664                             break;
1665                     }
1666                 }
1667                 log_rd("O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1668         
1669                 $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % BIN5_PLAYERS_N, 
1670                                  $i, ((($e + BIN5_PLAYERS_N - $table_pos + $table->gstart) % BIN5_PLAYERS_N) == 0 ?
1671                                       $table->card[$o]->value : -1), 
1672                                  ($i == 7 && $e == (BIN5_PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1673             }
1674         }    
1675     }
1676     else {
1677         $taked  = array(0,0,0,0,0);
1678         $inhand = array(0,0,0,0,0);
1679         $ontabl  = array(-1,-1,-1,-1,-1);
1680         $cards  = array();
1681
1682         for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1683             // for ($i = 0 ; $i < 40 ; $i++) {
1684             if ($table->card[$i]->stat == 'hand') {
1685                 if ($table->card[$i]->owner == $table_pos) {
1686                     $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1687                 }
1688                 $inhand[$table->card[$i]->owner]++;
1689             }
1690             else if ($table->card[$i]->stat == 'take') {
1691                 log_main("Card taked: ".$table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1692                 $taked[$table->card[$i]->owner]++;
1693             }
1694             else if ($table->card[$i]->stat == 'table') {
1695                 $ontabl[$table->card[$i]->owner] = $i;
1696             }
1697         }
1698         $logg = "\n";
1699         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1700             $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1701         }
1702         log_main("Stat table: ".$logg);
1703
1704         /* Set ours cards. */
1705         $oursarg = "";
1706         for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
1707             $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1708         for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
1709             $oursarg .= ($i == 0 ? "" : ", ")."-1";
1710         $ret .= sprintf('card_setours(%s);', $oursarg);
1711
1712         /* Dispose all cards */
1713         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1714             /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1715             $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1716                             ($inhand[$i] <= 8 ? $inhand[$i] : 8)  , $taked[$i]);
1717
1718             if ($ontabl[$i] != -1) {
1719                 $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1720                                 $table->card[$ontabl[$i]]->value, 
1721                                 $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1722             }
1723         }
1724     }
1725
1726     /* Show auction */
1727     if ($user->subst == 'asta') {
1728
1729         /* show users auction status */
1730         $showst = "";
1731         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1732             $user_cur = &$bri->user[$table->player[$i]];
1733             $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1734                                ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1735         }
1736         if (BIN5_PLAYERS_N == 3)
1737             $showst .= ",-2,-2";
1738         $ret .= sprintf('document.title = "Brisk - Tavolo %d (asta)";', $user->table_orig);
1739         $ret .= sprintf('show_astat(%s);', $showst);
1740
1741         if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
1742             /* show card chooser */
1743             $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
1744                             $table->asta_card);
1745         }
1746         else {
1747             /* show auction */
1748             if ($table_pos == ($table->gstart % BIN5_PLAYERS_N) &&
1749                 $table->asta_win == -1) 
1750                 $ret .= sprintf('dispose_asta(%d,%d, %s);', 
1751                                 $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
1752             else
1753                 $ret .= sprintf('dispose_asta(%d,%d, %s);',
1754                                 $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
1755         }
1756
1757         /* Remark */
1758         if ($table->asta_win == -1) { // auction case
1759             if ($table_pos == ($table->gstart % BIN5_PLAYERS_N)) 
1760                 $ret .= "remark_on();";
1761             else
1762                 $ret .= "remark_off();";
1763         }
1764         else { // chooseed case
1765             if ($table_pos == $table->asta_win) 
1766                 $ret .= "remark_on();";
1767             else
1768                 $ret .= "remark_off();";
1769         }
1770     }
1771     else if ($user->subst == 'game') {
1772         /* HIGHLIGHT */
1773         if (($table->gstart + $table->turn) % BIN5_PLAYERS_N == $table_pos) 
1774             $ret .= "is_my_time = true; remark_on();";
1775         else
1776             $ret .= "remark_off();";
1777     
1778         /* WHO CALL AND WHAT */
1779         $ret .= briscola_show($bri, $table, $user);
1780     
1781     }
1782     return ($ret);
1783 } // end function show_table(...
1784
1785 function calculate_winner(&$table)
1786 {
1787     $briontab = FALSE;
1788     $ontab = array();
1789     $ontid = array();
1790     $cur_win  =  -1;
1791     $cur_val  = 100;
1792     $cur_seed = $table->briscola - ($table->briscola % 10);
1793
1794     for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1795         // for ($i = 0 ; $i < 40 ; $i++) {
1796         if ($table->card[$i]->stat != "table")
1797             continue;
1798
1799         log_wr(sprintf("Card On table: [%d]", $i));
1800
1801         $v = $table->card[$i]->value; 
1802         $ontab[$table->card[$i]->owner] = $v;
1803         $ontid[$table->card[$i]->owner] = $i;
1804         /* se briscola setto il flag */
1805         if (($v - ($v % 10)) == $cur_seed)
1806             $briontab = TRUE;
1807     }
1808
1809     if ($briontab == FALSE) {
1810         $cur_win  = $table->gstart;
1811         $cur_val  = $ontab[$cur_win];
1812         $cur_seed = $cur_val - ($cur_val % 10);
1813     }
1814
1815     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1816         if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1817             if ($ontab[$i] < $cur_val) {
1818                 $cur_val = $ontab[$i];
1819                 $cur_win = $i;
1820             }
1821         }
1822     }
1823
1824     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1825         $table->card[$ontid[$i]]->owner = $cur_win;
1826         $table->card[$ontid[$i]]->stat =  "take"; // Card stat
1827     }
1828     return ($cur_win);
1829 }
1830
1831 function show_table_info(&$bri, &$table, $table_pos)
1832 {
1833     GLOBAL $G_lang, $mlang_bin5_bin5;
1834
1835     $ret = "";
1836     $user = $bri->user[$table->player[$table_pos]];
1837
1838     $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1839     $noty = sprintf('<table class=\"points\"><tr><th></th>');
1840   
1841     // Names.
1842     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) 
1843         $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($bri->user[$table->player[$i]]->name));
1844     $noty .= sprintf("</tr>");
1845
1846     // Points.
1847     log_main("show_table_info: pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1848
1849     for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1850         $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1851         for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) 
1852             $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1853         $noty .= "</tr>";
1854     }
1855
1856     // Total points.
1857     $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1858     for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) 
1859         $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1860     $noty .= "</tr></table>";
1861
1862     if ($table->old_reason != "") {
1863         $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1864     }
1865
1866     if ($table->old_win != -1) {
1867         log_main("TABLE_OLD_WIN:".$table->old_win);
1868         $win = $table->player[$table->old_win];
1869         log_main("TABLE_OLD_FRIEND:".$table->old_friend);
1870         $fri = $table->player[$table->old_friend];
1871
1872         $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1873
1874         if ($win != $fri) {
1875             /* MLANG: "<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", "hanno fatto <b>cappotto</b> EBBRAVI!.<hr>", "dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>", "<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", "ha fatto <b>cappotto</b> EBBRAVO!.<hr>", "doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>", ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt : 'pi&ugrave; di 60'), $table->old_pnt, ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso" */
1876       
1877             $noty .= sprintf($mlang_bin5_bin5['info_part'][$G_lang], 
1878                              xcape($bri->user[$win]->name),
1879                              xcape($bri->user[$fri]->name));
1880             if ($table->old_pnt == 120) {
1881                 $noty .= sprintf($mlang_bin5_bin5['info_capp'][$G_lang]);
1882             }
1883             else {
1884                 $noty .= sprintf($mlang_bin5_bin5['info_pnt'][$G_lang],
1885                                  ($table->old_asta_pnt > 61 ? $mlang_bin5_bin5['info_alea'][$G_lang].$table->old_asta_pnt :
1886                                   $mlang_bin5_bin5['info_more'][$G_lang]), $table->old_pnt,
1887                                  ($wol == 1 ? $mlang_bin5_bin5['info_win'][$G_lang] : ($wol == 0 ? $mlang_bin5_bin5['info_peer'][$G_lang] : $mlang_bin5_bin5['info_lost'][$G_lang])));
1888             }
1889         }
1890         else {
1891             $noty .= sprintf($mlang_bin5_bin5['info_alon'][$G_lang],
1892                              xcape($bri->user[$win]->name));
1893             if ($table->old_pnt == 120) {
1894                 $noty .= sprintf($mlang_bin5_bin5['info_acap'][$G_lang]);
1895             }
1896             else {
1897                 $noty .= sprintf($mlang_bin5_bin5['info_apnt'][$G_lang],
1898
1899                                  ($table->old_asta_pnt > 61 ? $mlang_bin5_bin5['info_alea'][$G_lang].$table->old_asta_pnt :
1900                                   $mlang_bin5_bin5['info_more'][$G_lang]), $table->old_pnt,
1901
1902                                  ($wol == 1 ? $mlang_bin5_bin5['info_win'][$G_lang] : ($wol == 0 ? $mlang_bin5_bin5['info_peer'][$G_lang] : $mlang_bin5_bin5['info_lost'][$G_lang])));
1903             }
1904         }
1905         if (($table->old_mult + asta2mult($table->old_asta_pnt)) > 1) {
1906             $noty .= sprintf($mlang_bin5_bin5['info_omul'][$G_lang], multoval($table->old_mult + asta2mult($table->old_asta_pnt)));
1907         }
1908         $noty .= "<hr><br>";
1909     }
1910     /* MLANG: "Fai <b>tu</b> il mazzo,", "Il mazzo a <b>$unam</b>," */
1911     if ($table->mazzo == $table_pos) 
1912         $noty .= $mlang_bin5_bin5['info_yshuf'][$G_lang];
1913     else {
1914         $unam = xcape($bri->user[$table->player[$table->mazzo]]->name);
1915         $noty .= sprintf($mlang_bin5_bin5['info_shuf'][$G_lang], $unam);
1916     }
1917
1918     if ($user->subst == 'asta') {
1919         if ($table->asta_win == -1)  // auction case
1920             $curplayer = $table->gstart % BIN5_PLAYERS_N;
1921         else 
1922             $curplayer = $table->asta_win;
1923     }
1924     else if ($user->subst == 'game') {
1925         $curplayer = ($table->gstart + $table->turn) % BIN5_PLAYERS_N;
1926     }
1927
1928     /* MLANG: " tocca a <b>te</b> giocare.", " tocca a <b>$unam</b> giocare.", " La partita vale <b>%s</b>.", "torna alla partita" */
1929     if ($curplayer == $table_pos) {
1930         $noty .= $mlang_bin5_bin5['info_yturn'][$G_lang];
1931     }
1932     else {
1933         $unam = xcape($bri->user[$table->player[$curplayer]]->name);
1934         $noty .= sprintf($mlang_bin5_bin5['info_turn'][$G_lang], $unam);
1935     }
1936   
1937     if (($table->mult + asta2mult($table->asta_pnt)) > 1) {
1938         $noty .= sprintf($mlang_bin5_bin5['info_mult'][$G_lang], multoval($table->mult + asta2mult($table->asta_pnt)));
1939     }
1940     $noty .= "<hr><br>";
1941     $ret .= show_notify($noty, 3000, $mlang_bin5_bin5['btn_bkgame'][$G_lang], 500, 400);
1942     /* NOTE: show_notify($noty, 3000, "torna alla partita", 500, 
1943      *                   130 + ($table->points_n > 0 ? 50 : 0) + 
1944      *                   (120 * ($table->points_n / MAX_POINTS)));
1945      *       will be used when we refact notify js function following 
1946      *       photoo class logic 
1947      */ 
1948   
1949     return ($ret);
1950 }
1951
1952 function table_wellcome($user)
1953 {
1954     GLOBAL $table_wellarr, $G_lang;
1955     $ret = "";
1956
1957     for ($i = 0 ; $i < count($table_wellarr[$G_lang]) ; $i++)
1958         $ret .= sprintf('chatt_sub("%s", [2, "ChanServ: "],"%s");', "", str_replace('"', '\"', $table_wellarr[$G_lang][$i]));
1959
1960     return ($ret);
1961 }
1962
1963
1964 function briscola_show($bri, $table, $user)
1965 {
1966     GLOBAL $G_lang, $mlang_bin5_bin5;
1967     $ptnadd = "";
1968     $ret = "";
1969
1970     if ($table->asta_card == 9) 
1971         $ptnadd = sprintf($mlang_bin5_bin5['call_wptn'][$G_lang], $table->asta_pnt);
1972   
1973     /* text of caller cell */
1974     if ($user->table_pos == $table->asta_win) {
1975         $prestr = sprintf('$("callerinfo").innerHTML = "%s";', $mlang_bin5_bin5['call_ycall'][$G_lang]);
1976         $ret .= sprintf($prestr, $ptnadd);
1977     }
1978     else {
1979         $prestr = sprintf('$("callerinfo").innerHTML = "%s";', $mlang_bin5_bin5['call_call'][$G_lang]);
1980         $ret .= sprintf($prestr, 
1981                         xcape($bri->user[$table->player[$table->asta_win]]->name), $ptnadd);
1982     }
1983     $ret .= sprintf('set_iscalling(%d);', ($table->asta_win - $user->table_pos + BIN5_PLAYERS_N) % BIN5_PLAYERS_N);
1984
1985     $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1986                     $table->asta_win);
1987     $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1988     $ret .= sprintf('$("caller").style.visibility = "visible";');
1989     $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1990     $ret .= sprintf('$("astalascio").style.visibility = "";');
1991     $ret .= sprintf('$("asta").style.visibility = "hidden";');
1992     $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1993   
1994     return ($ret);
1995 }
1996
1997
1998 function game_result($asta_pnt, $pnt)
1999 {
2000     if ($asta_pnt == 61) {
2001         if ($pnt > 60)
2002             return (1);
2003         else if ($pnt == 60)
2004             return (0);
2005         else
2006             return (-1);
2007     }
2008     else {
2009         if ($pnt >= $asta_pnt)
2010             return (1);
2011         else
2012             return (-1);
2013     }
2014 }
2015
2016 function log_points($remote_addr, $curtime, $user, $where, $mesg) 
2017 {
2018     if (($fp = @fopen(LEGAL_PATH."/points.log", 'a')) != FALSE) {
2019         /* Unix time | session | nickname | IP | where was | mesg */
2020         fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
2021                             ($user->flags & USER_FLAG_AUTH ? 'A' : 'N'),
2022                             $user->name, $remote_addr, $where , $mesg));
2023         fclose($fp);
2024     }
2025 }
2026
2027 ?>