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