Initial revision
[brisk.git] / web / brisk.phh
1 <?php
2 /*
3  *  brisk - brisk.phh
4  *
5  *  Copyright (C) 2006 matteo.nastasi@milug.org
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details. You should have received a
16  * copy of the GNU General Public License along with this program; if
17  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
18  * Suite 330, Boston, MA 02111-1307, USA.
19  *
20  */
21
22 define( FTOK_PATH, "/var/lib/brisk");
23 define(TABLES_N, 4);
24 define(PLAYERS_N, 3);
25 define(MAX_POINTS, 5);
26 define(MAX_PLAYERS, (PLAYERS_N * TABLES_N));
27 define(COMM_N, 12);
28 define(COMM_GEN_N, 50);
29 define(SESS_LEN, 13);
30 define(STREAM_TIMEOUT, 20);
31 define(EXPIRE_TIME, 180);
32 define(GARBAGE_TIMEOUT, 30);
33 define(NICKSERV, "<i>SERVER</i>");
34 // define(DEBUGGING, "local");
35
36 function xcape($s)
37 {
38   return (str_replace('@', '&#64;', str_replace('|', '&brvbar;', htmlentities($s,ENT_COMPAT,"UTF-8"))));
39 }
40
41
42 class Card {
43   var $value; /* 0 - 39 card value */
44   var $stat;  /* 'bunch', 'hand', 'table', 'take' */
45   var $owner; /* (table position 0-4) */
46   // var $pos;   /* Pos in hand. */
47   var $x;     /* When played the X position on the table of the owner. */
48   var $y;     /* When played the Y position on the table of the owner. */
49
50   function Card($value, $stat, $owner)
51   {
52     $this->value = $value;
53     $this->stat  = $stat;
54     $this->owner = $owner;
55   }
56
57   function assign($stat,$owner)
58   {
59     $this->stat  = $stat;
60     $this->owner = $owner;
61   }
62
63   function setpos($pos)
64   {
65     $this->pos   = $pos;
66   }
67
68   function play($x,$y)
69   {
70     $this->stat = 'table';
71     $this->x = $x;
72     $this->y = $y;
73   }
74
75   function take($newown)
76   {
77     $this->stat = 'take';
78     $this->owner = $newown;
79   }
80 }
81
82 class Table {
83   var $player;
84   var $player_n;
85   var $card;
86   var $mazzo;
87   var $gstart;
88   var $turn;
89
90   var $asta_pla;
91   var $asta_pla_n;
92   var $asta_card;
93   var $asta_pnt;
94   
95   var $mult;
96   var $points;    // points array
97   var $points_n;  // number of row of points
98   var $total;
99
100   var $asta_win;
101   var $briscola;
102   var $friend;
103   
104   var $old_asta_pnt;
105   var $old_pnt;
106   var $old_win;
107   var $old_friend;
108
109   function Table() 
110   {
111     $this->player    =   array();
112     $this->player_n  =   0;
113     $this->card      =  &$this->bunch_create();
114     $this->asta_pla  =   array(); // TRUE: in auction, FALSE: out of the auction
115     $this->asta_pla_n=  -1;
116     $this->asta_card =  -1;
117     $this->asta_pnt  =  -1;
118     $this->mult      =   1;
119     $this->points    =   array( );
120     $this->points_n  =   0;
121     $this->total     =   array( 0, 0, 0, 0, 0);
122     $this->asta_win  =  -1;
123     $this->briscola  =  -1;
124     $this->friend    =  -1;
125     $this->turn      =   0;
126     $this->old_asta_pnt = -1;
127     $this->old_pnt      = -1;
128     $this->old_win   =  -1;
129     $this->old_friend=  -1;
130
131   }
132
133   function &bunch_create()
134   {
135     $ret = array();
136
137     for ($i = 0 ; $i < 40 ; $i++) {
138       $ret[$i] = new Card($i, 'bunch', 'no_owner');
139     }
140
141     return ($ret);
142   }
143
144   function bunch_make()
145   {
146     $ct = array(0,0,0,0,0);
147     
148     mt_srand(make_seed());
149     
150     for ($i = 39 ; $i >= 0 ; $i--) 
151       $rest[$i] = $i;
152
153     for ($i = 39 ; $i >= 0 ; $i--) {
154       $rn = rand(0, $i);
155
156       if ($rn == 0)
157         log_main("RND ZERO", "");
158       
159       $id = $rest[$rn];
160
161       $owner = $i % 5;
162       $this->card[$id]->assign('hand', $owner);
163
164       $rest[$rn] = $rest[$i];
165       $pubbpos[$rn2] = $pubbpos[$i];
166     }
167   }
168
169   function init()
170   {
171     $this->mazzo    = rand(0,PLAYERS_N-1);
172     $this->points_n = 0;
173     $this->mult     = 1;
174     $this->old_win  =-1;
175     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
176       $this->total[$i] = 0;
177     }
178
179     log_main("table::init","ci siamo");
180   }
181
182   function game_init(&$bri)
183   {
184     log_rd2($sess,"GSTART 4");
185
186     $this->gstart = ($this->mazzo+1) % PLAYERS_N;
187     $this->bunch_make();
188     
189     
190     $this->asta_pla_n = PLAYERS_N;
191     $this->asta_card = -1;
192     $this->asta_pnt  = 60;
193     $this->asta_win  = -1;
194     $this->briscola  = -1;
195     $this->friend    = -1;
196     $this->turn      =  0;
197     
198     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
199       $this->asta_pla[$i] = TRUE;
200       $user_cur = &$bri->user[$this->player[$i]];
201       $user_cur->subst = 'asta';
202       $user_cur->asta_card = -2;
203       $user_cur->asta_pnt  = -1;
204     }
205   }
206
207   function game_next()
208   {
209     $this->mazzo  = ($this->mazzo + 1) % PLAYERS_N;
210   }
211
212   function getPlayer($idx)
213   {
214     return ($this->player[$idx]);
215   }
216
217   function setPlayer($idx, $player)
218   {
219     $this->player[$idx] = $player;
220   }
221 }
222
223 class User {
224   var $name;       // name of the user
225   var $sess;       // session of the user
226   var $lacc;       // last access (for the cleanup)
227   var $stat;       // status (outdoor, room, table, game, ...)
228   var $subst;      // substatus for each status   
229   var $step;       // step of the current status
230   var $trans_step; // step to enable transition between pages (disable == -1)
231   var $comm;       // commands array
232   var $asta_card;  // 
233   var $asta_pnt;   //
234
235   var $table;      // id of the current table (if in table state)
236   var $table_pos;  // idx on the table
237
238   function User($name, $sess, $stat = "", $subst = "", $table = -1) {
239     $this->name  = $name;
240     $this->sess  = $sess;
241     $this->lacc  = time();
242     $this->stat  = $stat;
243     $this->subst  = $subst;
244     $this->step  = 1;
245     $this->trans_step  = -1;
246     $this->comm  = array();
247     $this->asta_card = -2;
248     $this->asta_pnt  = -1;
249
250     $this->table = $table;
251   }
252 }
253
254 class brisco {
255   var $user;
256   var $table;
257   var $comm; // commands for many people
258   var $step; // current step of the comm array
259   var $garbage_timeout;
260
261   function brisco () {
262     $this->user = array();
263
264     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
265       $this->user[$i] = new User("", "");
266     }
267     for ($i = 0 ; $i < TABLES_N ; $i++) 
268       $this->table[$i] = new Table();
269     $this->garbage_timeout = 0;
270   }
271
272   function garbage_manager($force)
273   {
274     
275     /* Garbage collector degli utenti in timeout */
276     $curtime = time();
277     if ($force || $this->garbage_timeout < $curtime) {
278       
279       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
280         $user_cur = &$this->user[$i];
281         if ($user_cur->sess == "")
282           continue;
283         
284         if ($user_cur->lacc < $curtime) { // Auto logout dell'utente
285           log_rd2($user_cur->sess, "AUTO LOGOUT.");
286           /*
287           if ($user_cur->stat == 'table') {
288               log_rd2($user_cur->sess, "AUTO LOGOUT: Yet not implemented in table stat!");
289               continue;
290             }
291           else
292           */
293           if ($user_cur->stat == 'table' || $user_cur->stat == 'room') {
294             log_auth($user_cur->sess, "Autologout session.");
295             
296             $user_cur->sess = "";
297             $user_cur->name = "";
298             $user_cur->the_end = FALSE;
299             
300             log_rd2($user_cur->sess, "AUTO LOGOUT.");
301             if ($user_cur->subst == 'sitdown' || $user_cur->stat == 'table')
302               $this->room_wakeup(&$user_cur);
303             else if ($user_cur->subst == 'standup')
304               $this->room_outstandup(&$user_cur);
305             else
306               log_rd2($sess, "LOGOUT FROM WHAT ???");
307           }
308           //    } // if (0 == 1) 
309           
310         }
311       }
312       log_rd2($user_cur->sess, "GARBAGE UPDATED!");
313       
314       $this->garbage_timeout = time() + GARBAGE_TIMEOUT;
315     }
316   }
317
318
319   function room_wakeup(&$user)
320   {
321     $table_idx = $user->table;
322     $table = &$this->table[$table_idx];
323
324     log_main("WAKEUP", "begin function table:".$table_idx);
325
326     $from_table = ($user->stat == "table");
327     if ($from_table) {
328       log_main("WAKEUP", "from table [".$user->table."] nplayers_n: ".$this->table[$user->table]->player_n);
329
330       for ($i = 0 ; $i < $table->player_n ; $i++) {
331         $user_cur = &$this->user[$table->player[$i]];
332         log_main("PREIMPOST", "INLOOP name: ".$user_cur->name);
333
334         if ($user_cur != $user) {
335           $user_cur->stat = "room";
336           $user_cur->subst = "sitdown";
337         }
338         else if ($user->sess != "") {
339           $user_cur->stat = "room";
340           $user_cur->subst = "standup";
341           $user_cur->table = -1;
342         }
343       }
344     }
345     /* aggiorna l'array dei giocatori al tavolo. */
346     for ($i = $user->table_pos ; $i < $table->player_n-1 ; $i++) {
347       $table->player[$i] = $table->player[$i+1];
348       $user_cur = &$this->user[$table->player[$i]];
349       $user_cur->table_pos = $i;
350     }
351     $this->table[$table_idx]->player_n--;
352     
353     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
354       $user_cur = &$this->user[$i];
355       if ($user_cur->sess == '' || $user_cur->stat != 'room')
356         continue;
357       
358       log_main("VALORI", "name: ".$user_cur->name."from_table: ".$from_table."  tab: ".$user_cur->table." taix: ".$table_idx."  ucur: ".$user_cur."  us: ".$user);
359
360       // function show_room(&$bri, &$user)
361
362       $ret = "gst.st = ".($user_cur->step+1)."; ";
363       if ($from_table && ($user_cur->table == $table_idx || $user_cur == $user)) {
364         $ret .= 'gst.st_loc++; the_end=true; document.location.assign("index.php");|';
365         // $ret .= 'gst.st_loc++; document.location.assign("index.php");|';
366         log_main("DOCUMENT.index.php", "from table");
367       }
368       else if ($user_cur->stat == "room") {
369         $ret .= table_content($this, $user_cur, $table_idx);
370         $ret .= standup_content($this, $user_cur);
371         
372         $act_content = table_act_content(FALSE, 0, $e, $user->table);
373         $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
374         
375         
376         if ($user_cur == $user) {
377           // set the new status 
378           $ret .=  'subst = "standup"; ';
379           // clean the action buttons in other tables
380           for ($e = 0 ; $e < TABLES_N ; $e++) {
381             if ($this->table[$e]->player_n < PLAYERS_N)
382               $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, table_act_content(TRUE, 0, $e, $user->table));
383           }
384         }
385         else {
386           $act_content = table_act_content(($user_cur->subst == 'standup'), $table->player_n, $table_idx, $user_cur->table);
387           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
388         }
389       }
390       log_wr($user_cur->sess, "ROOM_WAKEUP: ".$ret);
391       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
392       $user_cur->step++;
393     }
394   }
395   
396
397
398
399   function room_outstandup(&$user)
400   {
401     $this->room_sitdown(&$user, -1);
402   }
403   
404   function table_update(&$user)
405   {
406     log_main("table_update", "pre - USER: ".$user->name);
407
408     $table_idx = $user->table;
409
410     if ($table_idx > -1) 
411       $table = &$this->table[$table_idx];
412     
413     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
414       $ret = "";
415       $user_cur = &$this->user[$i];
416       if ($user_cur->sess == '' || $user_cur->stat != 'room')
417       continue;
418       
419       $ret = "gst.st = ".($user_cur->step+1)."; ";
420       if ($table_idx > -1)
421         $ret .= table_content($this, $user_cur, $table_idx);
422       
423       if ($user_cur == $user) {
424         $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
425       }
426       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
427       $user_cur->step++;
428     }
429
430     log_main("table_update", "post");
431   }
432
433   function room_sitdown(&$user, $table_idx)
434   {
435     log_main("room_sitdown", ($user == FALSE ? "USER: FALSE" : "USER: ".$user->name));
436
437     if ($table_idx > -1) 
438       $table = &$this->table[$table_idx];
439     
440     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
441       $ret = "";
442       $user_cur = &$this->user[$i];
443       if ($user_cur->sess == '' || $user_cur->stat != 'room')
444       continue;
445       
446       $ret = "gst.st = ".($user_cur->step+1)."; ";
447       if ($table_idx > -1)
448       $ret .= table_content($this, $user_cur, $table_idx);
449       $ret .= standup_content($this, $user_cur);
450       
451       if ($user_cur == $user) {
452         $ret .=  'subst = "sitdown"; ';
453         // clean the action buttons in other tables
454         for ($e = 0 ; $e < TABLES_N ; $e++) {
455           $act_content = table_act_content(FALSE, 0, $e, $user_cur->table);
456           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $e, $act_content);
457         }
458       }
459       else if ($table_idx > -1) {
460         if ($table->player_n == PLAYERS_N) {
461           $act_content = table_act_content(($user_cur->subst == 'standup'), PLAYERS_N, $table_idx, $user_cur->table);
462           $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $table_idx, $act_content);
463         }
464       }
465       $user_cur->comm[$user_cur->step % COMM_N] = $ret;
466       $user_cur->step++;
467     }
468   }
469
470   function chatt_send(&$user, $mesg)
471   {
472     if ($user->stat == 'table') {
473       $table = &$this->table[$user->table];
474     }
475     
476     $user_mesg = substr($mesg,6);
477     
478     $dt = date("H:i ",time());
479     if (strncmp($user_mesg, "/nick ", 6) == 0) {
480       log_main($user->sess, "chatt_send BEGIN");
481
482       $name_new = substr(trim(substr($user_mesg, 6)),0,12);
483       $user_mesg = "COMMAND ".$user_mesg;
484       // Search dup name
485       // change
486       // update local graph
487       // update remote graphs
488       for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
489         $user_cur = &$this->user[$i];
490         if ($user_cur->sess == '' || $user_cur->stat != 'room')
491           continue;
492         if ($user_cur->name == $name_new) {
493           $user->comm[$user->step % COMM_N] = "gst.st = ".($user->step+1)."; ";
494           $user->comm[$user->step % COMM_N] .= sprintf('chatt_sub("%s","Nickname <b>%s</b> gi&agrave; in uso.");', $dt.NICKSERV, xcape($name_new));
495           $user->step++;
496           break;
497         }
498       }
499       if ($i == MAX_PLAYERS) {
500         $user->name = $name_new;
501
502       log_main($user->sess, "chatt_send start set");
503         
504
505         for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
506           log_main($user->sess, "chatt_send set loop");
507           
508           $user_cur = &$this->user[$i];
509           if ($user_cur->sess == '')
510             continue;
511           if ($user_cur->stat == 'room') {
512             if ($user->stat == 'room' && $user->subst == 'standup') {
513               standup_update(&$this,&$user);
514             }
515             else if ($user->stat == 'room' && $user->subst == 'sitdown' ||
516                      $user->stat == 'table') {
517               log_main($user->sess, "chatt_send pre table update");
518
519               $this->table_update(&$user);
520
521               log_main($user->sess, "chatt_send post table update");
522             }
523           }
524           else if ($user_cur->stat == 'table' && $user_cur->table == $user->table) {
525             $table = &$this->table[$user->table];
526             
527             $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
528             $user_cur->comm[$user_cur->step % COMM_N] = sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
529                 xcape($this->user[$table->player[($user_cur->table_pos)%PLAYERS_N]]->name),
530                 xcape($this->user[$table->player[($user_cur->table_pos+1)%PLAYERS_N]]->name),
531                 xcape($this->user[$table->player[($user_cur->table_pos+2)%PLAYERS_N]]->name),
532                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+3)%PLAYERS_N]]->name)),
533                 (PLAYERS_N == 3 ? "" :  xcape($this->user[$table->player[($user_cur->table_pos+4)%PLAYERS_N]]->name)));
534             if ($user_cur == $user)
535               $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>";', 
536                                                                    xcape($user->name,ENT_COMPAT,"UTF-8"));
537             $user_cur->step++;
538           }
539         }
540       }
541     }
542     else {
543       $user_mesg = xcape($user_mesg);
544       
545       for ($i = 0 ; $i < ($user->stat == 'room' ? MAX_PLAYERS : PLAYERS_N) ; $i++) {
546         if ($user->stat == 'room') {
547           $user_cur = &$this->user[$i];
548           if ($user_cur->sess == '' || $user_cur->stat != 'room')
549             continue;
550         }
551         else {
552           $user_cur = &$this->user[$table->player[$i]];
553         }
554         
555         $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ";
556         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('chatt_sub("%s","%s");',
557                                                              $dt.xcape($user->name), $user_mesg);
558         $user_cur->step++;
559       }
560     }
561   }
562   
563 } // end class brisco
564
565 function make_seed()
566 {
567   list($usec, $sec) = explode(' ', microtime());
568   return (float) $sec + ((float) $usec * 100000);
569 }
570
571 function log_main($sess, $log) {
572   $fp = fopen("/tmp/brisk_main.log", 'a');
573   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
574   fclose($fp);
575 }
576
577 function log_rd($sess, $log) {
578   // $fp = fopen("/tmp/brisk_rd.log", 'a');
579   // fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
580   // fclose($fp);
581         ;
582 }
583
584 function log_rd2($sess, $log) {
585   $fp = fopen("/tmp/brisk_rd2.log", 'a');
586   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
587   fclose($fp);
588 }
589
590 function log_send($sess, $log) {
591   $fp = fopen("/tmp/brisk_send.log", 'a');
592   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
593   fclose($fp);
594 }
595
596 function log_auth($sess, $log) {
597   $fp = fopen("/tmp/brisk_auth.log", 'a');
598   fwrite($fp, sprintf("SESS: [%d] [%s] [%s]\n", time(), $sess, $log));
599   fclose($fp);
600 }
601
602 function log_wr($sess, $log) {
603   $fp = fopen("/tmp/brisk_wr.log", 'a');
604   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
605   fclose($fp);
606 }
607
608 function log_load($sess, $log) {
609   $fp = fopen("/tmp/brisk_load.log", 'a');
610   fwrite($fp, sprintf("SESS: [%s] [%s]\n", $sess, $log));
611   fclose($fp);
612 }
613
614 function init_data()
615 {
616   $brisco = new brisco();
617
618   return $brisco;
619 }
620
621 function lock_data()
622 {
623         //  echo "LOCK: ".FTOK_PATH."/main";
624         //  exit;
625   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
626     echo "FTOK FAILED";
627     exit;
628   }
629   // echo "FTOK ".$tok."<br>";
630   if (($res = sem_get($tok)) == FALSE) {
631     echo "SEM_GET FAILED";
632     exit;
633   }
634   if (sem_acquire($res)) 
635     return ($res);
636   else
637     return (false);
638 }
639
640 function unlock_data($res)
641 {
642   return (sem_release($res));
643 }
644
645
646 function &load_data() 
647 {
648   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) {
649     echo "FTOK FAILED";
650     exit;
651   }
652
653   if ($shm = shm_attach($tok,100000 * TABLES_N)) {
654     if(($bri = @shm_get_var($shm, $tok)) == false) {
655       log_main("XXX", "INIT MAIN DATA");
656
657       $bri = init_data();
658       shm_put_var($shm, $tok, $bri);
659     }
660     
661     shm_detach($shm);
662
663     return ($bri);
664   }
665
666   return (NULL);
667 }
668
669
670 function save_data(&$bri) 
671 {
672   $ret =   FALSE;
673   $shm =   FALSE;
674   $isacq = FALSE;
675
676   // var_dump($bri);
677
678   if (($tok = ftok(FTOK_PATH."/main", "B")) == -1) 
679     return (FALSE);
680
681   do {
682     $isacq = TRUE;
683     
684     if (($shm = shm_attach($tok,100000 * TABLES_N)) == FALSE)
685       break;
686     
687     if (shm_put_var($shm, $tok, $bri) == FALSE)
688       break;
689     // log_main("XXX", "QUI CI ARRIVA [".$bri->user[0]->name."]");
690     $ret = TRUE;
691   } while (0);
692   
693   if ($shm)
694     shm_detach($shm);
695      
696   return ($ret);
697 }
698
699 function &get_user(&$bri, $sess, &$idx)
700 {
701   GLOBAL $PHP_SELF;
702
703   if (strlen($sess) == SESS_LEN) {
704     for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
705       if (strcmp($sess, $bri->user[$i]->sess) == 0) {
706         // find it
707         $idx = $i;
708         return ($bri->user[$i]);
709       }
710     }
711     log_main($sess, sprintf("get_user: Wrong sess from page [%s]",$PHP_SELF));
712     // for ($i = 0 ; $i < MAX_PLAYERS ; $i++) 
713     // log_main($sess, sprintf("get_user: Wrong sess compared with [%s]",$bri->user[$i]->sess));
714   }
715   else {
716     log_main($sess, sprintf("get_user: Wrong strlen [%s]",$sess));
717   }
718   return (FALSE);
719 }
720
721 /*
722  * function &add_user(&$bri, &$sess, &$idx, $name)
723  *
724  * RETURN VALUE:
725  *   if ($idx != -1 && ret == FALSE)  =>  duplicated nick
726  *   if ($idx == -1 && ret == FALSE)  =>  no space left
727  *   if (ret == TRUE)                 =>  SUCCESS
728  */
729 function &add_user(&$bri, &$sess, &$idx, $name)
730 {
731   $idx = -1;
732
733   for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
734     /* free user ? */
735     if (strcmp($sess, $bri->user[$i]->sess) == 0) {
736       if ($idx == -1)
737         $idx = $i;
738     }
739     if (strcmp($bri->user[$i]->name, $name) == 0) {
740       $idx = $i;
741       break;
742     }
743   }
744   if ($idx != -1 && $i == MAX_PLAYERS) {
745     /* SUCCESS */
746     $bri->user[$idx]->sess = uniqid("");
747     $sess = $bri->user[$idx]->sess;
748     $bri->user[$idx]->name = $name;
749     $bri->user[$idx]->stat = "room";
750     $bri->user[$idx]->subst = "standup";
751
752     log_main("XXX", sprintf("TROVATO LIBERO A [%d] sess [%s] name [%s]", $idx, $sess, $name));
753       
754     return ($bri->user[$idx]);
755   }
756   else {
757     return (FALSE);
758   }
759 }
760
761 function table_act_content($isstanding, $sitted, $table, $cur_table)
762 {
763   $ret = "";
764
765   if ($isstanding) {
766     if ($sitted < PLAYERS_N) {
767       $ret = sprintf('<input type=\\"button\\" name=\\"xhenter%d\\"  value=\\"Mi siedo.\\" onclick=\\"act_sitdown(%d);\\">', $table, $table);
768     }
769   }
770   else {
771     if ($table == $cur_table)
772       $ret = sprintf('<input type=\\"button\\" name=\\"xwakeup\\"  value=\\"Mi alzo.\\" onclick=\\"act_wakeup();\\">');
773     else
774       $ret = "";
775   }
776   return ($ret);
777 }
778
779 function table_content($bri, $user, $table_idx)
780 {
781   $content = "";
782
783   // TODO
784   //
785   //   Si possono usare i dati nella classe table
786   //
787
788   $sess = $user->sess;
789   $table = &$bri->table[$table_idx];
790
791   if ($user->stat != 'room')
792     return;
793
794   for ($i = 0 ; $i < $table->player_n ; $i++) {
795     $user_cur = &$bri->user[$table->player[$i]];
796
797     if ($user_cur == $user) 
798         { $hilion = "<b>"; $hilioff = "</b>"; }
799       else
800         { $hilion = ""; $hilioff = ""; }
801
802     log_main($bri->user[$e]->name, sprintf("IN TABLE [%d]", $table_idx));
803     
804     $content .= sprintf("%s%s%s<br>",$hilion, xcape($user_cur->name), $hilioff);
805   }
806   for ( ; $i < PLAYERS_N ; $i++)
807     $content .= "<br>";
808
809   $ret .= sprintf('$("table%d").innerHTML = "%s";', $table_idx, $content);
810   
811   return ($ret);
812 }
813
814 function standup_content(&$bri, $user)
815 {
816   $ret = "";
817   $content = "";
818
819   if ($user->stat != 'room')
820     return;
821
822   $content .= '<table width=\\"100%\\">';
823   for ($e = 0 , $ct = 0 ; $e < MAX_PLAYERS ; $e++) {
824     if ($bri->user[$e]->sess == "" || $bri->user[$e]->stat != "room" || $bri->user[$e]->name == "")
825       continue;
826
827
828     if ($bri->user[$e]->subst == "standup") {
829       if (($ct % 4) == 0) {
830         $content .= '<tr>';
831       }
832       if ($bri->user[$e] == $user) 
833         { $hilion = "<b>"; $hilioff = "</b>"; }
834       else
835         { $hilion = ""; $hilioff = ""; }
836
837       $content .= sprintf('<td style=\\"text-align: center\\">%s%s%s</td>',$hilion, xcape($bri->user[$e]->name), $hilioff);
838       if (($ct % 4) == 3) {
839         $content .= '</tr>';
840       }
841       $ct++;
842     }
843   }
844   $content .= '</table>';
845         
846   $content .= '<div class=\\"esco\\"><input name=\\"logout\\" value=\\"Esco.\\" onclick=\\"act_logout();\\" type=\\"button\\"></div>';
847
848   $ret .= sprintf('$("standup").innerHTML = "%s";', $content);
849
850   return ($ret);
851 }
852
853 function standup_update(&$bri, &$user)
854 {
855   for ($i = 0 ; $i < MAX_PLAYERS ; $i++) {
856     $user_cur = &$bri->user[$i];
857     if ($user_cur->sess == '')
858       continue;
859
860     log_main("STANDUP START", $user_cur->stat);
861
862     if ($user_cur->stat == 'room') {
863       $user_cur->comm[$user_cur->step % COMM_N] = "gst.st = ".($user_cur->step+1)."; ".standup_content($bri, $user_cur);
864       if ($user_cur == $user)
865         $user_cur->comm[$user_cur->step % COMM_N] .= sprintf('$("myname").innerHTML = "<b>%s</b>: ";',  xcape($user->name));
866
867       log_main("FROM STANDUP", "NAME: ".$user_cur->name." SENDED: ".$user_cur->comm[$user_cur->step % COMM_N]);
868
869       $user_cur->step++;
870     }
871   }
872 }
873
874
875
876
877
878 function show_notify($text, $tout, $butt)
879 {
880   log_main("SHOW_NOTIFY", $text);
881   return sprintf('var noti = new notify(gst,$("bg"),"%s",%d,"%s");', $text, $tout,$butt);
882 }
883
884
885
886
887 function briscola_show($bri, $table, $user)
888 {
889   $ptnadd = "";
890   $ret = "";
891
892   if ($table->asta_card == 9) 
893     $ptnadd = sprintf("<br>con %d punti", $table->asta_pnt);
894   
895   /* text of caller cell */
896   if ($user->table_pos == $table->asta_win) 
897     $ret .= sprintf('$("callerinfo").innerHTML = "Chiami%s:";', $ptnadd);
898   else 
899     $ret .= sprintf('$("callerinfo").innerHTML = "Chiama %s%s:";', 
900                     xcape($bri->user[$table->player[$table->asta_win]]->name), $ptnadd);
901
902   $ret .= sprintf('$("caller").style.backgroundImage = \'url("img/brisk_caller_sand%d.png")\';',
903                   $table->asta_win);
904   $ret .= sprintf('$("callerimg").src = "img/%02d.png";', $table->briscola);
905   $ret .= sprintf('$("caller").style.visibility = "visible";');
906   $ret .= sprintf('$("chooseed").style.visibility = "hidden";');
907   $ret .= sprintf('$("asta").style.visibility = "hidden";');
908   $ret .= sprintf('show_astat(-2,-2,-2,-2,-2);');
909   
910   return ($ret);
911 }
912
913
914 function game_result($asta_pnt, $pnt)
915 {
916   if ($asta_pnt == 61) {
917     if ($pnt > 60)
918       return (1);
919     else if ($pnt == 60)
920       return (0);
921     else
922       return (-1);
923   }
924   else {
925     if ($pnt >= $asta_pnt)
926       return (1);
927     else
928       return (-1);
929   }
930 }
931
932 function multoval($mult)
933 {
934   if ($mult == 2)
935     return ("doppio");
936   else if ($mult == 4)
937     return ("quadruplo");
938   else
939     return (sprintf("%d-plo", $mult));
940 }
941
942 function show_table_info(&$bri, &$table, $table_pos)
943 {
944   $pnt_min = $table->points_n - MAX_POINTS < 0 ? 0 : $table->points_n - MAX_POINTS;
945   $noty = sprintf('<table class=\"points\"><tr><th></th>');
946   
947   // Names.
948   for ($i = 0 ; $i < PLAYERS_N ; $i++) 
949     $noty .= sprintf('<th class=\"td_points\">%s</th>', xcape($bri->user[$table->player[$i]]->name));
950   $noty .= sprintf("</tr>");
951
952   // Points.
953   log_main("show_table_info", "pnt_min: ".$pnt_min."   Points_n: ".$table->points_n);
954
955   for ($i = $pnt_min ; $i < $table->points_n ; $i++) {
956     $noty .= sprintf('<tr><th class=\"td_points\">%d</th>', $i+1);
957     for ($e = 0 ; $e < PLAYERS_N ; $e++) 
958       $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->points[$i % MAX_POINTS][$e]);
959     $noty .= "</tr>";
960   }
961
962   // Total points.
963   $noty .= '<tr><th class=\"td_points\">Tot.</th>';
964   for ($e = 0 ; $e < PLAYERS_N ; $e++) 
965     $noty .= sprintf('<td class=\"td_points\">%d</td>', $table->total[$e]);
966   $noty .= "</tr></table>";
967
968   if ($table->old_win != -1) {
969     $win = $table->player[$table->old_win];
970     $fri = $table->player[$table->old_friend];
971
972     $wol = game_result($table->old_asta_pnt, $table->old_pnt);
973
974     if ($win != $fri) {
975       $noty .= sprintf("<hr>Nell'ultima mano ha chiamato <b>%s</b>, il socio era <b>%s</b>,<br>", 
976                        xcape($bri->user[$win]->name),
977                        xcape($bri->user[$fri]->name));
978       if ($table->old_pnt == 120) {
979         $noty .= sprintf("hanno fatto <b>cappotto</b> EBBRAVI!.<hr>");
980       }
981       else {
982         $noty .= sprintf("dovevano fare <b>%s</b> punti e ne hanno fatti <b>%d</b>: hanno <b>%s</b>.<hr>",
983                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
984                           'pi&ugrave; di 60'), $table->old_pnt,
985                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
986       }
987     }
988     else {
989       $noty .= sprintf("<hr>Nell'ultima mano <b>%s</b> si &egrave; chiamato in mano,<br>", 
990                        xcape($bri->user[$win]->name));
991       if ($table->old_pnt == 120) {
992         $noty .= sprintf("ha fatto <b>cappotto</b> EBBRAVO!.<hr>");
993       }
994       else {
995         $noty .= sprintf("doveva fare <b>%s</b> punti e ne ha fatti <b>%d</b>: ha <b>%s</b>.<hr>",
996                          ($table->old_asta_pnt > 61 ? "almeno ".$table->old_asta_pnt :
997                           'pi&ugrave; di 60'), $table->old_pnt,
998                          ($wol == 1 ? "vinto" : ($wol == 0 ? "pareggiato" : "perso")));
999       }
1000     }
1001   }
1002   if ($table->mazzo == $table_pos) 
1003     $noty .= "Fai <b>tu</b> il mazzo.";
1004   else {
1005     $unam = xcape($bri->user[$table->player[$table->mazzo]]->name);
1006     $noty .= "Il mazzo a <b>$unam</b>.";
1007   }
1008
1009   if ($table->mult > 1) {
1010     $noty .= sprintf(" La partita vale <b>%s</b>.", multoval($table->mult));
1011   }
1012   $noty .= "<hr><br>";
1013
1014   $ret .= show_notify($noty, 3000, "torna alla partita");
1015   
1016   return ($ret);
1017 }
1018
1019
1020
1021 function show_room(&$bri, &$user)
1022 {
1023   $ret .= sprintf('gst.st = %d;',  $user->step);
1024   $ret .= sprintf('stat = "%s";',  $user->stat);
1025   $ret .= sprintf('subst = "%s";', $user->subst);
1026   $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1027   for ($i = 0 ; $i < TABLES_N ; $i++) {
1028     $ret .= table_content($bri, $user, $i);
1029     $act_content = table_act_content(($user->subst == 'standup'), 
1030                                      $bri->table[$i]->player_n, $i, $user->table);
1031     $ret .= sprintf('$("table_act%d").innerHTML = "%s";', $i, $act_content);
1032   }
1033   $ret .= standup_content($bri, $user);
1034   
1035   return ($ret);
1036 }
1037
1038
1039
1040 /* show table 
1041 is_transition (is from room to table ?)
1042 is_again      (is another game)
1043  */
1044 function show_table(&$bri, &$user, $sendstep, $is_transition, $is_again)
1045 {
1046   $table_idx = $user->table;
1047   $table = &$bri->table[$table_idx];
1048
1049   /****************
1050    FOR RELOAD:
1051      DONE - user names
1052      handed cards
1053      tabled cards
1054      taked  cards
1055      remark on/off
1056      cards dnd (and gameable card if its turn)
1057      who call and what
1058   ****************/
1059  
1060
1061   $ret = "table_init();";
1062   
1063   if (!$is_again) {
1064     /* GENERAL STATUS */
1065     $ret .= sprintf( 'gst.st = %d; stat = "%s"; subst = "%s"; table_pos = %d;',
1066                      $sendstep, $user->stat, $user->subst, $user->table_pos);
1067     /* BACKGROUND */
1068     $ret .= "background_set();";
1069     
1070     /* USERS INFO */
1071     $ret .= sprintf('$("myname").innerHTML = "<b>%s</b>";', xcape($user->name,ENT_COMPAT,"UTF-8"));
1072     $ret .= sprintf('set_names(" %s", " %s", " %s", " %s", " %s"); ',
1073                     xcape($bri->user[$table->player[($user->table_pos)%PLAYERS_N]]->name),
1074                     xcape($bri->user[$table->player[($user->table_pos+1)%PLAYERS_N]]->name),
1075                     xcape($bri->user[$table->player[($user->table_pos+2)%PLAYERS_N]]->name),
1076                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($user->table_pos+3)%PLAYERS_N]]->name)),
1077                     (PLAYERS_N == 3 ? "" :  xcape($bri->user[$table->player[($user->table_pos+4)%PLAYERS_N]]->name)));
1078   }
1079   /* NOTIFY FOR THE CARD MAKER */
1080   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1081     $ret .= show_table_info(&$bri, &$table, $user->table_pos);
1082   }
1083
1084   /* CARDS */
1085   if ($is_transition) { //  && $user->subst ==  "asta" superfluo
1086     $ret .= "|";
1087     
1088     for ($i = 0 ; $i < 8 ; $i++) {
1089       for ($e = 0 ; $e < PLAYERS_N ; $e++) {
1090         $ct = 0;
1091         for ($o = 0 ; $o < 40 && $ct < $i+1 ; $o++) {
1092           if ($table->card[$o]->owner == (($e + $table->gstart) % PLAYERS_N)) {
1093             $ct++;
1094             if ($ct == $i+1)
1095               break;
1096           }
1097         }
1098         log_rd($sess, "O ".$o." VAL ".$table->card[$o]->value." Owner: ".$table->card[$o]->owner);
1099         
1100         $ret .= sprintf( ' card_send(%d,%d,%d,%f,%d);|', ($table->gstart + $e) % PLAYERS_N, 
1101                          $i, ((($e + PLAYERS_N - $user->table_pos + $table->gstart) % PLAYERS_N) == 0 ?
1102                               $table->card[$o]->value : -1), 
1103                          ($i == 7 && $e == (PLAYERS_N - 1) ? 1 : 0.5),$i+1);
1104       }
1105     }    
1106   }
1107   else {
1108     $taked  = array(0,0,0,0,0);
1109     $inhand = array(0,0,0,0,0);
1110     $ontabl  = array(-1,-1,-1,-1,-1);
1111     $cards  = array();
1112
1113     for ($i = 0 ; $i < 40 ; $i++) {
1114       if ($table->card[$i]->stat == 'hand') {
1115         if ($table->card[$i]->owner == $user->table_pos) {
1116           $cards[$inhand[$table->card[$i]->owner]] = $table->card[$i]->value;
1117         }
1118         $inhand[$table->card[$i]->owner]++;
1119       }
1120       else if ($table->card[$i]->stat == 'take') {
1121         log_main("Card taked:", $table->card[$i]->value."OWN: ".$table->card[$i]->owner);
1122         $taked[$table->card[$i]->owner]++;
1123       }
1124       else if ($table->card[$i]->stat == 'table') {
1125         $ontabl[$table->card[$i]->owner] = $i;
1126       }
1127     }
1128     $logg = "\n";
1129     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1130       $logg .= sprintf("INHAND: %d   IN TABLE %d   TAKED %d\n", $inhand[$i], $ontabl[$i], $taked[$i]);
1131     }
1132     log_main("Stat table:", $logg);
1133
1134     /* Set ours cards. */
1135     $oursarg = "";
1136     for ($i = 0 ; $i < $inhand[$user->table_pos] ; $i++) 
1137       $oursarg .= ($i == 0 ? "" : ", ").$cards[$i];
1138     for ($i = $inhand[$user->table_pos] ; $i < 8 ; $i++) 
1139       $oursarg .= ($i == 0 ? "" : ", ")."-1";
1140     $ret .= sprintf('card_setours(%s);', $oursarg);
1141
1142     /* Dispose all cards */
1143     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1144       /* Qui sotto al posto di + 1 c'era + ->gstart ... credo in modo errato */
1145       $ret .= sprintf('cards_dispose(%d,%d,%d);', $i,
1146                       $inhand[$i], $taked[$i]);
1147
1148       if ($ontabl[$i] != -1) {
1149         $ret .= sprintf('card_place(%d,%d,%d,%d,%d);',$i, $inhand[$i], 
1150                         $table->card[$ontabl[$i]]->value, 
1151                         $table->card[$ontabl[$i]]->x, $table->card[$ontabl[$i]]->y);
1152       }
1153     }
1154   }
1155
1156   /* Show auction */
1157   if ($user->subst == 'asta') {
1158
1159     /* show users auction status */
1160     $showst = "";
1161     for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1162       $user_cur = &$bri->user[$table->player[$i]];
1163       $showst .= sprintf("%s%d", ($i == 0 ? "" : ", "), 
1164                          ($user_cur->asta_card < 9 ? $user_cur->asta_card : $user_cur->asta_pnt));
1165     }
1166     if (PLAYERS_N == 3)
1167         $showst .= ",-2,-2";
1168     $ret .= sprintf('show_astat(%s);', $showst);
1169
1170     if ($table->asta_win != -1 && $table->asta_win == $user->table_pos) {
1171       /* show card chooser */
1172       $ret .= sprintf('choose_seed(%s); $("asta").style.visibility = "hidden";',
1173                       $table->asta_card);
1174     }
1175     else {
1176       /* show auction */
1177       if ($user->table_pos == ($table->gstart % PLAYERS_N) &&
1178           $table->asta_win == -1) 
1179         $ret .= sprintf('dispose_asta(%d,%d);', 
1180                         $table->asta_card + 1, $table->asta_pnt+1);
1181       else
1182         $ret .= sprintf('dispose_asta(%d,%d);',
1183                         $table->asta_card + 1, -($table->asta_pnt+1));
1184     }
1185
1186     /* Remark */
1187     if ($table->asta_win == -1) { // auction case
1188       if ($user->table_pos == ($table->gstart % PLAYERS_N)) 
1189         $ret .= "remark_on();";
1190       else
1191         $ret .= "remark_off();";
1192     }
1193     else { // chooseed case
1194       if ($user->table_pos == $table->asta_win) 
1195         $ret .= "remark_on();";
1196       else
1197         $ret .= "remark_off();";
1198     }
1199   }
1200   else if ($user->subst == 'game') {
1201     /* HIGHLIGHT */
1202     if (($table->gstart + $table->turn) % PLAYERS_N == $user->table_pos) 
1203       $ret .= "is_my_time = true; remark_on();";
1204     else
1205       $ret .= "remark_off();";
1206     
1207     /* WHO CALL AND WATH */
1208     $ret .= briscola_show($bri, $table, $user);
1209     
1210   }
1211   return ($ret);
1212   }
1213
1214 function calculate_winner(&$table)
1215 {
1216   $briontab = FALSE;
1217   $ontab = array();
1218   $ontid = array();
1219   $cur_win  =  -1;
1220   $cur_val  = 100;
1221   $cur_seed = $table->briscola - ($table->briscola % 10);
1222
1223   for ($i = 0 ; $i < 40 ; $i++) {
1224     if ($table->card[$i]->stat != "table")
1225       continue;
1226
1227     log_wr($sess, sprintf("Card On table: [%d]", $i));
1228
1229     $v = $table->card[$i]->value; 
1230     $ontab[$table->card[$i]->owner] = $v;
1231     $ontid[$table->card[$i]->owner] = $i;
1232     /* se briscola setto il flag */
1233     if (($v - ($v % 10)) == $cur_seed)
1234       $briontab = TRUE;
1235   }
1236
1237   if ($briontab == FALSE) {
1238     $cur_win  = $table->gstart;
1239     $cur_val  = $ontab[$cur_win];
1240     $cur_seed = $cur_val - ($cur_val % 10);
1241   }
1242
1243   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1244     if (($ontab[$i] - ($ontab[$i] % 10)) == $cur_seed) {
1245       if ($ontab[$i] < $cur_val) {
1246         $cur_val = $ontab[$i];
1247         $cur_win = $i;
1248       }
1249     }
1250   }
1251
1252   for ($i = 0 ; $i < PLAYERS_N ; $i++) {
1253     $table->card[$ontid[$i]]->owner = $cur_win;
1254     $table->card[$ontid[$i]]->stat =  "take";
1255   }
1256   return ($cur_win);
1257 }
1258
1259 function calculate_points(&$table)
1260 {
1261   $all_points = array( 11,10,4,3,2, 0,0,0,0,0 );
1262
1263   $pro = 0;
1264
1265   if ($table->asta_pnt == 60)
1266     $table->asta_pnt = 61;
1267
1268   $table->old_win = $table->asta_win;
1269   $table->old_friend = $table->friend;
1270   $table->old_asta_pnt = $table->asta_pnt;
1271
1272   for ($i = 0 ; $i < 40 ; $i++) {
1273     $ctt = $table->card[$i]->value % 10;
1274     $own = $table->card[$i]->owner;
1275     if ($own == $table->asta_win || $own == $table->friend) 
1276       $pro += $all_points[$ctt];
1277   }
1278
1279   log_wr("XXX", sprintf("PRO: [%d]", $pro));
1280
1281   
1282   if ($table->asta_pnt == 61 && $pro == 60) { // PATTA !
1283     $table->points[$table->points_n % MAX_POINTS] = array();
1284     for ($i = 0 ; $i < PLAYERS_N ; $i++) 
1285       $table->points[$table->points_n % MAX_POINTS][$i] = 0;
1286     $table->points_n++;
1287     $table->old_pnt = $pro;
1288     $table->mult *= 2;
1289
1290     return;
1291   }
1292
1293   if ($pro >= $table->asta_pnt) 
1294     $sig = 1;
1295   else
1296     $sig = -1;
1297
1298   $table->points[$table->points_n % MAX_POINTS] = array();
1299   for ($i = 0 ; $i < 5 ; $i++) {
1300     if ($i == $table->asta_win) 
1301       $pt = ($i == $table->friend ? 4 : 2);
1302     else if ($i == $table->friend) 
1303       $pt = 1;
1304     else
1305       $pt = -1;
1306
1307     log_wr("XXX", sprintf("PRO: pt[%d][%d] = %d", $table->points_n % MAX_POINTS, $i, $pt));
1308
1309     $pt = $pt * $sig * $table->mult * ($pro == 120 ? 2 : 1);
1310
1311     log_wr("XXX", sprintf("PRO:[%d][%d][%d]", $sig, $table->mult, ($pro == 120 ? 2 : 1)));
1312     
1313     $table->points[$table->points_n % MAX_POINTS][$i] = $pt;
1314     $table->total[$i] += $pt;
1315   }
1316   $table->points_n++;
1317   $table->old_pnt = $pro;
1318   $table->mult = 1;
1319 }
1320
1321 ?>