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