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