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