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