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