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