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