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