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