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