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