update indentation
[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     function User() {
433     }
434     
435     /* CREATE NOT USED
436        function create($name, $sess, $stat = "", $subst = "", $table = -1, $ip="0.0.0.0") {
437        if (($thiz =& new User()) == FALSE)
438        return (FALSE);
439      
440        $thiz->asta_card = -2;
441        $thiz->asta_pnt  = -1;
442        $thiz->handpt = -1;
443        $thiz->exitislock = TRUE;
444        $thiz->privflags = 0;
445      
446        return ($thiz);
447        }
448     */
449     
450     function parentcopy(&$from)
451     {
452         parent::copy($from);
453     }
454     
455     function copy(&$from)
456     {
457         $this->parentcopy($from);
458         
459         $this->asta_card  = $from->asta_card;
460         $this->asta_pnt   = $from->asta_pnt;
461         $this->handpt     = $from->handpt;
462         $this->exitislock = $from->exitislock;
463         $this->privflags  = $from->privflags;
464     }
465     
466     /* CLONE NOT USED
467        function myclone(&$from)
468        {
469        if (($thiz =& new User()) == FALSE)
470        return (FALSE);
471      
472        $thiz->copy($from);
473      
474        return ($thiz);
475        } 
476     */
477     
478     function spawn($from, $table, $table_pos)
479     {
480         GLOBAL $CO_bin5_pref_ring_endauct;
481         
482         if (($thiz = new Bin5_user()) == FALSE)
483             return (FALSE);
484         
485         $thiz->parentcopy($from);
486         
487         /* NOTE: at this moment idx and table_pos fields have the same value 
488            but diffentent functions, we keep them separated for a while */
489         $thiz->idx        = $table_pos;
490         $thiz->asta_card  = -2;
491         $thiz->asta_pnt   = -1;
492         $thiz->handpt     = -1;
493         $thiz->exitislock = TRUE;
494         
495         log_wr("Bin5 constructor");
496         
497         $this->privflags  = ($CO_bin5_pref_ring_endauct == "true" ? BIN5_USER_FLAG_RING_ENDAUCT : 0) | 0;
498         
499         $thiz->table_orig = $table;
500         $thiz->table      = 0;
501         $thiz->table_pos  = $table_pos;
502         
503         $thiz->step_inc();
504
505         return ($thiz);
506     }
507
508     function step_set($step) 
509     {
510         $this->step = $step & 0x7fffffff;
511         
512         return TRUE;
513     }
514     
515     function step_inc($delta = 1) {
516         $this->step += $delta;
517         /* modularization because unpack() not manage unsigned 32bit int correctly */
518         $this->step &= 0x7fffffff;
519         
520         return (TRUE);
521     }
522
523     static function load_step($tab_id, $sess)
524     {
525         $fp = FALSE;
526         do {
527             if (validate_sess($sess) == FALSE)
528                 break;
529             
530             if (file_exists(BIN5_PROXY_PATH."/table".$tab_id) == FALSE)
531                 mkdir(BIN5_PROXY_PATH."/table".$tab_id, 0775, TRUE);
532             if (($fp = @fopen(BIN5_PROXY_PATH."/table".$tab_id."/".$sess.".step", 'rb')) == FALSE)
533                 break;
534             if (($s = fread($fp, 8)) == FALSE)
535                 break;
536             if (mb_strlen($s, "ASCII") != 8)
537                 break;
538             $arr = unpack('Ls/Li', $s);
539             fclose($fp);
540             
541             // log_rd2("A0: ".$arr[0]."  A1: ".$arr[1]);
542             return ($arr);
543         } while (0);
544         
545         if ($fp != FALSE)
546             fclose($fp);
547         
548         log_rd2("STEP_GET [".$sess."]: return false ");
549         
550         return (FALSE);
551     }
552
553     function save_step() 
554     {
555         do {
556             if (validate_sess($this->sess) == FALSE)
557                 break;
558             if (file_exists(BIN5_PROXY_PATH."/table".$this->table_orig) == FALSE)
559                 mkdir(BIN5_PROXY_PATH."/table".$this->table_orig, 0775, TRUE);
560             if (($fp = @fopen(BIN5_PROXY_PATH."/table".$this->table_orig."/".$this->sess.".step", 'w')) == FALSE)
561                 break;
562             fwrite($fp, pack("LL",$this->step, $this->idx));
563             fclose($fp);
564             
565             log_main("step_set [".$this->sess. "] [".$this->step."]"); 
566             
567             return (TRUE);
568         } while (0);
569         
570         return (FALSE);
571     }
572     
573     static function unproxy_step($tab_id, $sess)
574     {
575         log_rd2("UNPROXY: ".BIN5_PROXY_PATH."/table".$tab_id."/".$sess.".step");
576         if (file_exists(BIN5_PROXY_PATH."/table".$tab_id) == FALSE)
577             return;
578
579         @unlink(BIN5_PROXY_PATH."/table".$tab_id."/".$sess.".step");
580     }
581     
582     static function load_data($tab_id, $id, $sess) 
583     {
584         log_load("Bin5_user::load_data: tab_id [".$tab_id."] id [".$id."] sess [".($sess == FALSE ? "FALSE" : $sess)."] ");
585         
586         do {
587             if (($tok = @ftok(FTOK_PATH."/bin5/table".$tab_id."/user".$id, "B")) == -1) {
588                 log_main("ftok failed");
589                 break;
590             }
591             
592             if (($shm_sz = sharedmem_sz($tok)) == -1) {
593                 log_main("shmop_open failed");
594             }
595             
596             if ($shm_sz == -1)
597                 $shm_sz = SHM_DIMS_U_MIN;
598             
599             if ($shm = shm_attach($tok, $shm_sz)) {
600                 if (($user = @shm_get_var($shm, $tok)) == FALSE) {
601                     break;
602                 }
603                 
604                 if ($sess != FALSE && $user->sess != $sess) {
605                     break;
606                 }
607                 log_only("user ==  ".($user == FALSE ?   "FALSE" : "TRUE")."  user ===  ".($user === FALSE ? "FALSE" : "TRUE")."  user isset ".(isset($user) ?   "TRUE" : "FALSE"));
608                 
609                 if ($user == FALSE) {
610                     log_only("INIT MAIN DATA");
611                     
612                     // SHSPLIT FIXME: init_data for User class ??
613                     $user = User::create($id, "", "");
614                     if (@shm_put_var($shm, $tok, $user) == FALSE) {
615                         log_shme("Bin5_user::save_data2");
616
617                         log_only("PUT_VAR FALLITA ".strlen(serialize($user)));
618                         log_only(serialize($user));
619                     }
620                 }
621                 else {
622                     if ($sess != FALSE) {
623                         // This part isn't strictly required but is good to verify
624                         // the coerence of cached and User class saved value of step field.
625                         $old_step = $user->step;
626                         $arr = Bin5_user::load_step($tab_id, $sess);
627                         $user->step = $arr['s'];
628                         if ($old_step != $user->step) {
629                             log_crit("Bin5:: steps are diffetents User->step ".$user->step." Old_step: ".$old_step);
630                         }
631
632                     }
633                 }
634                 
635                 $user->shm_sz = $shm_sz;
636                 
637                 shm_detach($shm);
638             }
639             
640             //  
641             // SHSPLIT: load users from the shared memory
642             //
643             return ($user);
644         } while (0);
645         
646         log_crit("Bin5_user::load_data:ret FALSE");
647         
648         return (FALSE);
649     }
650
651     static function save_data($user, $tab_id, $id) 
652     {
653         GLOBAL $sess;
654       
655         $shm =   FALSE;
656       
657         if (($tok = @ftok(FTOK_PATH."/bin5/table".$tab_id."/user".$id, "B")) == -1) {
658             return (FALSE);
659         }
660         while ($user->shm_sz < SHM_DIMS_U_MAX) {
661             if (($shm = shm_attach($tok, $user->shm_sz)) == FALSE)
662                 break;
663           
664             // log_only("PUT_VAR DI ".strlen(serialize($user)));
665             if (@shm_put_var($shm, $tok, $user) != FALSE) {
666                 shm_detach($shm);
667                 $user->save_step();
668                 log_main("User[".$id."] saved.");
669
670                 log_shme("Bin5_user::save_data");
671
672                 return (TRUE);
673             }
674             if (shm_remove($shm) === FALSE) {
675                 log_only("REMOVE FALLITA");
676                 break;
677             }
678             shm_detach($shm);
679             $user->shm_sz += SHM_DIMS_U_DLT;
680         } 
681       
682         if ($shm)
683             shm_detach($shm);
684       
685         return (FALSE);
686     }
687
688     function destroy_data($tab_id) 
689     {
690         do {
691             if (($tok = @ftok(FTOK_PATH."/bin5/table".$tab_id."/user".$this->table_pos, "B")) == -1) {
692                 log_crit("BIN5 USER DATA REMOVE FAILED 1 [".FTOK_PATH."/bin5/table".$tab_id."/user".$this->table_pos."]");
693                 break;
694             }
695           
696             if (($shm = @shmop_open($tok, 'a', 0, 0)) == FALSE) {
697                 log_crit("BIN5 USER DATA REMOVE FAILED 2");
698                 break;
699             }
700             if (shmop_delete($shm) == 0) {
701                 log_crit("BIN5 USER DATA REMOVE FAILED 3");
702                 break;
703             }
704             $shm = FALSE;
705
706             log_main("BIN5 USER DATA DESTROY SUCCESS");
707           
708             // log_main("QUI CI ARRIVA [".$bri->user[0]->name."]");
709             $ret = TRUE;
710         } while (0);
711       
712         if ($shm)
713             shm_detach($shm);
714       
715         return ($ret);
716     }
717
718 } // end class Bin5_user
719
720
721
722 class Bin5 {
723     static $delta_t = array();
724
725     var $user;
726     var $table;
727     var $comm; // commands for many people
728     var $step; // current step of the comm array
729     // externalized var $garbage_timeout;
730     var $shm_sz;
731     
732     var $table_idx;
733     var $table_token;
734     
735     var $the_end;
736     var $tok;
737
738     function Bin5 ($room, $table_idx, $table_token) {
739         $this->user = array();
740         $this->table = array();
741         
742         $this->the_end = FALSE;
743         $this->shm_sz = BIN5_SHM_MIN;
744         if (($this->tok = @ftok(FTOK_PATH."/bin5/table".$table_idx."/table", "B")) == -1) {
745             echo "FTOK FAILED";
746             exit;
747         }
748         
749         $user  = $room->user;
750         $table = $room->table[$table_idx];
751         
752         log_wr("Bin5 constructor");
753         
754         for ($i = 0 ; $i < $table->player_n ; $i++) {
755             $user[$table->player[$i]]->table_token = $table_token;
756             $this->user[$i] = Bin5_user::spawn($user[$table->player[$i]], $table_idx, $i);
757         }
758         $this->table[0] = Bin5_table::spawn(&$table);
759         
760         log_main("TABLE_OLD_WIN - Bin5:".$this->table[0]->old_win);
761         
762         $this->table_idx = $table_idx;
763         $this->table_token = $table_token;
764         Bin5::garbage_time_expire_set($table_idx, 0);
765         
766         log_wr("Bin5 constructor end");
767     }
768     
769
770     function get_user($sess, &$idx)
771     {
772         GLOBAL $PHP_SELF;
773         
774         if (validate_sess($sess)) {
775             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
776                 if (strcmp($sess, $this->user[$i]->sess) == 0) {
777                     // find it
778                     $idx = $i;
779                     $ret = &$this->user[$i];
780                     return ($ret);
781                 }
782             }
783             log_main(sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
784             // for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) 
785             // log_main(sprintf("get_user: Wrong sess compared with [%s]",$this->user[$i]->sess));
786         }
787         else {
788             log_main(sprintf("get_user: Wrong strlen [%s]",$sess));
789         }
790         
791         return (FALSE);
792     }
793     
794     
795     function garbage_manager($force)
796     {
797         GLOBAL $G_base;
798         
799         /* Garbage collector degli utenti in timeout */
800         $ismod = FALSE;
801         $curtime = time();
802         // externalized if ($force || $this->garbage_timeout < $curtime) {
803         if ($force || Bin5::garbage_time_is_expired($this->table_idx, $curtime)) {
804             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
805                 $user_cur = $this->user[$i];
806                 if ($user_cur->sess == "" || 
807                     ($user_cur->stat == 'table' && ($user_cur->subst == 'shutdowned' || $user_cur->subst == 'shutdowner')))
808                     continue;
809                 
810                 if ($user_cur->lacc + EXPIRE_TIME_RD < $curtime) { // Auto logout dell'utente
811                     log_rd2($user_cur->sess." bin5 AUTO LOGOUT.");
812                     
813                     if ($user_cur->stat == 'table') {
814                         log_auth($user_cur->sess," bin5 Autologout session.");
815                         
816                         /* SI DELEGA AL garbage_manager principale LA RIMOZIONE DELL'UTENTE 
817                            
818                            $tmp_sess = $user_cur->sess;
819                            $user_cur->sess = "";
820                            Bin5_user::step_unproxy($tmp_sess);
821                            $user_cur->name = "";
822                            $user_cur->the_end = FALSE;
823                            
824                         */
825                         
826                         /* se gli altri utenti non erano d'accordo questo utente viene bannato */
827                         $remcalc = $this->table[0]->exitlock_calc(&$this->user, $user_cur->table_pos);
828                         if ($remcalc < 3) {
829                             require_once("${G_base}Obj/hardban.phh");
830                             Hardbans::add(($user_cur->flags & USER_FLAG_AUTH ? $user_cur->name : FALSE),
831                                           $user_cur->ip, $user_cur->sess, $user_cur->laccwr + BAN_TIME);
832                         }
833                         //      $user->bantime = $user->laccwr + BAN_TIME;
834                         
835                         $this->table_wakeup($user_cur);
836                     }
837                 }
838             }
839             log_rd2($user_cur->sess." GARBAGE UPDATED!");
840             
841             // externalized $this->garbage_timeout = $curtime + GARBAGE_TIMEOUT;
842             Bin5::garbage_time_expire_set($this->table_idx, $curtime + GARBAGE_TIMEOUT);
843             
844             $ismod = TRUE;
845         }
846         
847         return ($ismod);
848     }
849     
850     // Bin5::load_data
851     static function load_data($table_idx, $table_token = "") 
852     {
853         $shm = FALSE;
854         
855         log_wr("TABLE_FTOK ".FTOK_PATH."/bin5/table".$table_idx."/table");
856         
857         do {
858             if (($tok = @ftok(FTOK_PATH."/bin5/table".$table_idx."/table", "B")) == -1) {
859                 log_main("ftok failed");
860                 break;
861             }
862             
863             if (($shm_sz = sharedmem_sz($tok)) == -1) {
864                 log_main("shmop_open failed");
865                 break;
866             }
867         
868             if (($shm = shm_attach($tok, $shm_sz)) == FALSE)
869                 break;
870
871             if (($bri = @shm_get_var($shm, $tok)) == FALSE) 
872                 break;
873
874             if ($table_token != "" && $bri->table_token != $table_token) {
875                 log_wr("bri->table_token: ".$bri->table_token."table_token: ".$table_token);
876                 break;
877             }
878             $bri->tok = $tok;
879
880             shm_detach($shm);
881       
882             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
883                 if (($bri->user[$i] = Bin5_user::load_data($table_idx, $i, FALSE)) == FALSE) {
884                     log_crit("Bin5_user::load_data failed");
885                     break;
886                 }
887             }
888             if ($i < BIN5_MAX_PLAYERS) {
889                 break;
890             }
891       
892             return ($bri); 
893         } while (FALSE);
894
895         if ($shm != FALSE)
896             shm_detach($shm);
897
898         log_wr("briskin5 load_data failed");
899     
900         return (FALSE);
901     }
902   
903
904
905     function save_data($bri) 
906     {
907         GLOBAL $sess;
908       
909         $ret =   FALSE;
910         $shm =   FALSE;
911       
912         log_main("SAVE BRISKIN5 DATA");
913       
914         if (!isset($bri->tok))
915             return (FALSE);
916       
917         $user_park = array();
918         for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
919             $user_park[$i] = $bri->user[$i];
920             $bri->user[$i] = FALSE;
921         }
922       
923         while ($bri->shm_sz < BIN5_SHM_MAX) {
924             if (($shm = shm_attach($bri->tok, $bri->shm_sz)) == FALSE)
925                 break;
926           
927             if (@shm_put_var($shm, $bri->tok, $bri) != FALSE) {
928
929                 log_shme("Bin5::save_data");
930
931                 $ret = TRUE;
932                 break;
933             }
934             if (shm_remove($shm) === FALSE) {
935                 log_only("REMOVE FALLITA");
936                 break;
937             }
938             shm_detach($shm);
939             $bri->shm_sz += BIN5_SHM_DLT;
940         } 
941       
942         if ($shm)
943             shm_detach($shm);
944       
945         // SHSPLIT: reattach users to the room class
946         for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
947             Bin5_user::save_data($user_park[$i], $bri->table_idx, $i);
948             $bri->user[$i] = $user_park[$i];
949         }
950         log_load("FINISH: ".($ret == TRUE ? "TRUE" : "FALSE"));
951       
952         return ($ret);
953     }
954   
955
956
957     function destroy_data() 
958     {
959         GLOBAL $sess;
960
961         $ret =   FALSE;
962         $shm =   FALSE;
963         log_main("DESTROY BRISKIN5 DATA");
964     
965         do {
966             log_main("DESTROY2 BRISKIN5 DATA [".$this->table_idx."]");
967             for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
968                 $this->user[$i]->destroy_data($this->table_idx);
969                 Bin5_user::unproxy_step($this->table_idx, $this->user[$i]->sess);
970             }
971             if (($tok = @ftok(FTOK_PATH."/bin5/table".$this->table_idx."/table", "B")) == -1) 
972                 break;
973
974             if (($shm = @shmop_open($tok, 'a', 0, 0)) == FALSE)
975                 break;
976       
977             if (shmop_delete($shm) == 0) {
978                 log_only("REMOVE FALLITA ");
979                 break;
980             }
981    
982             $shm = FALSE;
983             log_main("DESTROY2 BRISKIN5 DATA SUCCESS");
984       
985             // log_main("QUI CI ARRIVA [".$bri->user[0]->name."]");
986             $ret = TRUE;
987         } while (0);
988     
989         if ($shm)
990             shm_detach($shm);
991     
992         return ($ret);
993     }
994
995     static function lock_data($is_exclusive, $table_idx)
996     {
997         if (($res = file_lock(FTOK_PATH."/bin5/table".$table_idx."/table", $is_exclusive)) != FALSE) {
998             self::$delta_t = microtime(TRUE);
999             log_lock("LOCK   table [".$table_idx."]         [".self::$delta_t[$table_idx]."]");
1000           
1001             return (new Vect(array('res' => $res, 'tab' => $table_idx)));
1002         }
1003       
1004         return (FALSE);
1005     }
1006
1007   
1008     static function unlock_data($res_vect)
1009     {
1010         GLOBAL $sess; 
1011
1012         $res = $res_vect->getbyid('res');
1013         $tab = $res_vect->getbyid('tab');
1014
1015         log_lock("UNLOCK table [".$tab."]         [".(microtime(TRUE) - (self::$delta_t[$tab]))."]");
1016
1017         file_unlock($res);
1018     }
1019
1020
1021     function chatt_send($user, $mesg)
1022     {
1023         GLOBAL $mlang_brisk, $G_lang;
1024
1025         if ($user->stat == 'table') {
1026             $table = &$this->table[$user->table];
1027         }
1028     
1029         $user_mesg = substr($mesg,6);
1030     
1031         $curtime = time();
1032     
1033         $dt = date("H:i ", $curtime);
1034         if (strncmp($user_mesg, "/nick ", 6) == 0) {
1035             log_main($user->sess." chatt_send BEGIN");
1036
1037             if (($name_new = validate_name(substr($user_mesg, 6))) == FALSE) {
1038                 $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1039                 $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, $mlang_brisk['nickmust'][$G_lang]);
1040                 $user->step_inc();
1041
1042                 return;
1043             }
1044             $user_mesg = "COMMAND ".$user_mesg;
1045             // Search dup name
1046             // change
1047             // update local graph
1048             // update remote graphs
1049             for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1050                 $user_cur = $this->user[$i];
1051                 //      if ($user_cur->sess == '' || $user_cur->stat != 'room')
1052                 if ($user_cur->sess == '')
1053                     continue;
1054                 if (strcasecmp($user_cur->name, $name_new) == 0) {
1055                     $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1056
1057                     $premsg = sprintf($mlang_brisk['nickdupl'][$G_lang], xcape($name_new));
1058                     $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"%s");', $dt, NICKSERV, $premsg);
1059                     $user->step_inc();
1060                     break;
1061                 }
1062             }
1063             if ($i == BIN5_MAX_PLAYERS) {
1064                 if ($user->flags & USER_FLAG_AUTH && strcasecmp($user->name,$name_new) != 0) {
1065                     if ($this->table[$user->table]->auth_only == TRUE) {
1066                         $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
1067                         $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s", [2, "%s"],"<b>%s</b>");', $dt, NICKSERV, $mlang_brisk['authchan'][$G_lang]);
1068                         $user->step_inc();
1069                         return;
1070                     }
1071                     else {
1072                         $user->flags &= ~USER_FLAG_AUTH; // Remove auth if name changed
1073                     }
1074                 }
1075     
1076                 $user->name = $name_new;
1077
1078                 log_main($user->sess." chatt_send start set");
1079         
1080
1081                 for ($i = 0 ; $i < BIN5_MAX_PLAYERS ; $i++) {
1082                     log_main($user->sess." chatt_send set loop");
1083           
1084                     $user_cur = &$this->user[$i];
1085                     if ($user_cur->sess == '')
1086                         continue;
1087           
1088                     if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
1089                         $table = &$this->table[$user->table];
1090             
1091                         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1092                         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('set_names([%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"]); ',
1093                                                                              $this->user[$table->player[($user_cur->table_pos) % BIN5_PLAYERS_N]]->flags,
1094                                                                              xcape($this->user[$table->player[($user_cur->table_pos) % BIN5_PLAYERS_N]]->name),
1095
1096                                                                              $this->user[$table->player[($user_cur->table_pos+1) % BIN5_PLAYERS_N]]->flags,
1097                                                                              xcape($this->user[$table->player[($user_cur->table_pos+1) % BIN5_PLAYERS_N]]->name),
1098
1099                                                                              $this->user[$table->player[($user_cur->table_pos+2) % BIN5_PLAYERS_N]]->flags,
1100                                                                              xcape($this->user[$table->player[($user_cur->table_pos+2) % BIN5_PLAYERS_N]]->name),
1101
1102                                                                              (BIN5_PLAYERS_N == 3 ? 0:  $this->user[$table->player[($user_cur->table_pos+3) % BIN5_PLAYERS_N]]->flags),
1103                                                                              (BIN5_PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3) % BIN5_PLAYERS_N]]->name)),
1104
1105                                                                              (BIN5_PLAYERS_N == 3 ? 0:  $this->user[$table->player[($user_cur->table_pos+4) % BIN5_PLAYERS_N]]->flags),
1106                                                                              (BIN5_PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4) % BIN5_PLAYERS_N]]->name)));
1107                         if ($user_cur == $user) {
1108                             $user_cur->comm[$user_cur->step % COMM_N] .= $user_cur->myname_innerHTML();
1109                         }
1110                         $user_cur->step_inc();
1111                     }
1112                 }
1113             }
1114         }
1115         else {
1116             for ($i = 0 ; $i < ($user->stat == 'room' ? BIN5_MAX_PLAYERS : BIN5_PLAYERS_N) ; $i++) {
1117                 if ($user->stat == 'room') {
1118                     $user_cur = &$this->user[$i];
1119                     if ($user_cur->sess == '' || $user_cur->stat != 'room')
1120                         continue;
1121                 }
1122                 else {
1123                     $user_cur = &$this->user[$table->player[$i]];
1124                 }
1125         
1126                 $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
1127                 $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s", [%d, "%s"],"%s");',
1128                                                                      $dt, $user->flags, xcape($user->name), xcape($user_mesg));
1129                 $user_cur->step_inc();
1130             }
1131             log_legal($curtime, 'xxx', $user, ($user->stat == 'room' ? 'room' : 'table '.$user->table_orig),$user_mesg);
1132         }
1133     }
1134
1135     function table_wakeup($user)
1136     {
1137         $table = &$this->table[0];
1138
1139         log_main("BIN5_WAKEUP begin function table  stat: ".$user->stat."  subst: ".$user->subst);
1140
1141         $curtime = time();
1142
1143         log_main("BIN5_WAKEUP from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
1144     
1145         for ($i = 0 ; $i < $table->player_n ; $i++) {
1146             $user_cur = &$this->user[$i];
1147             log_main("PREIMPOST INLOOP name: ".$user_cur->name);
1148       
1149             if ($user_cur == $user)
1150                 $user_cur->subst = "shutdowner";
1151             else
1152                 $user_cur->subst = "shutdowned";
1153             $user_cur->laccwr = $curtime;
1154
1155             $ret = "gst.st = ".($user_cur->step+1)."; ";
1156             $ret .= 'gst.st_loc++; hstm.stop(); window.onbeforeunload = null; window.onunload = null; document.location.assign("../index.php");|';
1157
1158             log_wr($user_cur->sess." BIN5_WAKEUP: ".$ret);
1159             $user_cur->comm[$user_cur->step % COMM_N] = $ret;
1160             $user_cur->step_inc();
1161         }
1162
1163         $this->the_end = TRUE;
1164     }
1165   
1166     /*
1167      *  If all players are freezed the room garbage_manager clean up table and users.
1168      */ 
1169     function is_abandoned() 
1170     {
1171         $is_ab = TRUE;
1172         $curtime = time();
1173
1174         $table = &$this->table[0];
1175
1176         for ($i = 0 ; $i < $table->player_n ; $i++) {
1177             $user_cur = &$this->user[$i];
1178
1179             if ($user_cur->lacc + (EXPIRE_TIME_RD * 2) >= $curtime) { 
1180                 $is_ab = FALSE;
1181                 break;
1182             }
1183         }
1184
1185         return ($is_ab);
1186     }
1187
1188
1189     static function garbage_time_is_expired($tab_id, $tm) 
1190     {
1191         $ret = TRUE;
1192         $fp = FALSE;
1193         do {
1194             if (file_exists(BIN5_PROXY_PATH."/table".$tab_id) == FALSE)
1195                 mkdir(BIN5_PROXY_PATH."/table".$tab_id, 0775, TRUE);
1196             if (($fp = @fopen(BIN5_PROXY_PATH."/table".$tab_id."/garbage_time.expired", 'rb')) == FALSE)
1197                 break;
1198             if (($s = fread($fp, 4)) == FALSE)
1199                 break;
1200             if (mb_strlen($s, "ASCII") != 4)
1201                 break;
1202             $arr = unpack('Le', $s);
1203             if ($arr['e'] > $tm)
1204                 $ret = FALSE;
1205         } while (0);
1206       
1207         if ($fp != FALSE)
1208             fclose($fp);
1209       
1210         log_rd2("END: return ".($ret ? "TRUE" : "FALSE"));
1211       
1212         return ($ret);
1213     }
1214
1215     static function garbage_time_expire_set($tab_id, $tm) 
1216     {
1217         do {
1218             if (file_exists(BIN5_PROXY_PATH."/table".$tab_id) == FALSE)
1219                 mkdir(BIN5_PROXY_PATH."/table".$tab_id, 0775, TRUE);
1220             if (($fp = @fopen(BIN5_PROXY_PATH."/table".$tab_id."/garbage_time.expired", 'wb')) == FALSE)
1221                 break;
1222             fwrite($fp, pack("L",$tm));
1223             fclose($fp);
1224           
1225             return (TRUE);
1226         } while (0);
1227       
1228         return (FALSE);
1229     }
1230
1231 } // end class Bin5
1232
1233 function locshm_exists($tok)
1234 {
1235     // return (TRUE);
1236
1237     if (($id = @shmop_open($tok,"a", 0, 0)) == FALSE) {
1238         log_main($tok." SHM NOT exists");
1239
1240         return (FALSE);
1241     }
1242     else {
1243         shmop_close($id);
1244         log_main($tok." SHM exists");
1245
1246         return (TRUE);
1247     }
1248     
1249 }
1250
1251 function asta2mult($asta_pnt)
1252
1253     if ($asta_pnt > 110) 
1254         return (5);
1255     else if ($asta_pnt > 100) 
1256         return (4);
1257     else if ($asta_pnt > 90) 
1258         return (3);
1259     else if ($asta_pnt > 80) 
1260         return (2);
1261     else if ($asta_pnt > 70) 
1262         return (1);
1263     else
1264         return (0);
1265 }
1266
1267 // rendiamo qui l'elenco dei punti come return della func
1268 function calculate_points(&$table)
1269 {
1270     GLOBAL $G_all_points; 
1271
1272     $ret = array();
1273     $pro = 0;
1274
1275     if ($table->asta_pnt == 60)
1276         $table->asta_pnt = 61;
1277
1278     $table->old_reason = "";
1279     $table->old_win = $table->asta_win;
1280     $table->old_friend = $table->friend;
1281     $table->old_asta_pnt = $table->asta_pnt;
1282     $table->old_mult = $table->mult;
1283
1284     for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1285         // for ($i = 0 ; $i < 40 ; $i++) {
1286         $ctt = $table->card[$i]->value % 10;
1287         $own = $table->card[$i]->owner;
1288         if ($own == $table->asta_win || $own == $table->friend) 
1289             $pro += $G_all_points[$ctt];
1290     }
1291
1292     log_wr(sprintf("PRO: [%d]", $pro));
1293
1294   
1295     if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1296         $table->points[$table->points_n % MAX_POINTS] = array();
1297         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1298             $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1299             $ret[$i] = 0;
1300         }
1301         $table->points_n++;
1302         $table->old_pnt = $pro;
1303         $table->mult += 1;
1304
1305         return($ret);
1306     }
1307
1308     if ($pro >= $table->asta_pnt) 
1309         $sig = 1;
1310     else
1311         $sig = -1;
1312
1313     $gamult = asta2mult($table->asta_pnt);
1314   
1315     $table->points[$table->points_n % MAX_POINTS] = array();
1316     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1317         if ($i == $table->asta_win) 
1318             $pt = ($i == $table->friend ? 4 : 2);
1319         else if ($i == $table->friend) 
1320             $pt = 1;
1321         else
1322             $pt = -1;
1323     
1324     
1325
1326         log_wr(sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1327
1328         $pt = $pt * $sig * ($gamult + $table->mult) * ($pro == 120 ? 2 : 1);
1329
1330         log_wr(sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
1331     
1332         $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
1333         $table->total[$i] += $pt;
1334         $ret[$i] = $pt;
1335     }
1336     $table->points_n++;
1337     $table->old_pnt = $pro;
1338     $table->mult = 1;
1339   
1340     return($ret);
1341 }
1342
1343 /* show table 
1344    is_transition (is from room to table ?)
1345    is_again      (is another game)
1346
1347    Examples                    of $is_transition, $is_again:
1348    from reload of the page:              FALSE, FALSE
1349    from sitdown in room:                  TRUE, FALSE
1350    from table: asta cmd e tutti passano:  TRUE, TRUE
1351    from table: fine partita:              TRUE, TRUE
1352 */
1353 function show_table(&$room, &$user, $sendstep, $is_transition, $is_again)
1354 {
1355     $table_idx = $user->table;
1356     $table     = $room->table[$table_idx];
1357     $table_pos = $user->table_pos;
1358
1359     $ret = "table_init();";
1360     $ret .= $table->exitlock_show(&$room->user, $table_pos);
1361     if (!$is_again) {
1362         /* GENERAL STATUS */
1363         $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1364                          $sendstep, $user->stat, $user->subst, $table_pos);
1365
1366         log_rd(sprintf( 'SHOW_TABLE: gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;', $sendstep, $user->stat, $user->subst, $table_pos));
1367
1368         /* BACKGROUND */
1369         $ret .= "background_set();";
1370     
1371         /* USERS INFO */
1372         $ret .= $user->myname_innerHTML();
1373         $ret .= sprintf('set_names([%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"], [%d, "%s"]); ',
1374                         $room->user[$table->player[($table_pos) % BIN5_PLAYERS_N]]->flags,
1375                         xcape($room->user[$table->player[($table_pos) % BIN5_PLAYERS_N]]->name),
1376
1377                         $room->user[$table->player[($table_pos+1) % BIN5_PLAYERS_N]]->flags,
1378                         xcape($room->user[$table->player[($table_pos+1) % BIN5_PLAYERS_N]]->name),
1379
1380                         $room->user[$table->player[($table_pos+2) % BIN5_PLAYERS_N]]->flags,
1381                         xcape($room->user[$table->player[($table_pos+2) % BIN5_PLAYERS_N]]->name),
1382
1383                         (BIN5_PLAYERS_N == 3 ? 0 : $room->user[$table->player[($table_pos+3) % BIN5_PLAYERS_N]]->flags),
1384                         (BIN5_PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+3) % BIN5_PLAYERS_N]]->name)),
1385
1386                         (BIN5_PLAYERS_N == 3 ? 0 : $room->user[$table->player[($table_pos+4) % BIN5_PLAYERS_N]]->flags),
1387                         (BIN5_PLAYERS_N == 3 ? "" :  xcape($room->user[$table->player[($table_pos+4) % BIN5_PLAYERS_N]]->name)));
1388     }
1389     /* NOTIFY FOR THE CARD MAKER */
1390     if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1391         $ret .= show_table_info(&$room, &$table, $table_pos);
1392     }
1393     if (!$is_again) 
1394         $ret .= table_wellcome($user);
1395
1396     if ($is_transition && !$is_again) { // appena seduti al tavolo, play della mucca
1397         $ret .= playsound("cow.mp3");
1398     }
1399
1400
1401     /* CARDS */
1402     if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1403         $ret .= "|";
1404     
1405         for ($i = 0 ; $i < 8 ; $i++) {
1406             for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) {
1407                 $ct = 0;
1408                 for ($o = 0 ; $o < (BIN5_PLAYERS_N == 5 ? 40 : 24) && $ct < $i+1 ; $o++) {
1409                     // for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1410                     if ($table->card[$o]->owner == (($e + $table->gstart) % BIN5_PLAYERS_N)) {
1411                         $ct++;
1412                         if ($ct == $i+1)
1413                             break;
1414                     }
1415                 }
1416                 log_rd("O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1417         
1418                 $ret .= sprintf( ' card_send(%d,%d,%d,%8.2f,%d);|', ($table->gstart + $e) % BIN5_PLAYERS_N, 
1419                                  $i, ((($e + BIN5_PLAYERS_N - $table_pos + $table->gstart) % BIN5_PLAYERS_N) == 0 ?
1420                                       $table->card[$o]->value : -1), 
1421                                  ($i == 7 && $e == (BIN5_PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1422             }
1423         }    
1424     }
1425     else {
1426         $taked  = array(0,0,0,0,0);
1427         $inhand = array(0,0,0,0,0);
1428         $ontabl  = array(-1,-1,-1,-1,-1);
1429         $cards  = array();
1430
1431         for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1432             // for ($i = 0 ; $i < 40 ; $i++) {
1433             if ($table->card[$i]->stat == 'hand') {
1434                 if ($table->card[$i]->owner == $table_pos) {
1435                     $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1436                 }
1437                 $inhand[$table->card[$i]->owner]++;
1438             }
1439             else if ($table->card[$i]->stat == 'take') {
1440                 log_main("Card taked: ".$table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1441                 $taked[$table->card[$i]->owner]++;
1442             }
1443             else if ($table->card[$i]->stat == 'table') {
1444                 $ontabl[$table->card[$i]->owner] = $i;
1445             }
1446         }
1447         $logg = "\n";
1448         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1449             $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1450         }
1451         log_main("Stat table: ".$logg);
1452
1453         /* Set ours cards. */
1454         $oursarg = "";
1455         for ($i = 0 ; $i < $inhand[$table_pos] ; $i++) 
1456             $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1457         for ($i = $inhand[$table_pos] ; $i < 8 ; $i++) 
1458             $oursarg .= ($i == 0 ? "" : ", ")."-1";
1459         $ret .= sprintf('card_setours(%s);', $oursarg);
1460
1461         /* Dispose all cards */
1462         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1463             /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1464             $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1465                             ($inhand[$i] <= 8 ? $inhand[$i] : 8)  , $taked[$i]);
1466
1467             if ($ontabl[$i] != -1) {
1468                 $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1469                                 $table->card[$ontabl[$i]]->value, 
1470                                 $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1471             }
1472         }
1473     }
1474
1475     /* Show auction */
1476     if ($user->subst == 'asta') {
1477
1478         /* show users auction status */
1479         $showst = "";
1480         for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1481             $user_cur = &$room->user[$table->player[$i]];
1482             $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1483                                ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1484         }
1485         if (BIN5_PLAYERS_N == 3)
1486             $showst .= ",-2,-2";
1487         $ret .= sprintf('document.title = "Brisk - Tavolo %d (asta)";', $user->table_orig);
1488         $ret .= sprintf('show_astat(%s);', $showst);
1489
1490         if ($table->asta_win != -1 && $table->asta_win == $table_pos) {
1491             /* show card chooser */
1492             $ret .= sprintf('choose_seed(%s); $("astalascio").style.visibility = ""; $("asta").style.visibility = "hidden";',
1493                             $table->asta_card);
1494         }
1495         else {
1496             /* show auction */
1497             if ($table_pos == ($table->gstart % BIN5_PLAYERS_N) &&
1498                 $table->asta_win == -1) 
1499                 $ret .= sprintf('dispose_asta(%d,%d, %s);', 
1500                                 $table->asta_card + 1, $table->asta_pnt+1, ($user->handpt <= 2 ? "true" : "false"));
1501             else
1502                 $ret .= sprintf('dispose_asta(%d,%d, %s);',
1503                                 $table->asta_card + 1, -($table->asta_pnt+1), ($user->handpt <= 2 ?  "true" : "false"));
1504         }
1505
1506         /* Remark */
1507         if ($table->asta_win == -1) { // auction case
1508             if ($table_pos == ($table->gstart % BIN5_PLAYERS_N)) 
1509                 $ret .= "remark_on();";
1510             else
1511                 $ret .= "remark_off();";
1512         }
1513         else { // chooseed case
1514             if ($table_pos == $table->asta_win) 
1515                 $ret .= "remark_on();";
1516             else
1517                 $ret .= "remark_off();";
1518         }
1519     }
1520     else if ($user->subst == 'game') {
1521         /* HIGHLIGHT */
1522         if (($table->gstart + $table->turn) % BIN5_PLAYERS_N == $table_pos) 
1523             $ret .= "is_my_time = true; remark_on();";
1524         else
1525             $ret .= "remark_off();";
1526     
1527         /* WHO CALL AND WHAT */
1528         $ret .= briscola_show($room, $table, $user);
1529     
1530     }
1531     return ($ret);
1532 } // end function show_table(...
1533
1534 function calculate_winner(&$table)
1535 {
1536     $briontab = FALSE;
1537     $ontab = array();
1538     $ontid = array();
1539     $cur_win  =  -1;
1540     $cur_val  = 100;
1541     $cur_seed = $table->briscola - ($table->briscola % 10);
1542
1543     for ($i = 0 ; $i < (BIN5_PLAYERS_N == 5 ? 40 : 24) ; $i++) {
1544         // for ($i = 0 ; $i < 40 ; $i++) {
1545         if ($table->card[$i]->stat != "table")
1546             continue;
1547
1548         log_wr(sprintf("Card On table: [%d]", $i));
1549
1550         $v = $table->card[$i]->value; 
1551         $ontab[$table->card[$i]->owner] = $v;
1552         $ontid[$table->card[$i]->owner] = $i;
1553         /* se briscola setto il flag */
1554         if (($v - ($v % 10)) == $cur_seed)
1555             $briontab = TRUE;
1556     }
1557
1558     if ($briontab == FALSE) {
1559         $cur_win  = $table->gstart;
1560         $cur_val  = $ontab[$cur_win];
1561         $cur_seed = $cur_val - ($cur_val % 10);
1562     }
1563
1564     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1565         if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1566             if ($ontab[$i] < $cur_val) {
1567                 $cur_val = $ontab[$i];
1568                 $cur_win = $i;
1569             }
1570         }
1571     }
1572
1573     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) {
1574         $table->card[$ontid[$i]]->owner = $cur_win;
1575         $table->card[$ontid[$i]]->stat =  "take"; // Card stat
1576     }
1577     return ($cur_win);
1578 }
1579
1580 function show_table_info(&$room, &$table, $table_pos)
1581 {
1582     GLOBAL $G_lang, $mlang_bin5_bin5;
1583
1584     $ret = "";
1585     $user = $room->user[$table->player[$table_pos]];
1586
1587     $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
1588     $noty = sprintf('<table class=\"points\"><tr><th></th>');
1589   
1590     // Names.
1591     for ($i = 0 ; $i < BIN5_PLAYERS_N ; $i++) 
1592         $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($room->user[$table->player[$i]]->name));
1593     $noty .= sprintf("</tr>");
1594
1595     // Points.
1596     log_main("show_table_info: pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
1597
1598     for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
1599         $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
1600         for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) 
1601             $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
1602         $noty .= "</tr>";
1603     }
1604
1605     // Total points.
1606     $noty .= '<tr><th class=\"td_points\">Tot.</th>';
1607     for ($e = 0 ; $e < BIN5_PLAYERS_N ; $e++) 
1608         $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
1609     $noty .= "</tr></table>";
1610
1611     if ($table->old_reason != "") {
1612         $noty .= sprintf("<hr><b>%s</b><br>", xcape($table->old_reason));
1613     }
1614
1615     if ($table->old_win != -1) {
1616         log_main("TABLE_OLD_WIN:".$table->old_win);
1617         $win = $table->player[$table->old_win];
1618         log_main("TABLE_OLD_FRIEND:".$table->old_friend);
1619         $fri = $table->player[$table->old_friend];
1620
1621         $wol = game_result($table->old_asta_pnt, $table->old_pnt);
1622
1623         if ($win != $fri) {
1624             /* 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" */
1625       
1626             $noty .= sprintf($mlang_bin5_bin5['info_part'][$G_lang], 
1627                              xcape($room->user[$win]->name),
1628                              xcape($room->user[$fri]->name));
1629             if ($table->old_pnt == 120) {
1630                 $noty .= sprintf($mlang_bin5_bin5['info_capp'][$G_lang]);
1631             }
1632             else {
1633                 $noty .= sprintf($mlang_bin5_bin5['info_pnt'][$G_lang],
1634                                  ($table->old_asta_pnt > 61 ? $mlang_bin5_bin5['info_alea'][$G_lang].$table->old_asta_pnt :
1635                                   $mlang_bin5_bin5['info_more'][$G_lang]), $table->old_pnt,
1636                                  ($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])));
1637             }
1638         }
1639         else {
1640             $noty .= sprintf($mlang_bin5_bin5['info_alon'][$G_lang],
1641                              xcape($room->user[$win]->name));
1642             if ($table->old_pnt == 120) {
1643                 $noty .= sprintf($mlang_bin5_bin5['info_acap'][$G_lang]);
1644             }
1645             else {
1646                 $noty .= sprintf($mlang_bin5_bin5['info_apnt'][$G_lang],
1647
1648                                  ($table->old_asta_pnt > 61 ? $mlang_bin5_bin5['info_alea'][$G_lang].$table->old_asta_pnt :
1649                                   $mlang_bin5_bin5['info_more'][$G_lang]), $table->old_pnt,
1650
1651                                  ($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])));
1652             }
1653         }
1654         if (($table->old_mult + asta2mult($table->old_asta_pnt)) > 1) {
1655             $noty .= sprintf($mlang_bin5_bin5['info_omul'][$G_lang], multoval($table->old_mult + asta2mult($table->old_asta_pnt)));
1656         }
1657         $noty .= "<hr><br>";
1658     }
1659     /* MLANG: "Fai <b>tu</b> il mazzo,", "Il mazzo a <b>$unam</b>," */
1660     if ($table->mazzo == $table_pos) 
1661         $noty .= $mlang_bin5_bin5['info_yshuf'][$G_lang];
1662     else {
1663         $unam = xcape($room->user[$table->player[$table->mazzo]]->name);
1664         $noty .= sprintf($mlang_bin5_bin5['info_shuf'][$G_lang], $unam);
1665     }
1666
1667     if ($user->subst == 'asta') {
1668         if ($table->asta_win == -1)  // auction case
1669             $curplayer = $table->gstart % BIN5_PLAYERS_N;
1670         else 
1671             $curplayer = $table->asta_win;
1672     }
1673     else if ($user->subst == 'game') {
1674         $curplayer = ($table->gstart + $table->turn) % BIN5_PLAYERS_N;
1675     }
1676
1677     /* MLANG: " tocca a <b>te</b> giocare.", " tocca a <b>$unam</b> giocare.", " La partita vale <b>%s</b>.", "torna alla partita" */
1678     if ($curplayer == $table_pos) {
1679         $noty .= $mlang_bin5_bin5['info_yturn'][$G_lang];
1680     }
1681     else {
1682         $unam = xcape($room->user[$table->player[$curplayer]]->name);
1683         $noty .= sprintf($mlang_bin5_bin5['info_turn'][$G_lang], $unam);
1684     }
1685   
1686     if (($table->mult + asta2mult($table->asta_pnt)) > 1) {
1687         $noty .= sprintf($mlang_bin5_bin5['info_mult'][$G_lang], multoval($table->mult + asta2mult($table->asta_pnt)));
1688     }
1689     $noty .= "<hr><br>";
1690     $ret .= show_notify($noty, 3000, $mlang_bin5_bin5['btn_bkgame'][$G_lang], 500, 400);
1691     /* NOTE: show_notify($noty, 3000, "torna alla partita", 500, 
1692      *                   130 + ($table->points_n > 0 ? 50 : 0) + 
1693      *                   (120 * ($table->points_n / MAX_POINTS)));
1694      *       will be used when we refact notify js function following 
1695      *       photoo class logic 
1696      */ 
1697   
1698     return ($ret);
1699 }
1700
1701 function table_wellcome($user)
1702 {
1703     GLOBAL $table_wellarr, $G_lang;
1704     $ret = "";
1705
1706     for ($i = 0 ; $i < count($table_wellarr[$G_lang]) ; $i++)
1707         $ret .= sprintf('chatt_sub("%s", [2, "ChanServ: "],"%s");', "", str_replace('"', '\"', $table_wellarr[$G_lang][$i]));
1708
1709     return ($ret);
1710 }
1711
1712
1713 function briscola_show($room, $table, $user)
1714 {
1715     GLOBAL $G_lang, $mlang_bin5_bin5;
1716     $ptnadd = "";
1717     $ret = "";
1718
1719     if ($table->asta_card == 9) 
1720         $ptnadd = sprintf($mlang_bin5_bin5['call_wptn'][$G_lang], $table->asta_pnt);
1721   
1722     /* text of caller cell */
1723     if ($user->table_pos == $table->asta_win) {
1724         $prestr = sprintf('$("callerinfo").innerHTML = "%s";', $mlang_bin5_bin5['call_ycall'][$G_lang]);
1725         $ret .= sprintf($prestr, $ptnadd);
1726     }
1727     else {
1728         $prestr = sprintf('$("callerinfo").innerHTML = "%s";', $mlang_bin5_bin5['call_call'][$G_lang]);
1729         $ret .= sprintf($prestr, 
1730                         xcape($room->user[$table->player[$table->asta_win]]->name), $ptnadd);
1731     }
1732     $ret .= sprintf('set_iscalling(%d);', ($table->asta_win - $user->table_pos + BIN5_PLAYERS_N) % BIN5_PLAYERS_N);
1733
1734     $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
1735                     $table->asta_win);
1736     $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
1737     $ret .= sprintf('$("caller").style.visibility = "visible";');
1738     $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
1739     $ret .= sprintf('$("astalascio").style.visibility = "";');
1740     $ret .= sprintf('$("asta").style.visibility = "hidden";');
1741     $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
1742   
1743     return ($ret);
1744 }
1745
1746
1747 function game_result($asta_pnt, $pnt)
1748 {
1749     if ($asta_pnt == 61) {
1750         if ($pnt > 60)
1751             return (1);
1752         else if ($pnt == 60)
1753             return (0);
1754         else
1755             return (-1);
1756     }
1757     else {
1758         if ($pnt >= $asta_pnt)
1759             return (1);
1760         else
1761             return (-1);
1762     }
1763 }
1764
1765 function log_points($curtime, $user, $where, $mesg) 
1766 {
1767     GLOBAL $_SERVER;
1768
1769     if (($fp = @fopen(LEGAL_PATH."/points.log", 'a')) != FALSE) {
1770         /* Unix time | session | nickname | IP | where was | mesg */
1771         fwrite($fp, sprintf("%ld|%s|%s|%s|%s|%s|%s|\n", $curtime, $user->sess,
1772                             ($user->flags & USER_FLAG_AUTH ? 'A' : 'N'),
1773                             $user->name, $_SERVER['REMOTE_ADDR'], $where , $mesg));
1774         fclose($fp);
1775     }
1776 }
1777
1778 ?>