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