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