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