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