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