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