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