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