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