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