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