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