global is_page_streaming variable removed
[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     protected function blocking_error($is_unrecoverable)
724     {
725         log_crit("BLOCKING_ERROR UNREC: ".($is_unrecoverable ? "TRUE" : "FALSE"));
726         return (sprintf(($is_unrecoverable ? 'xstm.stop(); ' : '').'window.onbeforeunload = null; window.onunload = null; document.location.assign("../index.php");'));
727     }
728     
729     protected function page_sync($sess, $page)
730     {
731         log_rd2("PAGE_SYNC");
732         printf("xXx BIN5_USER::PAGE_SYNC\n");
733         return (sprintf('xstm.stop(); window.onbeforeunload = null; window.onunload = null; document.location.assign("%s");', $page));
734     }
735
736     protected function maincheck($cur_stat, $cur_subst, $cur_step, &$new_stat, &$new_subst, &$new_step, $splashdate, $table_idx, $table_token)
737     {
738         GLOBAL $G_lang, $mlang_indrd;
739         GLOBAL $G_with_splash, $G_splash_content, $G_splash_interval, $G_splash_idx;
740         GLOBAL $G_splash_w, $G_splash_h, $G_splash_timeout;
741         $CO_splashdate = "CO_splashdate".$G_splash_idx;
742         $$CO_splashdate = $splashdate;
743         
744         GLOBAL $S_load_stat;
745         
746         log_rd("maincheck begin");
747         
748         $ret = FALSE;
749         $curtime = time();
750         
751       /* Nothing changed, return. */
752       if ($cur_step == $this->step) 
753           return (FALSE);
754       
755       log_rd2("do other cur_stat[".$cur_stat."] user->stat[".$this->stat."] cur_step[".$cur_step."] user_step[".$this->step."]");
756       
757       if ($cur_step == -1) {
758           /*
759            *  if $cur_step == -1 load the current state from the main struct
760            */
761           
762           $S_load_stat['wR_minusone']++;
763           
764           // if ($this->the_end == TRUE) {
765           // log_rd2("main_check: the end".var_export(debug_backtrace()));
766           // }
767           
768           if ($this->trans_step != -1) {
769               log_rd2("TRANS USATO ".$this->trans_step);
770               $cur_step = $this->trans_step;
771               $this->trans_step = -1;
772           }
773           else {
774               log_rd2("TRANS NON ATTIVATO");
775           }
776       }
777       
778       
779       /* this part I suppose is read only on $this->room structure */
780       if ($cur_step == -1) {
781           log_rd2("PRE-NEWSTAT");
782               
783           /***************
784            *             *
785            *    TABLE    *
786            *             *
787            ***************/
788           if ($this->stat == 'table') {
789               log_load("RESYNC");
790               /* NOTE: $this->room is associated with the current $bri object */
791               printf("xXx CLASS NAME [%s]\n", get_class($this->room));
792               $ret = show_table(&$this->room, $this, $this->step, FALSE, FALSE);
793           }
794           log_rd2("NEWSTAT: ".$this->stat);
795
796           $new_stat =  $this->stat;
797           $new_subst = $this->subst;
798           $new_step =  $this->step;
799       } /* if ($cur_step == -1) { */
800       else {
801           /* $sem = Room::lock_data(FALSE); */
802           $S_load_stat['rU_heavy']++;
803           
804           if ($cur_step < $this->step) {
805               do {
806                   if ($cur_step + COMM_N < $this->step) {
807                       if (($cur_stat != $this->stat)) {
808                           $to_stat = $this->stat;
809                           /* Room::unlock_data($sem); */
810                           log_load("RESYNC");
811                           printf("xXx BIN5_USER::MAINCHECK\n");
812                           return ($this->page_sync($this->sess, ($to_stat == "table" ? "index.php" : "../index.php"), $this->table, $this->table_token));
813                       }
814                       log_rd2("lost history, refresh from scratch");
815                       printf("xXx LOST HISTORY!\n");
816                       $new_step = -1;
817                       break;
818                   } 
819                   for ($i = $cur_step ; $i < $this->step ; $i++) {
820                       $ii = $i % COMM_N;
821                       log_rd2("ADDED TO THE STREAM: ".$this->comm[$ii]);
822                       $ret .= $this->comm[$ii];
823                   }
824                   $new_stat =  $this->stat;
825                   $new_subst = $this->subst;
826                   $new_step =  $this->step;
827               } while (0);
828               
829               log_rd2($this->step, 'index_rd.php: after ret set');
830               
831               if ($this->the_end == TRUE) {
832                   log_rd2("LOGOUT BYE BYE!!");
833                   log_auth($this->sess, "Explicit logout.");
834                   
835                   if ($this->the_end == TRUE) {
836                       $this->reset();
837                       
838                       // FIXME !!! 
839                       /* if ($this->subst == 'sitdown') { */
840                       /*     log_load("ROOM WAKEUP"); */
841                       /*     $this->room->room_wakeup($this); */
842                       /* } */
843                       /* else if ($this->subst == 'standup') */
844                       /*     $this->room->room_outstandup($this); */
845                       /* else */
846                       /*     log_rd2("LOGOUT FROM WHAT ???"); */
847                       
848                   } /* if ($this->the_end == TRUE) { ... */
849               } /* if ($this->the_end == TRUE) { ... */
850           } /* if ($cur_step < $this->step) { */
851           
852           /* Room::unlock_data($sem); */
853       }  /* else of if ($cur_step == -1) { */
854       
855     
856       return ($ret);
857   }  //   function maincheck (...
858
859
860
861
862
863
864 } // end class Bin5_user
865
866
867
868 class Bin5 {
869     static $delta_t = array();
870
871     var $user;
872     var $table;
873     var $comm; // commands for many people
874     var $step; // current step of the comm array
875     var $garbage_timeout;
876     var $shm_sz;
877     
878     var $table_idx;
879     var $table_token;
880     
881     var $the_end;
882     var $tok;
883
884     static function page_manager($room, $header_out, $path, $method, $addr, $get, $post, $cookie) 
885     {
886         switch ($path) {
887         case "":
888         case "index.php":
889             ob_start();
890             bin5_index_main($room, $header_out, $addr, $get, $post, $cookie);
891             $content = ob_get_contents();
892             ob_end_clean();
893             
894             force_no_cache($header_out);
895
896             $pgflush = new PageFlush($new_socket, $curtime, 20, $header_out, $content);
897             
898             if ($pgflush->try_flush($curtime) == FALSE) {
899                 // Add $pgflush to the pgflush array
900                 array_push($pages_flush, $pgflush);
901             }
902             break;
903         }
904         return TRUE;
905     }
906
907     function Bin5 ($room, $table_idx, $table_token, $get, $post, $cookie) {
908         $this->user = array();
909         $this->table = array();
910         
911         $this->the_end = FALSE;
912         $this->shm_sz = BIN5_SHM_MIN;
913         if (($this->tok = @ftok(FTOK_PATH."/bin5/table".$table_idx."/table", "B")) == -1) {
914             echo "FTOK FAILED";
915             exit;
916         }
917         
918         $user  = $room->user;
919         $table = $room->table[$table_idx];
920         
921         log_wr("Bin5 constructor");
922         
923         for ($i = 0 ; $i < $table->player_n ; $i++) {
924             $user[$table->player[$i]]->table_token = $table_token;
925             $this->user[$i] = Bin5_user::spawn($user[$table->player[$i]], $this, $table_idx, $i, $get, $post, $cookie);
926         }
927         $this->table[0] = Bin5_table::spawn(&$table);
928         
929         log_main("TABLE_OLD_WIN - Bin5:".$this->table[0]->old_win);
930         
931         $this->table_idx = $table_idx;
932         $this->table_token = $table_token;
933         $this->garbage_timeout = 0;
934         
935         log_wr("Bin5 constructor end");
936     }
937     
938
939     function get_user($sess, &$idx)
940     {
941         GLOBAL $PHP_SELF;
942         
943         if (validate_sess($sess)) {
944             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
945                 if (strcmp($sess, $this->user[$i]->sess) == 0) {
946                     // find it
947                     $idx = $i;
948                     $ret = &$this->user[$i];
949                     return ($ret);
950                 }
951             }
952             log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
953             // for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) 
954             // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
955         }
956         else {
957             log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
958         }
959         
960         return (FALSE);
961     }
962     
963     
964     function garbage_manager($force)
965     {
966         GLOBAL $G_base;
967         
968         /* Garbage collector degli utenti in timeout */
969         $ismod = FALSE;
970         $curtime = time();
971         if ($force || $this->garbage_timeout < $curtime) {
972             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
973                 $user_cur = $this->user[$i];
974                 if ($user_cur->sess == "" || 
975                     ($user_cur->stat == 'table' && ($user_cur->subst == 'shutdowned' || $user_cur->subst == 'shutdowner')))
976                     continue;
977                 
978                 if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) { // Auto logout dell'utente
979                     log_rd2($user_cur->sess." bin5 AUTO LOGOUT.");
980                     
981                     if ($user_cur->stat == 'table') {
982                         log_auth($user_cur->sess," bin5 Autologout session.");
983                         
984                         /* SI DELEGA AL garbage_manager principale LA RIMOZIONE DELL'UTENTE 
985                            
986                            $tmp_sess = $user_cur->sess;
987                            $user_cur->sess = "";
988                            Bin5_user::step_unproxy($tmp_sess);
989                            $user_cur->name = "";
990                            $user_cur->the_end = FALSE;
991                            
992                         */
993                         
994                         /* se gli altri utenti non erano d'accordo questo utente viene bannato */
995                         $remcalc = $this->table[0]->exitlock_calc(&$this->user, $user_cur->table_pos);
996                         if ($remcalc < 3) {
997                             require_once("${G_base}Obj/hardban.phh");
998                             Hardbans::add(($user_cur->flags & USER_FLAG_AUTH ? $user_cur->name : FALSE),
999                                           $user_cur->ip, $user_cur->sess, $user_cur->laccwr + BAN_TIME);
1000                         }
1001                         //      $user->bantime = $user->laccwr + BAN_TIME;
1002                         
1003                         $this->table_wakeup($user_cur);
1004                     }
1005                 }
1006             }
1007             log_rd2($user_cur->sess." GARBAGE UPDATED!");
1008             
1009             $this->garbage_timeout = $curtime + GARBAGE_TIMEOUT;
1010             
1011             $ismod = TRUE;
1012         }
1013         
1014         return ($ismod);
1015     }
1016     
1017     // Bin5::load_data
1018     static function load_data($table_idx, $table_token = "") 
1019     {
1020         $shm = FALSE;
1021         
1022         log_wr("TABLE_FTOK ".FTOK_PATH."/bin5/table".$table_idx."/table");
1023         
1024         do {
1025             if (($tok = @ftok(FTOK_PATH."/bin5/table".$table_idx."/table", "B")) == -1) {
1026                 log_main("ftok failed");
1027                 break;
1028             }
1029             
1030             if (($shm_sz = sharedmem_sz($tok)) == -1) {
1031                 log_main("shmop_open failed");
1032                 break;
1033             }
1034         
1035             if (($shm = shm_attach($tok, $shm_sz)) == FALSE)
1036                 break;
1037
1038             if (($bri = @shm_get_var($shm, $tok)) == FALSE) 
1039                 break;
1040
1041             if ($table_token != "" && $bri->table_token != $table_token) {
1042                 log_wr("bri->table_token: ".$bri->table_token."table_token: ".$table_token);
1043                 break;
1044             }
1045             $bri->tok = $tok;
1046
1047             shm_detach($shm);
1048       
1049             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1050                 if (($bri->user[$i] = Bin5_user::load_data($table_idx, $i, FALSE)) == FALSE) {
1051                     log_crit("Bin5_user::load_data failed");
1052                     break;
1053                 }
1054             }
1055             if ($i < BIN5_MAX_PLAYERS) {
1056                 break;
1057             }
1058       
1059             return ($bri); 
1060         } while (FALSE);
1061
1062         if ($shm != FALSE)
1063             shm_detach($shm);
1064
1065         log_wr("briskin5 load_data failed");
1066     
1067         return (FALSE);
1068     }
1069   
1070
1071
1072     function save_data($bri) 
1073     {
1074         GLOBAL $sess;
1075       
1076         $ret =   FALSE;
1077         $shm =   FALSE;
1078       
1079         log_main("SAVE BRISKIN5 DATA");
1080       
1081         if (!isset($bri->tok))
1082             return (FALSE);
1083       
1084         $user_park = array();
1085         for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1086             $user_park[$i] = $bri->user[$i];
1087             $bri->user[$i] = FALSE;
1088         }
1089       
1090         while ($bri->shm_sz < BIN5_SHM_MAX) {
1091             if (($shm = shm_attach($bri->tok, $bri->shm_sz)) == FALSE)
1092                 break;
1093           
1094             if (@shm_put_var($shm, $bri->tok, $bri) != FALSE) {
1095
1096                 log_shme("Bin5::save_data");
1097
1098                 $ret = TRUE;
1099                 break;
1100             }
1101             if (shm_remove($shm) === FALSE) {
1102                 log_only("REMOVE FALLITA");
1103                 break;
1104             }
1105             shm_detach($shm);
1106             $bri->shm_sz += BIN5_SHM_DLT;
1107         } 
1108       
1109         if ($shm)
1110             shm_detach($shm);
1111       
1112         // SHSPLIT: reattach users to the room class
1113         for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1114             Bin5_user::save_data($user_park[$i], $bri->table_idx, $i);
1115             $bri->user[$i] = $user_park[$i];
1116         }
1117         log_load("FINISH: ".($ret == TRUE ? "TRUE" : "FALSE"));
1118       
1119         return ($ret);
1120     }
1121   
1122
1123
1124     function destroy_data() 
1125     {
1126         GLOBAL $sess;
1127
1128         $ret =   FALSE;
1129         $shm =   FALSE;
1130         log_main("DESTROY BRISKIN5 DATA");
1131     
1132         do {
1133             log_main("DESTROY2 BRISKIN5 DATA [".$this->table_idx."]");
1134             for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1135                 $this->user[$i]->destroy_data($this->table_idx);
1136                 Bin5_user::unproxy_step($this->table_idx, $this->user[$i]->sess);
1137             }
1138             if (($tok = @ftok(FTOK_PATH."/bin5/table".$this->table_idx."/table", "B")) == -1) 
1139                 break;
1140
1141             if (($shm = @shmop_open($tok, 'a', 0, 0)) == FALSE)
1142                 break;
1143       
1144             if (shmop_delete($shm) == 0) {
1145                 log_only("REMOVE FALLITA ");
1146                 break;
1147             }
1148    
1149             $shm = FALSE;
1150             log_main("DESTROY2 BRISKIN5 DATA SUCCESS");
1151       
1152             // log_main("QUI CI ARRIVA [".$bri->user[0]->name."]");
1153             $ret = TRUE;
1154         } while (0);
1155     
1156         if ($shm)
1157             shm_detach($shm);
1158     
1159         return ($ret);
1160     }
1161
1162     static function lock_data($is_exclusive, $table_idx)
1163     {
1164         if (($res = file_lock(FTOK_PATH."/bin5/table".$table_idx."/table", $is_exclusive)) != FALSE) {
1165             self::$delta_t = microtime(TRUE);
1166             log_lock("LOCK   table [".$table_idx."]         [".self::$delta_t[$table_idx]."]");
1167           
1168             return (new Vect(array('res' => $res, 'tab' => $table_idx)));
1169         }
1170       
1171         return (FALSE);
1172     }
1173
1174   
1175     static function unlock_data($res_vect)
1176     {
1177         GLOBAL $sess; 
1178
1179         $res = $res_vect->getbyid('res');
1180         $tab = $res_vect->getbyid('tab');
1181
1182         log_lock("UNLOCK table [".$tab."]         [".(microtime(TRUE) - (self::$delta_t[$tab]))."]");
1183
1184         file_unlock($res);
1185     }
1186
1187
1188     function chatt_send($user, $mesg)
1189     {
1190         GLOBAL $mlang_brisk, $G_lang;
1191
1192         if ($user->stat == 'table') {
1193             $table = &$this->table[$user->table];
1194         }
1195     
1196         $user_mesg = substr($mesg,6);
1197     
1198         $curtime = time();
1199     
1200         $dt = date("H:i ", $curtime);
1201         if (strncmp($user_mesg, "/nick ", 6) == 0) {
1202             log_main($user->sess." chatt_send BEGIN");
1203
1204             if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
1205                 $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1206                 $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['nickmust'][$G_lang]);
1207                 $user->step_inc();
1208
1209                 return;
1210             }
1211             $user_mesg = "COMMAND ".$user_mesg;
1212             // Search dup name
1213             // change
1214             // update local graph
1215             // update remote graphs
1216             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1217                 $user_cur = $this->user[$i];
1218                 //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1219                 if ($user_cur->sess == '')
1220                     continue;
1221                 if (strcasecmp($user_cur->name, $name_new) == 0) {
1222                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1223
1224                     $premsg = sprintf($mlang_brisk['nickdupl'][$G_lang], xcape($name_new));
1225                     $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, $premsg);
1226                     $user->step_inc();
1227                     break;
1228                 }
1229             }
1230             if ($i == BIN5_MAX_PLAYERS) {
1231                 if ($user->flags & USER_FLAG_AUTH && strcasecmp($user->name,$name_new) != 0) {
1232                     if ($this->table[$user->table]->auth_only == TRUE) {
1233                         $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1234                         $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"<b>%s</b>");', $dt, NICKSERV, $mlang_brisk['authchan'][$G_lang]);
1235                         $user->step_inc();
1236                         return;
1237                     }
1238                     else {
1239                         $user->flags &= ~USER_FLAG_AUTH; // Remove auth if name changed
1240                     }
1241                 }
1242     
1243                 $user->name = $name_new;
1244
1245                 log_main($user->sess." chatt_send start set");
1246         
1247
1248                 for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1249                     log_main($user->sess." chatt_send set loop");
1250           
1251                     $user_cur = &$this->user[$i];
1252                     if ($user_cur->sess == '')
1253                         continue;
1254           
1255                     if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
1256                         $table = &$this->table[$user->table];
1257             
1258                         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1259                         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('set_names([%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"]); ',
1260                                                                              $this->user[$table->player[($user_cur->table_pos) % BIN5_PLAYERS_N]]->flags,
1261                                                                              xcape($this->user[$table->player[($user_cur->table_pos) % BIN5_PLAYERS_N]]->name),
1262
1263                                                                              $this->user[$table->player[($user_cur->table_pos+1) % BIN5_PLAYERS_N]]->flags,
1264                                                                              xcape($this->user[$table->player[($user_cur->table_pos+1) % BIN5_PLAYERS_N]]->name),
1265
1266                                                                              $this->user[$table->player[($user_cur->table_pos+2) % BIN5_PLAYERS_N]]->flags,
1267                                                                              xcape($this->user[$table->player[($user_cur->table_pos+2) % BIN5_PLAYERS_N]]->name),
1268
1269                                                                              (BIN5_PLAYERS_N == 3 ? 0:  $this->user[$table->player[($user_cur->table_pos+3) % BIN5_PLAYERS_N]]->flags),
1270                                                                              (BIN5_PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3) % BIN5_PLAYERS_N]]->name)),
1271
1272                                                                              (BIN5_PLAYERS_N == 3 ? 0:  $this->user[$table->player[($user_cur->table_pos+4) % BIN5_PLAYERS_N]]->flags),
1273                                                                              (BIN5_PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4) % BIN5_PLAYERS_N]]->name)));
1274                         if ($user_cur == $user) {
1275                             $user_cur->comm[$user_cur->step % COMM_N] .= $user_cur->myname_innerHTML();
1276                         }
1277                         $user_cur->step_inc();
1278                     }
1279                 }
1280             }
1281         }
1282         else {
1283             for ($i = 0 ; $i < ($user->stat == 'room' ? BIN5_MAX_PLAYERS : BIN5_PLAYERS_N) ; $i++) {
1284                 if ($user->stat == 'room') {
1285                     $user_cur = &$this->user[$i];
1286                     if ($user_cur->sess == '' || $user_cur->stat != 'room')
1287                         continue;
1288                 }
1289                 else {
1290                     $user_cur = &$this->user[$table->player[$i]];
1291                 }
1292         
1293                 $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1294                 $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s", [%d, "%s"],"%s");',
1295                                                                      $dt, $user->flags, xcape($user->name), xcape($user_mesg));
1296                 $user_cur->step_inc();
1297             }
1298             log_legal($curtime, 'xxx', $user, ($user->stat == 'room' ? 'room' : 'table '.$user->table_orig),$user_mesg);
1299         }
1300     }
1301
1302     function table_wakeup($user)
1303     {
1304         $table = &$this->table[0];
1305
1306         log_main("BIN5_WAKEUP begin function table  stat: ".$user->stat."  subst: ".$user->subst);
1307
1308         $curtime = time();
1309
1310         log_main("BIN5_WAKEUP from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1311     
1312         for ($i = 0 ; $i < $table->player_n ; $i++) {
1313             $user_cur = &$this->user[$i];
1314             log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1315       
1316             if ($user_cur == $user)
1317                 $user_cur->subst = "shutdowner";
1318             else
1319                 $user_cur->subst = "shutdowned";
1320             $user_cur->laccwr = $curtime;
1321
1322             $ret = "gst.st = ".($user_cur->step+1)."; ";
1323             $ret .= 'gst.st_loc++; xstm.stop(); window.onbeforeunload = null; window.onunload = null; document.location.assign("../index.php");|';
1324
1325             log_wr($user_cur->sess." BIN5_WAKEUP: ".$ret);
1326             $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1327             $user_cur->step_inc();
1328         }
1329
1330         $this->the_end = TRUE;
1331     }
1332   
1333     /*
1334      *  If all players are freezed the room garbage_manager clean up table and users.
1335      */ 
1336     function is_abandoned() 
1337     {
1338         $is_ab = TRUE;
1339         $curtime = time();
1340
1341         $table = &$this->table[0];
1342
1343         for ($i = 0 ; $i < $table->player_n ; $i++) {
1344             $user_cur = &$this->user[$i];
1345
1346             if ($user_cur->lacc + (EXPIRE_TIME_RD * 2) >= $curtime) { 
1347                 $is_ab = FALSE;
1348                 break;
1349             }
1350         }
1351
1352         return ($is_ab);
1353     }
1354
1355     static function request_mgr(&$s_a_p, $header, &$header_out, &$new_socket, $path, $addr, $get, $post, $cookie)
1356     {
1357         printf("NEW_SOCKET (root): %d\n", intval($new_socket));
1358         
1359         $enc = get_encoding($header);
1360         if (isset($header['User-Agent']) && strstr($header['User-Agent'], "MSIE")) {
1361             $transp_type = "htmlfile";
1362         }
1363         else {
1364             $transp_type = "iframe";
1365         }
1366         force_no_cache($header_out);
1367
1368         if (($table_idx = gpcs_var('table_idx', $get, $post, $cookie)) === FALSE) 
1369             unset($table_idx);
1370         
1371         if (($table_token = gpcs_var('table_token', $get, $post, $cookie)) === FALSE) 
1372             unset($table_token);
1373
1374
1375         switch ($path) {
1376         case "":
1377         case "index.php":
1378             ob_start();
1379             bin5_index_main($transp_type, $header_out, $addr, $get, $post, $cookie);
1380             $content = ob_get_contents();
1381             ob_end_clean();
1382         
1383             $s_a_p->pgflush_try_add($enc, $new_socket, 20, $header_out, $content);
1384             return TRUE;
1385         
1386         break;
1387         case "index_wr.php":
1388             // FIXME $content can be unset
1389             if (isset($table_idx) && isset($table_token)) {
1390                 if (($bri = $s_a_p->app->match_get($table_idx, $table_token)) != FALSE) {
1391                     ob_start();
1392                     bin5_index_wr_main($bri, $addr, $get, $post, $cookie);
1393                     $content = ob_get_contents();
1394                     ob_end_clean();
1395                 }
1396             }
1397             $s_a_p->pgflush_try_add($enc, $new_socket, 20, $header_out, $content);
1398             return TRUE;
1399             
1400             break;
1401         case "index_rd_ifra.php":
1402             do {
1403                 if (!isset($table_idx)
1404                     || !isset($table_token)
1405                     || !isset($cookie['sess'])
1406                     || ($bri = $s_a_p->app->match_get($table_idx, $table_token)) == NULL
1407                     || (($user = $bri->get_user($cookie['sess'], $idx)) == FALSE)) {
1408
1409                     $content = Bin5_user::stream_fini($s_a_p->rndstr, TRUE);
1410                     $s_a_p->pgflush_try_add($enc, $new_socket, 20, $header_out, $content);
1411
1412                     return TRUE;
1413                     break;
1414                 }
1415                 // close a previous opened index_read_ifra socket, if exists
1416                 if (($prev = $user->rd_socket_get()) != NULL) {
1417                     $s_a_p->socks_unset($user->rd_socket_get());
1418                     fclose($user->rd_socket_get());
1419                     printf("CLOSE AND OPEN AGAIN ON IFRA2\n");
1420                     $user->rd_socket_set(NULL);
1421                 }
1422                 
1423                 $content = "";
1424                 $user->stream_init($s_a_p->rndstr, $enc, $header_out, $content, $get, $post, $cookie);
1425                 $response = headers_render($header_out, -1).chunked_content($user->rd_zls_get(), $content);
1426                 $response_l = mb_strlen($response, "ASCII");
1427                 
1428                 $wret = @fwrite($new_socket, $response, $response_l);
1429                 if ($wret < $response_l) {
1430                     printf("TROUBLES WITH FWRITE: %d\n", $wret);
1431                     $user->rd_cache_set(mb_substr($content, $wret, $response_l - $wret, "ASCII"));
1432                 }
1433                 else {
1434                     $user->rd_cache_set("");
1435                 }
1436                 fflush($new_socket);
1437                 
1438                 
1439                 $s_a_p->socks_set($new_socket, $user);
1440                 $user->rd_socket_set($new_socket);
1441                 printf(" - qui ci siamo - ");
1442                 return TRUE;
1443             } while (FALSE);
1444             
1445             return FALSE;
1446             break;
1447             
1448         default:
1449             return FALSE;
1450             break;
1451       }
1452
1453       return (FALSE);
1454   }
1455
1456
1457
1458 } // end class Bin5
1459
1460 function locshm_exists($tok)
1461 {
1462     // return (TRUE);
1463
1464     if (($id = @shmop_open($tok,"a", 0, 0)) == FALSE) {
1465         log_main($tok." SHM NOT exists");
1466
1467         return (FALSE);
1468     }
1469     else {
1470         shmop_close($id);
1471         log_main($tok." SHM exists");
1472
1473         return (TRUE);
1474     }
1475     
1476 }
1477
1478 function asta2mult($asta_pnt)
1479
1480     if ($asta_pnt > 110) 
1481         return (5);
1482     else if ($asta_pnt > 100) 
1483         return (4);
1484     else if ($asta_pnt > 90) 
1485         return (3);
1486     else if ($asta_pnt > 80) 
1487         return (2);
1488     else if ($asta_pnt > 70) 
1489         return (1);
1490     else
1491         return (0);
1492 }
1493
1494 // rendiamo qui l'elenco dei punti come return della func
1495 function calculate_points(&$table)
1496 {
1497     GLOBAL $G_all_points; 
1498
1499     $ret = array();
1500     $pro = 0;
1501
1502     if ($table->asta_pnt == 60)
1503         $table->asta_pnt = 61;
1504
1505     $table->old_reason = "";
1506     $table->old_win = $table->asta_win;
1507     $table->old_friend = $table->friend;
1508     $table->old_asta_pnt = $table->asta_pnt;
1509     $table->old_mult = $table->mult;
1510
1511     for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1512         // for ($i = 0 ; $i < 40 ; $i++) {
1513         $ctt = $table->card[$i]->value % 10;
1514         $own = $table->card[$i]->owner;
1515         if ($own == $table->asta_win || $own == $table->friend) 
1516             $pro += $G_all_points[$ctt];
1517     }
1518
1519     log_wr(sprintf("PRO: [%d]", $pro));
1520
1521   
1522     if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1523         $table->points[$table->points_n % MAX_POINTS] = array();
1524         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1525             $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1526             $ret[$i] = 0;
1527         }
1528         $table->points_n++;
1529         $table->old_pnt = $pro;
1530         $table->mult += 1;
1531
1532         return($ret);
1533     }
1534
1535     if ($pro >= $table->asta_pnt) 
1536         $sig = 1;
1537     else
1538         $sig = -1;
1539
1540     $gamult = asta2mult($table->asta_pnt);
1541   
1542     $table->points[$table->points_n % MAX_POINTS] = array();
1543     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1544         if ($i == $table->asta_win) 
1545             $pt = ($i == $table->friend ? 4 : 2);
1546         else if ($i == $table->friend) 
1547             $pt = 1;
1548         else
1549             $pt = -1;
1550     
1551     
1552
1553         log_wr(sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1554
1555         $pt = $pt * $sig * ($gamult + $table->mult) * ($pro == 120 ? 2 : 1);
1556
1557         log_wr(sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
1558     
1559         $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
1560         $table->total[$i] += $pt;
1561         $ret[$i] = $pt;
1562     }
1563     $table->points_n++;
1564     $table->old_pnt = $pro;
1565     $table->mult = 1;
1566   
1567     return($ret);
1568 }
1569
1570 /* show table 
1571    is_transition (is from room to table ?)
1572    is_again      (is another game)
1573
1574    Examples                    of $is_transition, $is_again:
1575    from reload of the page:              FALSE, FALSE
1576    from sitdown in room:                  TRUE, FALSE
1577    from table: asta cmd e tutti passano:  TRUE, TRUE
1578    from table: fine partita:              TRUE, TRUE
1579 */
1580 function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
1581 {
1582     $table_idx = $user->table;
1583     $table     = $bri->table[$table_idx];
1584     $table_pos = $user->table_pos;
1585
1586     $ret = "table_init();";
1587     $ret .= $table->exitlock_show(&$bri->user, $table_pos);
1588     if (!$is_again) {
1589         /* GENERAL STATUS */
1590         $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1591                          $sendstep, $user->stat, $user->subst, $table_pos);
1592
1593         log_rd(sprintf( 'SHOW_TABLE: gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;', $sendstep, $user->stat, $user->subst, $table_pos));
1594
1595         /* BACKGROUND */
1596         $ret .= "background_set();";
1597     
1598         /* USERS INFO */
1599         $ret .= $user->myname_innerHTML();
1600         $ret .= sprintf('set_names([%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"]); ',
1601                         $bri->user[$table->player[($table_pos) % BIN5_PLAYERS_N]]->flags,
1602                         xcape($bri->user[$table->player[($table_pos) % BIN5_PLAYERS_N]]->name),
1603
1604                         $bri->user[$table->player[($table_pos+1) % BIN5_PLAYERS_N]]->flags,
1605                         xcape($bri->user[$table->player[($table_pos+1) % BIN5_PLAYERS_N]]->name),
1606
1607                         $bri->user[$table->player[($table_pos+2) % BIN5_PLAYERS_N]]->flags,
1608                         xcape($bri->user[$table->player[($table_pos+2) % BIN5_PLAYERS_N]]->name),
1609
1610                         (BIN5_PLAYERS_N == 3 ? 0 : $bri->user[$table->player[($table_pos+3) % BIN5_PLAYERS_N]]->flags),
1611                         (BIN5_PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+3) % BIN5_PLAYERS_N]]->name)),
1612
1613                         (BIN5_PLAYERS_N == 3 ? 0 : $bri->user[$table->player[($table_pos+4) % BIN5_PLAYERS_N]]->flags),
1614                         (BIN5_PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($table_pos+4) % BIN5_PLAYERS_N]]->name)));
1615     }
1616     /* NOTIFY FOR THE CARD MAKER */
1617     if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1618         $ret .= show_table_info(&$bri, &$table, $table_pos);
1619         $ret .= "setTimeout(preload_images, 500, g_preload_img_arr, g_imgct);";
1620     }
1621     if (!$is_again) 
1622         $ret .= table_wellcome($user);
1623
1624     if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1625         $ret .= playsound("cow.mp3");
1626     }
1627
1628
1629     /* CARDS */
1630     if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1631         $ret .= "|";
1632     
1633         for ($i = 0 ; $i < 8 ; $i++) {
1634             for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) {
1635                 $ct = 0;
1636                 for ($o = 0 ; $o < (BIN5_PLAYERS_N == 5 ? 40 : 24) && $ct < $i+1 ; $o++) {
1637                     // for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1638                     if ($table->card[$o]->owner == (($e + $table->gstart) % BIN5_PLAYERS_N)) {
1639                         $ct++;
1640                         if ($ct == $i+1)
1641                             break;
1642                     }
1643                 }
1644                 log_rd("O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1645         
1646                 $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % BIN5_PLAYERS_N, 
1647                                  $i, ((($e + BIN5_PLAYERS_N - $table_pos + $table->gstart) % BIN5_PLAYERS_N) == 0 ?
1648                                       $table->card[$o]->value : -1), 
1649                                  ($i == 7 && $e == (BIN5_PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1650             }
1651         }    
1652     }
1653     else {
1654         $taked  = array(0,0,0,0,0);
1655         $inhand = array(0,0,0,0,0);
1656         $ontabl  = array(-1,-1,-1,-1,-1);
1657         $cards  = array();
1658
1659         for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1660             // for ($i = 0 ; $i < 40 ; $i++) {
1661             if ($table->card[$i]->stat == 'hand') {
1662                 if ($table->card[$i]->owner == $table_pos) {
1663                     $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1664                 }
1665                 $inhand[$table->card[$i]->owner]++;
1666             }
1667             else if ($table->card[$i]->stat == 'take') {
1668                 log_main("Card taked: ".$table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1669                 $taked[$table->card[$i]->owner]++;
1670             }
1671             else if ($table->card[$i]->stat == 'table') {
1672                 $ontabl[$table->card[$i]->owner] = $i;
1673             }
1674         }
1675         $logg = "\n";
1676         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1677             $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1678         }
1679         log_main("Stat table: ".$logg);
1680
1681         /* Set ours cards. */
1682         $oursarg = "";
1683         for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
1684             $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1685         for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
1686             $oursarg .= ($i == 0 ? "" : ", ")."-1";
1687         $ret .= sprintf('card_setours(%s);', $oursarg);
1688
1689         /* Dispose all cards */
1690         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1691             /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1692             $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1693                             ($inhand[$i] <= 8 ? $inhand[$i] : 8)  , $taked[$i]);
1694
1695             if ($ontabl[$i] != -1) {
1696                 $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1697                                 $table->card[$ontabl[$i]]->value, 
1698                                 $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1699             }
1700         }
1701     }
1702
1703     /* Show auction */
1704     if ($user->subst == 'asta') {
1705
1706         /* show users auction status */
1707         $showst = "";
1708         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1709             $user_cur = &$bri->user[$table->player[$i]];
1710             $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1711                                ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1712         }
1713         if (BIN5_PLAYERS_N == 3)
1714             $showst .= ",-2,-2";
1715         $ret .= sprintf('document.title = "Brisk - Tavolo %d (asta)";', $user->table_orig);
1716         $ret .= sprintf('show_astat(%s);', $showst);
1717
1718         if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
1719             /* show card chooser */
1720             $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
1721                             $table->asta_card);
1722         }
1723         else {
1724             /* show auction */
1725             if ($table_pos == ($table->gstart % BIN5_PLAYERS_N) &&
1726                 $table->asta_win == -1) 
1727                 $ret .= sprintf('dispose_asta(%d,%d, %s);', 
1728                                 $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
1729             else
1730                 $ret .= sprintf('dispose_asta(%d,%d, %s);',
1731                                 $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
1732         }
1733
1734         /* Remark */
1735         if ($table->asta_win == -1) { // auction case
1736             if ($table_pos == ($table->gstart % BIN5_PLAYERS_N)) 
1737                 $ret .= "remark_on();";
1738             else
1739                 $ret .= "remark_off();";
1740         }
1741         else { // chooseed case
1742             if ($table_pos == $table->asta_win) 
1743                 $ret .= "remark_on();";
1744             else
1745                 $ret .= "remark_off();";
1746         }
1747     }
1748     else if ($user->subst == 'game') {
1749         /* HIGHLIGHT */
1750         if (($table->gstart + $table->turn) % BIN5_PLAYERS_N == $table_pos) 
1751             $ret .= "is_my_time = true; remark_on();";
1752         else
1753             $ret .= "remark_off();";
1754     
1755         /* WHO CALL AND WHAT */
1756         $ret .= briscola_show($bri, $table, $user);
1757     
1758     }
1759     return ($ret);
1760 } // end function show_table(...
1761
1762 function calculate_winner(&$table)
1763 {
1764     $briontab = FALSE;
1765     $ontab = array();
1766     $ontid = array();
1767     $cur_win  =  -1;
1768     $cur_val  = 100;
1769     $cur_seed = $table->briscola - ($table->briscola % 10);
1770
1771     for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1772         // for ($i = 0 ; $i < 40 ; $i++) {
1773         if ($table->card[$i]->stat != "table")
1774             continue;
1775
1776         log_wr(sprintf("Card On table: [%d]", $i));
1777
1778         $v = $table->card[$i]->value; 
1779         $ontab[$table->card[$i]->owner] = $v;
1780         $ontid[$table->card[$i]->owner] = $i;
1781         /* se briscola setto il flag */
1782         if (($v - ($v % 10)) == $cur_seed)
1783             $briontab = TRUE;
1784     }
1785
1786     if ($briontab == FALSE) {
1787         $cur_win  = $table->gstart;
1788         $cur_val  = $ontab[$cur_win];
1789         $cur_seed = $cur_val - ($cur_val % 10);
1790     }
1791
1792     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1793         if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1794             if ($ontab[$i] < $cur_val) {
1795                 $cur_val = $ontab[$i];
1796                 $cur_win = $i;
1797             }
1798         }
1799     }
1800
1801     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1802         $table->card[$ontid[$i]]->owner = $cur_win;
1803         $table->card[$ontid[$i]]->stat =  "take"; // Card stat
1804     }
1805     return ($cur_win);
1806 }
1807
1808 function show_table_info(&$bri, &$table, $table_pos)
1809 {
1810     GLOBAL $G_lang, $mlang_bin5_bin5;
1811
1812     $ret = "";
1813     $user = $bri->user[$table->player[$table_pos]];
1814
1815     $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1816     $noty = sprintf('<table class=\"points\"><tr><th></th>');
1817   
1818     // Names.
1819     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) 
1820         $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($bri->user[$table->player[$i]]->name));
1821     $noty .= sprintf("</tr>");
1822
1823     // Points.
1824     log_main("show_table_info: pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1825
1826     for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1827         $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1828         for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) 
1829             $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1830         $noty .= "</tr>";
1831     }
1832
1833     // Total points.
1834     $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1835     for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) 
1836         $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1837     $noty .= "</tr></table>";
1838
1839     if ($table->old_reason != "") {
1840         $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1841     }
1842
1843     if ($table->old_win != -1) {
1844         log_main("TABLE_OLD_WIN:".$table->old_win);
1845         $win = $table->player[$table->old_win];
1846         log_main("TABLE_OLD_FRIEND:".$table->old_friend);
1847         $fri = $table->player[$table->old_friend];
1848
1849         $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1850
1851         if ($win != $fri) {
1852             /* 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" */
1853       
1854             $noty .= sprintf($mlang_bin5_bin5['info_part'][$G_lang], 
1855                              xcape($bri->user[$win]->name),
1856                              xcape($bri->user[$fri]->name));
1857             if ($table->old_pnt == 120) {
1858                 $noty .= sprintf($mlang_bin5_bin5['info_capp'][$G_lang]);
1859             }
1860             else {
1861                 $noty .= sprintf($mlang_bin5_bin5['info_pnt'][$G_lang],
1862                                  ($table->old_asta_pnt > 61 ? $mlang_bin5_bin5['info_alea'][$G_lang].$table->old_asta_pnt :
1863                                   $mlang_bin5_bin5['info_more'][$G_lang]), $table->old_pnt,
1864                                  ($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])));
1865             }
1866         }
1867         else {
1868             $noty .= sprintf($mlang_bin5_bin5['info_alon'][$G_lang],
1869                              xcape($bri->user[$win]->name));
1870             if ($table->old_pnt == 120) {
1871                 $noty .= sprintf($mlang_bin5_bin5['info_acap'][$G_lang]);
1872             }
1873             else {
1874                 $noty .= sprintf($mlang_bin5_bin5['info_apnt'][$G_lang],
1875
1876                                  ($table->old_asta_pnt > 61 ? $mlang_bin5_bin5['info_alea'][$G_lang].$table->old_asta_pnt :
1877                                   $mlang_bin5_bin5['info_more'][$G_lang]), $table->old_pnt,
1878
1879                                  ($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])));
1880             }
1881         }
1882         if (($table->old_mult + asta2mult($table->old_asta_pnt)) > 1) {
1883             $noty .= sprintf($mlang_bin5_bin5['info_omul'][$G_lang], multoval($table->old_mult + asta2mult($table->old_asta_pnt)));
1884         }
1885         $noty .= "<hr><br>";
1886     }
1887     /* MLANG: "Fai <b>tu</b> il mazzo,", "Il mazzo a <b>$unam</b>," */
1888     if ($table->mazzo == $table_pos) 
1889         $noty .= $mlang_bin5_bin5['info_yshuf'][$G_lang];
1890     else {
1891         $unam = xcape($bri->user[$table->player[$table->mazzo]]->name);
1892         $noty .= sprintf($mlang_bin5_bin5['info_shuf'][$G_lang], $unam);
1893     }
1894
1895     if ($user->subst == 'asta') {
1896         if ($table->asta_win == -1)  // auction case
1897             $curplayer = $table->gstart % BIN5_PLAYERS_N;
1898         else 
1899             $curplayer = $table->asta_win;
1900     }
1901     else if ($user->subst == 'game') {
1902         $curplayer = ($table->gstart + $table->turn) % BIN5_PLAYERS_N;
1903     }
1904
1905     /* MLANG: " tocca a <b>te</b> giocare.", " tocca a <b>$unam</b> giocare.", " La partita vale <b>%s</b>.", "torna alla partita" */
1906     if ($curplayer == $table_pos) {
1907         $noty .= $mlang_bin5_bin5['info_yturn'][$G_lang];
1908     }
1909     else {
1910         $unam = xcape($bri->user[$table->player[$curplayer]]->name);
1911         $noty .= sprintf($mlang_bin5_bin5['info_turn'][$G_lang], $unam);
1912     }
1913   
1914     if (($table->mult + asta2mult($table->asta_pnt)) > 1) {
1915         $noty .= sprintf($mlang_bin5_bin5['info_mult'][$G_lang], multoval($table->mult + asta2mult($table->asta_pnt)));
1916     }
1917     $noty .= "<hr><br>";
1918     $ret .= show_notify($noty, 3000, $mlang_bin5_bin5['btn_bkgame'][$G_lang], 500, 400);
1919     /* NOTE: show_notify($noty, 3000, "torna alla partita", 500, 
1920      *                   130 + ($table->points_n > 0 ? 50 : 0) + 
1921      *                   (120 * ($table->points_n / MAX_POINTS)));
1922      *       will be used when we refact notify js function following 
1923      *       photoo class logic 
1924      */ 
1925   
1926     return ($ret);
1927 }
1928
1929 function table_wellcome($user)
1930 {
1931     GLOBAL $table_wellarr, $G_lang;
1932     $ret = "";
1933
1934     for ($i = 0 ; $i < count($table_wellarr[$G_lang]) ; $i++)
1935         $ret .= sprintf('chatt_sub("%s", [2, "ChanServ: "],"%s");', "", str_replace('"', '\"', $table_wellarr[$G_lang][$i]));
1936
1937     return ($ret);
1938 }
1939
1940
1941 function briscola_show($bri, $table, $user)
1942 {
1943     GLOBAL $G_lang, $mlang_bin5_bin5;
1944     $ptnadd = "";
1945     $ret = "";
1946
1947     if ($table->asta_card == 9) 
1948         $ptnadd = sprintf($mlang_bin5_bin5['call_wptn'][$G_lang], $table->asta_pnt);
1949   
1950     /* text of caller cell */
1951     if ($user->table_pos == $table->asta_win) {
1952         $prestr = sprintf('$("callerinfo").innerHTML = "%s";', $mlang_bin5_bin5['call_ycall'][$G_lang]);
1953         $ret .= sprintf($prestr, $ptnadd);
1954     }
1955     else {
1956         $prestr = sprintf('$("callerinfo").innerHTML = "%s";', $mlang_bin5_bin5['call_call'][$G_lang]);
1957         $ret .= sprintf($prestr, 
1958                         xcape($bri->user[$table->player[$table->asta_win]]->name), $ptnadd);
1959     }
1960     $ret .= sprintf('set_iscalling(%d);', ($table->asta_win - $user->table_pos + BIN5_PLAYERS_N) % BIN5_PLAYERS_N);
1961
1962     $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1963                     $table->asta_win);
1964     $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1965     $ret .= sprintf('$("caller").style.visibility = "visible";');
1966     $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1967     $ret .= sprintf('$("astalascio").style.visibility = "";');
1968     $ret .= sprintf('$("asta").style.visibility = "hidden";');
1969     $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1970   
1971     return ($ret);
1972 }
1973
1974
1975 function game_result($asta_pnt, $pnt)
1976 {
1977     if ($asta_pnt == 61) {
1978         if ($pnt > 60)
1979             return (1);
1980         else if ($pnt == 60)
1981             return (0);
1982         else
1983             return (-1);
1984     }
1985     else {
1986         if ($pnt >= $asta_pnt)
1987             return (1);
1988         else
1989             return (-1);
1990     }
1991 }
1992
1993 function log_points($remote_addr, $curtime, $user, $where, $mesg) 
1994 {
1995     if (($fp = @fopen(LEGAL_PATH."/points.log", 'a')) != FALSE) {
1996         /* Unix time | session | nickname | IP | where was | mesg */
1997         fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
1998                             ($user->flags & USER_FLAG_AUTH ? 'A' : 'N'),
1999                             $user->name, $remote_addr, $where , $mesg));
2000         fclose($fp);
2001     }
2002 }
2003
2004 ?>