small fixes, typo, etc
[e-DoKo.git] / index.php
1 <?php
2 error_reporting(E_ALL);
3
4 global $REV;
5 $REV  ="\$Rev$";
6
7 include_once("config.php");      
8 include_once("output.php");      /* html output only */
9 include_once("db.php");          /* database only */
10 include_once("functions.php");   /* the rest */
11
12 /* check if some variables are set in the config file, else set defaults */
13 if(!isset($EmailName))
14      $EmailName="[DoKo] ";
15
16
17 /* in case work has to be done on the database or other section we can
18  * shut down the server and tell people to come back later 
19  */
20 if(0) 
21   {
22     output_header();
23     echo "Working on the database...please check back in a few mintues"; 
24     output_footer(); 
25     exit(); 
26   }
27
28 if(DB_open()<0)
29   {
30     output_header();
31     echo "Database error, can't connect...";
32     output_footer(); 
33     exit(); 
34   }
35
36 /* done major error checking, output header of HTML page */
37 output_header();
38
39 /* check if we want to start a new game */
40 if(myisset("new"))
41   {
42     $names = DB_get_all_names();
43     output_form_for_new_game($names);
44   }
45 /*check if everything is ready to set up a new game */
46  else if( myisset("PlayerA", "PlayerB","PlayerC","PlayerD","dullen","schweinchen" ))
47   {
48     $PlayerA = $_REQUEST["PlayerA"];
49     $PlayerB = $_REQUEST["PlayerB"];
50     $PlayerC = $_REQUEST["PlayerC"];
51     $PlayerD = $_REQUEST["PlayerD"];
52
53     $dullen      = $_REQUEST["dullen"];
54     $schweinchen = $_REQUEST["schweinchen"];
55     
56     $EmailA  = DB_get_email_by_name($PlayerA);
57     $EmailB  = DB_get_email_by_name($PlayerB);
58     $EmailC  = DB_get_email_by_name($PlayerC);
59     $EmailD  = DB_get_email_by_name($PlayerD);
60     
61     if($EmailA=="" || $EmailB=="" || $EmailC=="" || $EmailD=="")
62       {
63         echo "couldn't find one of the names, please start a new game";
64         output_footer();
65         DB_close();
66         exit();
67       }
68     
69     $useridA  = DB_get_userid_by_name($PlayerA);
70     $useridB  = DB_get_userid_by_name($PlayerB);
71     $useridC  = DB_get_userid_by_name($PlayerC);
72     $useridD  = DB_get_userid_by_name($PlayerD);
73     
74     /* create random numbers */
75     $randomNR       = create_array_of_random_numbers();
76     $randomNRstring = join(":",$randomNR);
77     
78     /* get ruleset information or create new one */
79     $ruleset = DB_get_ruleset($dullen,$schweinchen);
80     if($ruleset <0) 
81       {
82         echo "Error defining ruleset: $ruleset";
83         output_footer();
84         DB_close();
85         exit();
86       };
87     
88     /* create game */
89     $followup = NULL;
90     if(myisset("followup") )
91       {
92         $followup= $_REQUEST["followup"];
93         $session = DB_get_session_by_gameid($followup);
94         $ruleset = DB_get_ruleset_by_gameid($followup); /* just copy ruleset from old game, 
95                                                          this way no manipulation is possible */
96         if($session)
97           mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,NULL,'1','pre',".
98                       "'$ruleset','$session' ,NULL)");
99         else
100           {
101             /* get max session */
102             $max = DB_get_max_session();
103             $max++;
104             mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,NULL,'1','pre',".
105                         "'$ruleset','$max' ,NULL)");
106             mysql_query("UPDATE Game SET session='".$max."' WHERE id=".DB_quote_smart($followup));
107           }
108       }
109     else
110       mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,NULL,'1','pre', ".
111                   "'$ruleset',NULL ,NULL)");
112     $game_id = mysql_insert_id();
113     
114     /* create hash */
115     $TIME  = (string) time(); /* to avoid collisions */
116     $hashA = md5("AGameOfDoko".$game_id.$PlayerA.$EmailA.$TIME);
117     $hashB = md5("AGameOfDoko".$game_id.$PlayerB.$EmailB.$TIME);
118     $hashC = md5("AGameOfDoko".$game_id.$PlayerC.$EmailC.$TIME);
119     $hashD = md5("AGameOfDoko".$game_id.$PlayerD.$EmailD.$TIME);
120     
121     /* create hands */
122     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridA).
123                 ", ".DB_quote_smart($hashA).", 'start','1',NULL,NULL,NULL,NULL)");
124     $hand_idA = mysql_insert_id();                                                             
125     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridB).
126                 ", ".DB_quote_smart($hashB).", 'start','2',NULL,NULL,NULL,NULL)");
127     $hand_idB = mysql_insert_id();                                                             
128     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridC).
129                 ", ".DB_quote_smart($hashC).", 'start','3',NULL,NULL,NULL,NULL)");
130     $hand_idC = mysql_insert_id();                                                             
131     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridD).
132                 ", ".DB_quote_smart($hashD).", 'start','4',NULL,NULL,NULL,NULL)");
133     $hand_idD = mysql_insert_id();
134     
135     /* save cards */
136     for($i=0;$i<12;$i++)
137       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idA', '".$randomNR[$i]."', 'false')");
138     for($i=12;$i<24;$i++)
139       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idB', '".$randomNR[$i]."', 'false')");
140     for($i=24;$i<36;$i++)
141       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idC', '".$randomNR[$i]."', 'false')");
142     for($i=36;$i<48;$i++)
143       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idD', '".$randomNR[$i]."', 'false')");
144     
145     /* send out email, TODO: check for error with email */
146     $message = "\n".
147       "you are invited to play a game of DoKo (that is to debug the program ;).\n".
148       "Place comments and bug reports here:\n".
149       "http://wiki.nubati.net/index.php?title=EmailDoko\n\n".
150       "The whole round would consist of the following players:\n".
151       "$PlayerA\n".
152       "$PlayerB\n".
153       "$PlayerC\n".
154       "$PlayerD\n\n".
155       "If you want to join this game, please follow this link:\n\n".
156       "".$host."?me=";
157     
158     mymail($EmailA,"You are invited to a game of DoKo","Hello $PlayerA,\n".$message.$hashA);
159     mymail($EmailB,"You are invited to a game of DoKo","Hello $PlayerB,\n".$message.$hashB);
160     mymail($EmailC,"You are invited to a game of DoKo","Hello $PlayerC,\n".$message.$hashC);
161     mymail($EmailD,"You are invited to a game of DoKo","Hello $PlayerD,\n".$message.$hashD);
162     
163     echo "You started a new game. The emails have been sent out!";    
164   }    /* end set up a new game */
165 /* cancle a game, if nothing has happend in the last N minutes */
166 else if(myisset("cancle","me"))
167   {
168     $me = $_REQUEST["me"];
169     
170     /* test for valid ID */
171     $myid = DB_get_userid_by_hash($me);
172     if(!$myid)
173       {
174         echo "Can't find you in the database, please check the url.<br />\n";
175         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
176         output_footer();
177         DB_close();
178         exit();
179       }
180     
181     DB_update_user_timestamp($myid);
182     
183     /* get some information from the DB */
184     $gameid   = DB_get_gameid_by_hash($me);
185     $myname   = DB_get_name_by_hash($me);
186     
187     /* check if game really is old enough */
188     $result = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
189     $r = mysql_fetch_array($result,MYSQL_NUM);
190     if(time()-strtotime($r[0]) > 60*60*24*30) /* = 1 month */
191       {
192         $message = "Hello, \n\n".
193           "Game $gameid has been cancled since nothing happend for a while and $myname requested it.\n";
194         
195         $userids = DB_get_all_userid_by_gameid($gameid);
196         foreach($userids as $user)
197           {
198             $To = DB_get_email_by_userid($user);
199             mymail($To,$EmailName."game $gameid cancled (timed out)",$message);
200           }
201         
202         /* delete everything from the dB */
203         DB_cancel_game($me);
204         
205         echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
206       }
207     else
208       echo "<p>You need to wait longer before you can cancle a game...</p>\n";
209   }
210 /* handle request from one specific player for one game,
211  * (the hash is set on a per game base) */
212 else if(myisset("me"))
213   {
214     $me = $_REQUEST["me"];
215     
216     /* test for valid ID */
217     $myid = DB_get_userid_by_hash($me);
218     if(!$myid)
219       {
220         echo "Can't find you in the database, please check the url.<br />\n";
221         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
222         output_footer();
223         DB_close();
224         exit();
225       }
226
227     /* the user had done something, update the timestamp */
228     DB_update_user_timestamp($myid);
229     
230     /* get some information from the DB */
231     $gameid   = DB_get_gameid_by_hash($me);
232     $myname   = DB_get_name_by_hash($me);
233     $mystatus = DB_get_status_by_hash($me);
234     $mypos    = DB_get_pos_by_hash($me);
235     $myhand   = DB_get_handid_by_hash($me);
236
237     /* get prefs and save them */
238     DB_get_PREF($myid);
239     /* end set pref */
240       
241       
242     /* get rule set for this game */
243     $result = mysql_query("SELECT * FROM Rulesets".
244                           " LEFT JOIN Game ON Game.ruleset=Rulesets.id ".
245                           " WHERE Game.id='$gameid'" );
246     $r      = mysql_fetch_array($result,MYSQL_NUM);
247
248     $RULES["dullen"]      = $r[2];
249     $RULES["schweinchen"] = $r[3];
250     $RULES["call"]        = "1st-own-card";
251
252
253     /* get some infos about the game */
254     $gametype   = DB_get_gametype_by_gameid($gameid);
255     $gamestatus = DB_get_game_status_by_gameid($gameid);
256     $GT         = $gametype;
257     if($gametype=="solo")
258       {
259         $gametype = DB_get_solo_by_gameid($gameid);
260         $GT  = $gametype." ".$GT;
261       }
262
263     /* display rule set for this game */
264     echo "<div class=\"ruleset\">\n";
265
266     if($gamestatus != 'pre')
267       echo " Gametype: $GT <br />\n";
268     
269     echo "Rules: <br />\n";
270     echo "10ofhearts : ".$r[2]."<br />\n";
271     echo "schweinchen: ".$r[3]."<br />\n";
272     echo "</div>\n";
273     
274     /* does anyone have both foxes */
275     $GAME["schweinchen"]=0; 
276     for($i=1;$i<5;$i++)
277       {
278         $hash  = DB_get_hash_from_game_and_pos($gameid,$i);
279         $cards = DB_get_all_hand($hash);
280         if( in_array("19",$cards) && in_array("20",$cards) )
281           {
282             $GAME["schweinchen"]=1;
283             $GAME["schweinchen-who"]=$hash;
284           }
285       };
286
287     /* mystatus gets the player through the different stages of a game.
288      * start:    yes/no
289      * init:     check values from start,
290      *           check for sickness
291      * check:    check for return values from init
292      * poverty:  handle poverty, wait here until all player have reached this state
293      *           display sickness and move on to game
294      * play:     game in progress
295      * gameover: are we revisiting a game
296      */
297     switch($mystatus)
298       {
299       case 'start':
300         check_want_to_play($me);
301         /* move on to the next stage*/
302         DB_set_hand_status_by_hash($me,'init');
303         break;
304       case 'init':
305         /* first check if everything went ok  in the last step
306          * if not, send user back, if yes, check what he did
307          */
308         if( !myisset("in") )
309           {
310             echo "<p> you need to answer the <a href=\"$host?me=$me\">question</a>.</p>";
311             DB_set_hand_status_by_hash($me,'start');
312           }
313         else
314           {
315             if($_REQUEST["in"] == "no")
316               {
317                 /* cancle the game */
318                 $message = "Hello, \n\n".
319                   "the game has been canceled due to the request of one of the players.\n";
320                 
321                 $userids = DB_get_all_userid_by_gameid($gameid);
322                 foreach($userids as $user)
323                   {
324                     $To = DB_get_email_by_userid($user);
325                     mymail($To,$EmailName."game $gameid canceled",$message);
326                   }
327                 
328                 /* delete everything from the dB */
329                 DB_cancel_game($me);
330               }
331             else
332               {
333                 echo "thanks for joining the game...";
334                 
335                 $mycards = DB_get_hand($me);
336                 sort($mycards);
337                 echo "<p class=\"mycards\" style=\"margin-top:8em;\">your cards are: <br />\n";
338                 foreach($mycards as $card) 
339                   display_card($card,$PREF["cardset"]);
340                 echo "</p>\n";   
341                 
342                 output_check_for_sickness($me,$mycards);
343                 
344                 /* move on to the next stage*/
345                 DB_set_hand_status_by_hash($me,'check');
346               }
347           }
348         break;
349
350     case 'check':
351       /* ok, user is in the game, saw his cards and selected his vorbehalt
352        * so first we check what he selected
353        */
354       echo "Processing what you selected in the last step...<br />";
355
356       if(!myisset("solo","wedding","poverty","nines") )
357         {
358           /* all these variables have a pre-selected default,
359            * so we should never get here,
360            * unless a user tries to cheat ;) */
361           echo "something went wrong...please contact the admin.";
362         }
363       else
364         {
365           /* check if this sickness needs to be handled first */
366           $gametype    = DB_get_gametype_by_gameid($gameid);
367           $startplayer = DB_get_startplayer_by_gameid($gameid);
368           
369           if( $_REQUEST["solo"]!="No")
370             {
371               /* user wants to play a solo */
372
373               /* store the info in the user's hand info */
374               DB_set_solo_by_hash($me,$_REQUEST["solo"]);
375               DB_set_sickness_by_hash($me,"solo");
376
377               echo "<br />Seems like you want to play a ".$_REQUEST["solo"]." solo. Got it.<br />\n";
378               
379               if($gametype == "solo" && $startplayer<$mypos)
380                 {}/* do nothing, since someone else already is playing solo */
381               else
382                 {
383                   /* this solo comes first 
384                    * store info in game table
385                    */
386                   DB_set_gametype_by_gameid($gameid,"solo");
387                   DB_set_startplayer_by_gameid($gameid,$mypos);
388                   DB_set_solo_by_gameid($gameid,$_REQUEST["solo"]);
389                 };
390             }
391           else if($_REQUEST["wedding"] == "yes")
392             {
393               /* TODO: add silent solo somewhere*/
394               echo "Ok, you don't want to play a silent solo...wedding was chosen.<br />\n";
395               DB_set_sickness_by_hash($me,"wedding");
396             }
397           else if($_REQUEST["poverty"] == "yes")
398             {
399               echo "Don't think you can win with just a few trump...? ok, poverty chosen <br />\n";
400               DB_set_sickness_by_hash($me,"poverty");
401             }
402           else if($_REQUEST["nines"] == "yes")
403             {
404               echo "What? You just don't want to play a game because you have a few nines? Well, if no one".
405                 " is playing solo, this game will be canceled.<br />\n";
406               DB_set_sickness_by_hash($me,"nines");
407             }
408         }
409
410       echo " Ok, done with checking, please go to the <a href=\"$host?me=$me\">next step of the setup</a>.<br />";
411
412       /* move on to the next stage*/
413       DB_set_hand_status_by_hash($me,'poverty');
414
415       /* check if everyone has reached this stage, send out email */
416       $userids = DB_get_all_userid_by_gameid($gameid);
417       $ok=1;
418       foreach($userids as $user)
419         {
420           $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
421           if($userstat!='poverty' && $userstat!='play')
422             $ok=0;
423         };
424       if($ok)
425         foreach($userids as $user)
426           {
427             $To = DB_get_email_by_userid($user);
428             $userhash =DB_get_hash_from_gameid_and_userid($gameid,$user);
429             if($userhash!=$me)
430               {
431                 $message = "Everyone finish the questionary in game $gameid, ".
432                            "please visit this link now to continue: \n".
433                            " ".$host."?me=".$userhash."\n\n" ;
434                 mymail($To,$EmailName." finished setup",$message);
435               }
436           };
437
438       break;
439
440     case 'poverty':
441       /* here we need to check if there is a solo or some other form of sickness.
442        * If so, which one is the most important one
443        * set that one in the Game table
444        * tell people about it.
445        */
446       echo "<br /> Checking if someone else selected solo, nines or wedding or poverty.<br />";
447       
448       /* check if everyone has reached this stage */
449       $userids = DB_get_all_userid_by_gameid($gameid);
450       $ok=1;
451       foreach($userids as $user)
452         {
453           $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
454           if($userstat!='poverty' && $userstat!='play')
455             $ok=0;
456         };
457
458       if(!$ok)
459         {
460           echo "This step can only be handled after everyone finished the last step. ".
461                "Seems like this is not the case, so you need to wait a bit... ".
462                "you will get an email once that is the case, please use the link in ".
463                "that email to continue the game.<br />";
464         }
465       else
466         {
467           echo "Everyone has finished checking their cards, let's see what they said...<br />";
468
469           /* check what kind of game we are playing,  in case there are any solos this already 
470            *will have the correct information in it */
471           $gametype    = DB_get_gametype_by_gameid($gameid);
472           $startplayer = DB_get_startplayer_by_gameid($gameid);
473
474           /* check for different sickness and just output a general info */
475
476           
477           $nines = 0;
478           $poverty = 0;
479           $wedding = 0;
480           $solo = 0;
481           foreach($userids as $user)
482             {
483               $name = DB_get_name_by_userid($user);
484               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
485               if($usersick == 'nines')
486                 {
487                   $nines = $user;
488                   echo "$name has a Vorbehalt. <br />";
489                   break;
490                 }
491               else if($usersick == 'poverty')
492                 {
493                   $poverty++;
494                   echo "$name has a Vorbehalt. <br />";
495                 }
496               else if($usersick == 'wedding')
497                 {
498                   $wedding=$user;
499                   echo "$name has a Vorbehalt. <br />"  ;
500                 }
501               else if($usersick == 'solo')
502                 {
503                   $solo++;
504                   echo "$name has a Vorbehalt. <br />"  ;
505                 }
506             }
507
508           /* now check which sickness comes first and set the gametype to it */
509
510           /* gamestatus == normal, => cancel game */
511           if($gametype == "solo")
512             {
513               /* do nothing */
514             }
515           else if($nines)
516             {
517               /* cancle game */
518               /* TODO: should we keep statistics of this? */
519               $message = "Hello, \n\n".
520                 "the game has been canceled because ".DB_get_name_by_userid($nines).
521                 " has five or more nines and nobody is playing solo.\n";
522               
523               /* TODO: add info about redeal in case this is a game of a series */
524               
525               $userids = DB_get_all_userid_by_gameid($gameid);
526               foreach($userids as $user)
527                 {
528                   $To = DB_get_email_by_userid($user);
529                   mymail($To,$EmailName."game $gameid canceled",$message);
530                 }
531               
532               /* delete everything from the dB */
533               DB_cancel_game($me);
534               
535               echo "The game has been canceled because ".DB_get_name_by_userid($nines).
536                 " has five or more nines and nobody is playing solo.\n";
537               output_footer();
538               DB_close();
539               exit();
540             }
541           else if($poverty==1)
542             {
543               DB_set_gametype_by_gameid($gameid,"poverty");
544               $gametype = "poverty";
545               $who=DB_get_sickness_by_gameid($gameid);
546               if(!$who)
547                 {
548                   $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
549                   if($firstsick == "poverty")
550                     DB_set_sickness_by_gameid($gameid,2); /* who needs to be asked first */
551                   else
552                     DB_set_sickness_by_gameid($gameid,1); /* who needs to be asked first */
553                 }
554             }
555           else if($poverty==2)
556             {
557               DB_set_gametype_by_gameid($gameid,"dpoverty");
558               $gametype = "dpoverty";
559               $who=DB_get_sickness_by_gameid($gameid);
560               if(!$who)
561                 {
562                   $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
563                   if($firstsick == "poverty")
564                     {
565                       $seconsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
566                       if($secondsick == "poverty")
567                         DB_set_sickness_by_gameid($gameid,30); /* who needs to be asked first */
568                       else
569                         DB_set_sickness_by_gameid($gameid,20); /* who needs to be asked first */
570                     }
571                   else
572                     DB_set_sickness_by_gameid($gameid,10); /* who needs to be asked first */
573                 }
574             }
575           else if($wedding> 0)
576             {
577               DB_set_gametype_by_gameid($gameid,"wedding");
578               DB_set_sickness_by_gameid($gameid,'-1'); /* wedding not resolved yet */
579               $gametype = "wedding";
580             };
581
582           echo "<br />\n";
583
584           /* now the gametype is set correctly (shouldn't matter that this is calculated for every user)
585            * output what kind of game we have */
586           
587           $poverty = 0;
588           foreach($userids as $user)
589             {
590               /* userids are sorted by position... 
591                * so output whatever the firstone has, then whatever the next one has
592                * stop when the sickness is the same as the gametype 
593                */
594               
595               $name     = DB_get_name_by_userid($user);
596               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
597
598               if($usersick)
599                 echo "$name has $usersick. <br />"; /*TODO: perhaps save this in a string and store in Game? */
600
601               if($usersick=="poverty")
602                 $poverty++;
603               if($usersick == "wedding" && $gametype =="wedding")
604                 break;
605               if($usersick == "poverty" && $gametype =="poverty")
606                 break;
607               if($usersick == "poverty" && $gametype =="dpoverty" && $poverty==2)
608                 break;
609               if($usersick == "solo" && $gametype =="solo")
610                 break;
611             };
612
613           /* output Schweinchen in case the rules need it */
614           if( $gametype != "solo")
615             if($GAME["schweinchen"] && $RULES["schweinchen"]=="both" )
616               echo DB_get_name_by_hash($GAME["schweinchen-who"])." has Schweinchen. <br />";
617           
618           echo "<br />\n";
619           
620           /* finished the setup, set re/contra parties if possible, go to next stage unless there is a case of poverty*/
621           switch($gametype)
622             {
623             case "solo":
624               /* are we the solo player? set us to re, else set us to contra */
625               $pos = DB_get_pos_by_hash($me);
626               if($pos == $startplayer)
627                 DB_set_party_by_hash($me,"re");
628               else
629                 DB_set_party_by_hash($me,"contra");
630               DB_set_hand_status_by_hash($me,'play');
631               break;
632
633             case "wedding":
634               /* set person with the wedding to re, do the rest during the game */
635               $usersick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
636               if($usersick == "wedding")
637                 DB_set_party_by_hash($me,"re");
638               else
639                 DB_set_party_by_hash($me,"contra");
640               
641               echo "Whoever will make the first trick will be on the re team. <br />\n";
642               echo " Ok, the game can start now, please finish <a href=\"$host?me=$me\">the setup</a>.<br />";       
643               DB_set_hand_status_by_hash($me,'play');
644               break;
645
646             case "normal":
647               $hand = DB_get_all_hand($me);
648               
649               if(in_array('3',$hand)||in_array('4',$hand))
650                 DB_set_party_by_hash($me,"re");
651               else
652                 DB_set_party_by_hash($me,"contra");
653               DB_set_hand_status_by_hash($me,'play');
654               break;
655             case "poverty":
656             case "dpoverty":
657               /* check if poverty resolved (e.g. DB.Game who set to NULL)
658                *   yes? =>trump was taken, start game; break; 
659                */
660               $who = DB_get_sickness_by_gameid($gameid);
661               if($who<0)
662                 { /* trump has been taken */
663                   DB_set_hand_status_by_hash($me,'play');
664                   break;
665                 };
666               
667               if($who>9) /*= two people still have trump on the table*/
668                 $add = 10;
669               else
670                 $add = 1;
671
672               /* check if we are being asked now
673                *    no? display wait message, e.g. player X is asked at the moment 
674                */
675               $usersick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
676               if(myisset("trump") && $_REQUEST["trump"]=="no" && ($who==$mypos || $who==$mypos*10))
677                 {
678                   /* user doesn't want to take trump */
679                   /* set next player who needs to be asked */
680                   $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
681                   $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
682                   
683                   if($firstsick=="poverty")
684                     {
685                       if($secondsick=="poverty")
686                         DB_set_sickness_by_gameid($gameid,$who+$add*3);
687                       else
688                         DB_set_sickness_by_gameid($gameid,$who+$add*2);
689                     }
690                   else
691                     DB_set_sickness_by_gameid($gameid,$who+$add);
692
693                   /* email next player */
694                   $who = DB_get_sickness_by_gameid($gameid);
695                   if($who>9) $who = $who/10;
696                   
697                   if($who<=4)
698                     {
699                       $To       = DB_get_email_by_pos_and_gameid($who,$gameid);
700                       $userhash = DB_get_hash_from_game_and_pos($gameid,$who);
701                       
702                       $message = "Someone has poverty, it's your turn to decide, if you want to take the trump. Please visit:".
703                         " ".$host."?me=".$userhash."\n\n" ;
704                       mymail($To,$EmailName." poverty",$message);
705                     }
706
707                   /* this user is done */
708                   DB_set_hand_status_by_hash($me,'play');
709                   break;                
710                 }
711               else if(myisset("trump") && !myisset("exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
712                 {
713                   /* user wants to take trump */
714                   $trump = $_REQUEST["trump"];
715
716                   /* get hand id for user $trump */
717                   $userhand = DB_get_handid_by_gameid_and_userid($gameid,$trump);
718                   /* copy trump from player A to B */
719                   $result = mysql_query("UPDATE Hand_Card SET hand_id='$myhand' WHERE hand_id='$userhand' AND card_id<'27'" );
720                   
721                   /* add hidden button with trump in it to get to the next point */
722                   echo "<form action=\"index.php\" method=\"post\">\n";
723                   echo "  <input type=\"hidden\" name=\"exchange\" value=\"-1\" />\n";
724                   echo "  <input type=\"hidden\" name=\"trump\" value=\"".$trump."\" />\n";
725                   echo "  <input type=\"hidden\" name=\"me\" value=\"".$me."\" />\n";
726                   echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select cards to give back\" />\n";
727                   echo "</form>\n";
728                 }
729               else if(myisset("trump","exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
730                 {
731                   $trump    = $_REQUEST["trump"];
732                   $exchange = $_REQUEST["exchange"];
733                   $userhand = DB_get_handid_by_gameid_and_userid($gameid,$trump);
734
735                   /* if exchange is set to a value>0, exchange that card back to user $trump */
736                   if($exchange >0)
737                     {
738                       $result = mysql_query("UPDATE Hand_Card SET hand_id='$userhand'".
739                                             " WHERE hand_id='$myhand' AND card_id='$exchange'" );
740                     };
741                   
742                   /* if number of cards == 12, set status to play for both users */
743                   $result = mysql_query("SELECT COUNT(*) FROM Hand_Card  WHERE hand_id='$myhand'" );
744                   $r      = mysql_fetch_array($result,MYSQL_NUM);
745                   if(!$r)
746                     {
747                       die("error in poverty");
748                     };
749                   if($r[0]==12)
750                     {
751                       if($gametype=="poverty" || $who<9)
752                         {
753                           DB_set_sickness_by_gameid($gameid,-1); /* done with poverty */                          
754                         }
755                       else /* reduce poverty count by one, that is go to single digits $who */
756                         {
757                           $add = 1;
758                           $who = $who/10;
759
760                           /* whom to ask next */
761                           $firstsick  = DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
762                           $secondsick = DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
763
764                           if($firstsick!="poverty")
765                             DB_set_sickness_by_gameid($gameid,$who+$add);
766                           else
767                             {
768                               if($secondsick!="poverty")
769                                 DB_set_sickness_by_gameid($gameid,$who+$add*2);
770                               else
771                                 DB_set_sickness_by_gameid($gameid,$who+$add*3);
772                             };
773
774                           /* email next player */
775                           $who = DB_get_sickness_by_gameid($gameid);
776                           if($who<=4)
777                             {
778                               $To       = DB_get_email_by_pos_and_gameid($who,$gameid);
779                               $userhash = DB_get_hash_from_game_and_pos($gameid,$who);
780                               
781                               $message = "Someone has poverty, it's your turn to decide, ".
782                                          "if you want to take the trump. Please visit:".
783                                          " ".$host."?me=".$userhash."\n\n" ;
784                               mymail($To,$EmailName." poverty",$message);
785                             }
786
787                         }
788                       
789                       /* this user is done */
790                       DB_set_hand_status_by_hash($me,'play');
791                       /* and so is his partner */
792                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$trump);
793                       DB_set_hand_status_by_hash($hash,'play');
794
795                       /* set party to re, unless we had dpoverty, in that case check if we need to set re/contra*/
796                       $re_set=0;
797                       foreach($userids as $user)
798                         {
799                           $userhash =DB_get_hash_from_gameid_and_userid($gameid,$user);
800                           $party=DB_get_party_by_hash($userhash);
801                           if($party=="re")
802                             $re_set=1;
803                         }
804                       if($re_set)
805                         {
806                           DB_set_party_by_hash($me,"contra");
807                           DB_set_party_by_hash($hash,"contra");
808                         }
809                       else
810                         {
811                           foreach($userids as $user)
812                             {
813                               $userhash =DB_get_hash_from_gameid_and_userid($gameid,$user);
814                               if($userhash==$hash||$userhash==$me)
815                                 DB_set_party_by_hash($userhash,"re");
816                               else
817                                 DB_set_party_by_hash($userhash,"contra");
818                             }
819                         }
820
821
822                       break;
823                     }
824                   else
825                     {
826                       /* else show all trump, have lowest card pre-selected, have hidden setting for */
827                       echo "you need to get rid of a few cards<br />\n";
828                       
829                       set_gametype($gametype); /* this sets the $CARDS variable */
830                       $mycards = DB_get_hand($me);
831                       $mycards = mysort($mycards,$gametype);
832
833                       echo "<form class=\"exchange\" action=\"index.php\" method=\"post\">\n";
834                       $type="exchange";
835                       foreach($mycards as $card) 
836                         display_link_card($card,$PREF["cardset"],$type);
837                       echo "  <input type=\"hidden\" name=\"trump\" value=\"".$trump."\" />\n";
838                       echo "  <input type=\"hidden\" name=\"me\" value=\"".$me."\" />\n";
839                       echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select one card to give back\" />\n";
840                       echo "</form>\n";
841                     }
842                 }
843               else if($who == $mypos || $who == $mypos*10)
844                 {
845                   foreach($userids as $user)
846                     {
847                       $name = DB_get_name_by_userid($user);
848                       $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
849                       
850                       if($usersick=="poverty")
851                         {
852                           $hash =DB_get_hash_from_gameid_and_userid($gameid,$user);
853                           $cards=DB_get_hand($hash);
854                           $nrtrump=count_trump($cards);
855                           /* count trump */
856                           if($nrtrump<4)
857                             echo "Player $name has $nrtrump trump. Do you want to take them?".
858                               "<a href=\"index.php?me=$me&amp;trump=$user\">yes</a> <br />";
859                         }
860                     }
861                   echo "I don't want to take any trump: ".
862                     "<a href=\"index.php?me=$me&amp;trump=no\">yes</a> <br />";
863
864                   echo "Your cards are: <br />\n";
865                   $mycards = DB_get_hand($me);
866                   sort($mycards);
867                   echo "<p class=\"mycards\" style=\"margin-top:8em;\">your cards are: <br />\n";
868                   foreach($mycards as $card) 
869                     display_card($card,$PREF["cardset"]);
870                   echo "</p>\n";   
871                 }
872               else
873                 {
874                   $mysick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
875                   if($mysick=="poverty")
876                     echo "The others are asked if they want to take your trump, you have to wait (you'll get an email).";
877                   else
878                     echo "it's not your turn yet to decide if you want to take the trump or not.";
879                 }
880               /*
881                *    yes, display number of trump and user's hand, ask if he wants to take it 
882                *      no, set whom-to-ask to next player, email next player, cancle game if no next player
883                *      yes -> link to new page:display all cards, ask for N return cards
884                *          set re/contra 
885                *        
886                */
887             };
888         }
889       /* check if no one wanted to take trump, in that case the gamesickness would be set to 5 or 50 */
890       $who = DB_get_sickness_by_gameid($gameid);
891       if($who==5 || $who==50)
892         {
893           $message = "Hello, \n\n".
894             "Game $gameid has been cancled since nobody wanted to take the trump.\n";
895           
896           $userids = DB_get_all_userid_by_gameid($gameid);
897           foreach($userids as $user)
898             {
899               $To = DB_get_email_by_userid($user);
900               mymail($To,$EmailName."game $gameid cancled (poverty not resolved)",$message);
901             }
902           
903           /* delete everything from the dB */
904           DB_cancel_game($me);
905           
906           echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
907           output_footer();
908           DB_close();
909           exit();
910         }
911
912       /* check if all players are ready to play */
913       $ok=1;
914       foreach($userids as $user)
915         if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
916           $ok=0;
917
918       if($ok)
919         {
920           /* only set this after all poverty, etc. are handled*/
921           DB_set_game_status_by_gameid($gameid,'play');
922
923           /* email startplayer */
924           $startplayer = DB_get_startplayer_by_gameid($gameid);
925           $email       = DB_get_email_by_pos_and_gameid($startplayer,$gameid);
926           $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
927           
928           if($hash!=$me)
929             {
930               /* email startplayer) */
931               $message = "It's your turn now in game $gameid.\n".
932                 "Use this link to play a card: ".$host."?me=".$hash."\n\n" ;
933               mymail($email,$EmailName."ready, set, go... ",$message);
934             }
935           else
936             echo " Please, <a href=\"$host?me=$me\">start</a> the game.<br />";  
937         }
938       else
939         echo "\n <br />";        
940
941       break;
942     case 'play':
943     case 'gameover': 
944       /* both entries here,  so that the tricks are visible for both.
945        * in case of 'play' there is a break later that skips the last part
946        */
947       
948       /* figure out what kind of game we are playing, 
949        * set the global variables $CARDS["trump"],$CARDS["diamonds"],$CARDS["hearts"],
950        * $CARDS["clubs"],$CARDS["spades"],$CARDS["foxes"]
951        * accordingly
952        */
953       
954       $gametype = DB_get_gametype_by_gameid($gameid);
955       $GT = $gametype;
956       if($gametype=="solo")
957         {
958           $gametype = DB_get_solo_by_gameid($gameid);
959           $GT = $gametype." ".$GT;
960         }
961       else
962         $gametype="normal";
963       
964       set_gametype($gametype); /* this sets the $CARDS variable */
965       
966       /* get some infos about the game */
967       $gamestatus = DB_get_game_status_by_gameid($gameid);
968       
969       /* display useful things in divs */
970       
971       /* display links to the users status page */
972       $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
973       $r      = mysql_fetch_array($result,MYSQL_NUM);
974       
975       display_links($r[0],$r[1]);
976       
977       /* end display useful things*/
978       
979       /* has the game started? No, then just wait here...*/
980       if($gamestatus == 'pre')
981         {
982           echo "You finished the setup, but not everyone else finished it... ".
983                "so you need to wait for the others. Just wait for the an email... <br />";
984           break; /* not sure this works... the idea is that you can 
985                   * only  play a card after everyone is ready to play */
986         }
987       
988       /* display the table and the names */
989       $result = mysql_query("SELECT  User.fullname as name,".
990                             "        Hand.position as position, ".
991                             "        User.id, ".
992                             "        Hand.party as party, ".
993                             "        Hand.sickness as sickness, ".
994                             "        Hand.point_call, ".
995                             "        User.last_login ".
996                             "FROM Hand ".
997                             "LEFT JOIN User ON User.id=Hand.user_id ".
998                             "WHERE Hand.game_id='".$gameid."' ".
999                             "ORDER BY position ASC");
1000       
1001       echo "<div class=\"table\">\n".
1002         "  <img src=\"pics/table.png\" alt=\"table\" />\n";
1003       while($r = mysql_fetch_array($result,MYSQL_NUM))
1004         {
1005           $name  = $r[0];
1006           $pos   = $r[1];
1007           $user  = $r[2];
1008           $party = $r[3];
1009           $sickness  = $r[4];
1010           $call      = $r[5];
1011           $lastlogin = strtotime($r[6]);
1012           
1013           $offset = DB_get_user_timezone($user);
1014           $zone   = return_timezone($offset);
1015           date_default_timezone_set($zone);
1016
1017           echo " <span class=\"table".($pos-1)."\">\n";
1018           echo " $name ";
1019           /* add hints for poverty, wedding, solo, etc */
1020           if($GT=="poverty" && $party=="re")
1021             if($sickness=="poverty")
1022               {
1023                 $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1024                 $cards = DB_get_all_hand($userhash);
1025                 $trumpNR = count_trump($cards);
1026                 if($trumpNR)
1027                   echo "(poverty < trump back)";
1028                 else
1029                   echo "(poverty <)";
1030               }
1031             else
1032               echo "(poverty >)";
1033
1034           if($GT=="dpoverty")
1035             if($party=="re")
1036               if($sickness=="poverty")
1037                 {
1038                 $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1039                 $cards = DB_get_all_hand($userhash);
1040                 $trumpNR = count_trump($cards);
1041                 if($trumpNR)
1042                   echo "(poverty A < trump back)";
1043                 else
1044                   echo "(poverty A <)";
1045                 }
1046               else
1047                 echo "(poverty A >)";
1048             else
1049               if($sickness=="poverty")
1050                 {
1051                 $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1052                 $cards = DB_get_all_hand($userhash);
1053                 $trumpNR = count_trump($cards);
1054                 if($trumpNR)
1055                   echo "(poverty B < trump back)";
1056                 else
1057                   echo "(poverty B <)";
1058                 }
1059               else
1060                 echo "(poverty B >)";
1061               
1062           if($GT=="wedding" && $party=="re")
1063               if($sickness=="wedding")
1064                 echo "(wedding  +)";
1065               else
1066                 echo "(wedding)";
1067           
1068           if(ereg("solo",$GT) && $party=="re")
1069              echo "($GT)";
1070
1071           /* add point calls */
1072           if($call!=NULL)
1073             echo " $party $call ";
1074
1075           echo "<br />\n";
1076           echo " local time: ".date("Y-m-d H:i:s")."<br />\n";
1077           echo " last login: ".date("Y-m-d H:i:s",$lastlogin)."<br />\n";
1078           echo " </span>\n";
1079
1080         }
1081       echo  "</div>\n";
1082
1083       /* get everything relevant to display the tricks */
1084       $result = mysql_query("SELECT Hand_Card.card_id as card,".
1085                             "       Hand.position as position,".
1086                             "       Play.sequence as sequence, ".
1087                             "       Trick.id, ".
1088                             "       Comment.comment, ".
1089                             "       Play.create_date, ".
1090                             "       Hand.user_id ".
1091                             "FROM Trick ".
1092                             "LEFT JOIN Play ON Trick.id=Play.trick_id ".
1093                             "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
1094                             "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
1095                             "LEFT JOIN Comment ON Play.id=Comment.play_id ".
1096                             "WHERE Trick.game_id='".$gameid."' ".
1097                             "ORDER BY Trick.id,sequence ASC");
1098       $trickNR = 1;
1099       
1100       $lasttrick = DB_get_max_trickid($gameid);
1101       
1102       $play = array(); /* needed to calculate winner later  */
1103       $seq  = 1;          
1104       $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
1105       $firstcard = ""; /* first card in a trick */
1106       
1107       echo "\n<ul class=\"tricks\">\n";
1108       echo "  <li class=\"nohighlight\"> Game $gameid: </li>\n";
1109       
1110       while($r = mysql_fetch_array($result,MYSQL_NUM))
1111         {
1112           $pos     = $r[1];
1113           $seq     = $r[2];
1114           $trick   = $r[3];
1115           $comment = $r[4];
1116           $timeplayed = strtotime($r[5]);
1117           $user    = $r[6];
1118
1119           $offset = DB_get_user_timezone($user);
1120           $zone   = return_timezone($offset);
1121           date_default_timezone_set($zone);
1122
1123           /* check if first schweinchen has been played */
1124           if($r[0] == 19 || $r[0] == 20 )
1125             $GAME["schweinchen"]++;
1126           
1127           /* save card to be able to find the winner of the trick later */
1128           $play[$seq] = array("card"=>$r[0],"pos"=>$pos); 
1129           
1130           if($seq==1)
1131             {
1132               /* first card in a trick, output some html */
1133               if($trick!=$lasttrick)
1134                 {
1135                   /* start of an old trick? */
1136                   echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">Trick $trickNR</a>\n".
1137                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1138                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1139                 }
1140               else if($trick==$lasttrick)
1141                 {
1142                   /* start of a last trick? */
1143                   echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">Trick $trickNR</a>\n".
1144                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1145                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1146                 };
1147               
1148               /* remember first card, so that we are able to check, what cards can be played */
1149               $firstcard = $r[0];
1150             };
1151           
1152           /* display card */
1153           echo "      <div class=\"card".($pos-1)."\">\n";
1154           
1155           /* display comments */
1156           if($comment!="")
1157             echo "        <span class=\"comment\">".$comment."</span>\n";
1158           
1159           echo "        ";
1160           display_card($r[0],$PREF["cardset"]);
1161           
1162           echo "      </div>\n"; /* end div card */
1163           
1164           /* end of trick? */
1165           if($seq==4)
1166             {
1167               $trickNR++;
1168               echo "    </div>\n  </li>\n";  /* end div table, end li table */
1169             }
1170         }
1171       
1172       if($seq!=4 && $trickNR>1) 
1173         echo "    </div>\n  </li>\n";  /* end div table, end li table */
1174       
1175       echo "</ul>\n";
1176       
1177       /* whos turn is it? */
1178       if($seq==4)
1179         {
1180           $winner = get_winner($play,$gametype); /* returns the position */
1181           $next = $winner;
1182           $firstcard = ""; /* new trick, no first card */
1183         }
1184       else
1185         {
1186           $next = $pos+1;
1187           if($next==5) $next=1;
1188         }
1189       
1190       /* my turn?, display cards as links, ask for comments*/
1191       if(DB_get_pos_by_hash($me) == $next)
1192         $myturn = 1;
1193       else
1194         $myturn = 0;
1195       
1196       /* do we want to play a card? */
1197       if(myisset("card") && $myturn)
1198         {
1199           $card   = $_REQUEST["card"];
1200           $handid = DB_get_handid_by_hash($me); 
1201           
1202           /* check if we have card and that we haven't played it yet*/
1203           /* set played in hand_card to true where hand_id and card_id*/
1204           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
1205                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1206           $r = mysql_fetch_array($result,MYSQL_NUM);
1207           $handcardid = $r[0];
1208           
1209           if($handcardid) /* everything ok, play card  */
1210             {
1211               $comment = "";
1212
1213               /* mark card as played */
1214               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
1215                           DB_quote_smart($card));
1216
1217               /* update Game timestamp */
1218               DB_update_game_timestamp($gameid);
1219
1220               /* check if a call was made */
1221               if(myisset("call120") && $_REQUEST["call120"] == "yes")
1222                 $result = mysql_query("UPDATE Hand SET point_call='120' WHERE hash='$me' ");
1223               if(myisset("call90")  && $_REQUEST["call90"]  == "yes")
1224                 $result = mysql_query("UPDATE Hand SET point_call='90'  WHERE hash='$me' ");
1225               if(myisset("call60")  && $_REQUEST["call60"]  == "yes")
1226                 $result = mysql_query("UPDATE Hand SET point_call='60'  WHERE hash='$me' ");
1227               if(myisset("call30")  && $_REQUEST["call30"]  == "yes")
1228                 $result = mysql_query("UPDATE Hand SET point_call='30'  WHERE hash='$me' ");
1229               if(myisset("call0")   && $_REQUEST["call0"]   == "yes")
1230                 $result = mysql_query("UPDATE Hand SET point_call='0'   WHERE hash='$me' ");
1231                 
1232
1233               /* check for schweinchen */
1234               //echo "schweinchen = ".$GAME["schweinchen"]." --$card-<br />";
1235               if($card == 19 || $card == 20 )
1236                 {
1237                   $GAME["schweinchen"]++;
1238                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
1239                     $comment="Schweinchen! ";
1240                   if($RULES["schweinchen"]=="both" )
1241                     $comment="Schweinchen! ";
1242                   if ($debug) echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
1243                 }
1244
1245               /* get trick id or start new trick */
1246               $a = DB_get_current_trickid($gameid);
1247               $trickid  = $a[0];
1248               $sequence = $a[1];
1249               $tricknr  = $a[2];
1250               
1251               $playid = DB_play_card($trickid,$handcardid,$sequence);
1252               
1253               /* if sequence == 4 check who one in case of wedding */
1254               if($sequence == 4 && $GT == "wedding") 
1255                 {
1256                   /* is wedding resolve */
1257                   $resolved = DB_get_sickness_by_gameid($gameid); 
1258                   if($resolved<0)
1259                     {
1260                       /* who has wedding */
1261                       $userids = DB_get_all_userid_by_gameid($gameid);
1262                       foreach($userids as $user)
1263                         {
1264                           $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1265                           if($usersick == "wedding")
1266                             $whosick = $user;
1267                         }
1268                       /* who won the trick */
1269                       $play     = DB_get_cards_by_trick($trickid);
1270                       $winner   = get_winner($play,$gametype); /* returns the position */
1271                       $winnerid = DB_get_userid_by_gameid_and_position($gameid,$winner);
1272                       /* is tricknr <=3 */
1273                       if($tricknr <=3 && $winnerid!=$whosick)
1274                         {
1275                           /* set resolved at tricknr*/
1276                           $resolved = DB_set_sickness_by_gameid($gameid,$tricknr); 
1277                           /* set partner */
1278                           $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1279                           DB_set_party_by_hash($whash,"re");
1280                         }
1281                       if($tricknr == 3 && $winnerid==$whosick)
1282                         {
1283                           /* set resolved at tricknr*/
1284                           $resolved = DB_set_sickness_by_gameid($gameid,'3'); 
1285                         }
1286                     }
1287                 }
1288               
1289               /* check for coment */
1290               if(myisset("comment"))
1291                 {
1292                   $comment.=$_REQUEST["comment"];
1293                 };  
1294               if($comment != "")
1295                 DB_insert_comment($comment,$playid,$myid);
1296
1297               /* display played card */
1298               echo "<div class=\"card\">";
1299               echo " you played  <br />";
1300               display_card($card,$PREF["cardset"]);
1301               echo "</div>\n";
1302               
1303               /*check if we still have cards left, else set status to gameover */
1304               if(sizeof(DB_get_hand($me))==0)
1305                 {
1306                   DB_set_hand_status_by_hash($me,'gameover');
1307                   $mystatus='gameover';
1308                 }
1309               
1310               /* if all players are done, set game status to game over, 
1311                * get the points of the last trick and send out an email 
1312                * to all players
1313                */
1314               $userids = DB_get_all_userid_by_gameid($gameid);
1315               
1316               $done=1;
1317               foreach($userids as $user)
1318                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1319                   $done=0;
1320               
1321               if($done)
1322                 {
1323                   DB_set_game_status_by_gameid($gameid,"gameover");
1324                   /* get score for last trick 
1325                    * all other tricks are handled a few lines further down*/
1326                   $play   = DB_get_cards_by_trick($trickid);
1327                   $winner = get_winner($play,$gametype); /* returns the position */
1328                   /* get points of last trick and save it */
1329                   $points = 0;
1330                   foreach($play as $card)
1331                     $points = $points + card_value($card["card"]);
1332                   $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
1333                   if($winnerid>0)
1334                     mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
1335                   else
1336                     echo "ERROR during scoring";
1337                   
1338                   /* email all players */
1339                   /* individual score */
1340                   $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1341                                         " LEFT JOIN Hand ON Hand.id=hand_id".
1342                                         " LEFT JOIN User ON Hand.user_id=User.id".
1343                                         " WHERE Hand.game_id=$gameid".
1344                                         " GROUP BY fullname" );
1345                   $message = "The game is over. Thanks for playing :)\n";
1346                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1347                     $message .= " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."\n";
1348                   $message .= "\nIf your not in the list above your score is zero...\n\n";
1349
1350                   $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1351                                         " LEFT JOIN Hand ON Hand.id=hand_id".
1352                                         " LEFT JOIN User ON Hand.user_id=User.id".
1353                                         " WHERE Hand.game_id=$gameid".
1354                                         " GROUP BY Hand.party" );
1355                   $message .= "\n";
1356                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1357                     $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
1358                   
1359                   /* check who wants to be CC'ed on the email */
1360                   $h = array();
1361                   $header = "";
1362                   foreach($userids as $user)
1363                     {
1364                       $result = mysql_query("SELECT value from User_Prefs".
1365                                             " WHERE user_id='$user' AND pref_key='ccemail'" );
1366                       $r = mysql_fetch_array($result,MYSQL_NUM);
1367                       if($r && $r[0]=="yes")
1368                         $h[]   = DB_get_email_by_userid($user);
1369                     }
1370                   if(sizeof($h))
1371                     $header = "CC: ".join(",",$h)."\r\n";
1372                   
1373                   foreach($userids as $user)
1374                     {
1375                       $To   = DB_get_email_by_userid($user);
1376                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1377                       $mymessage = $message."Use this link to have a look at the game: ".$host."?me=".$hash."\n\n" ;
1378                       mymail($To,$EmailName."game over (game $gameid)",$mymessage,$header);
1379                     }
1380                 }
1381               
1382               
1383               /* email next player */
1384               if(DB_get_game_status_by_gameid($gameid)=='play')
1385                 {
1386                   if($sequence==4)
1387                     {
1388                       $play   = DB_get_cards_by_trick($trickid);
1389                       $winner = get_winner($play,$gametype); /* returns the position */
1390                       
1391                       /* get points of last trick and save it, last trick is handled 
1392                        * a few lines further up  */
1393                       $points = 0;
1394                       foreach($play as $card)
1395                         $points = $points + card_value($card["card"]);
1396                       
1397                       $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
1398                       if($winnerid>0)
1399                         mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
1400                       else
1401                         echo "ERROR during scoring";
1402                       
1403                       if($debug)
1404                         echo "DEBUG: $winner got $points <br />";
1405                       
1406                       /* who is the next player? */
1407                       $next = $winner;
1408                     }
1409                   else
1410                     {
1411                       $next = DB_get_pos_by_hash($me)+1;
1412                     }
1413                   if($next==5) $next=1;
1414                   
1415                   /* email next player */
1416                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1417                   $email     = DB_get_email_by_hash($next_hash);
1418                   
1419                   $message = "A card has been played in game $gameid.\n\n".
1420                     "It's your turn  now.\n".
1421                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
1422                   mymail($email,$EmailName."a card has been played",$message);            
1423                 }
1424             }
1425           else
1426             {
1427               echo "can't find that card?! <br />\n";
1428             }
1429         }
1430       else if(myisset("card") && !$myturn )
1431         {
1432           echo "please wait until it's your turn! <br />\n";
1433         }
1434       
1435       $mycards = DB_get_hand($me);
1436       $mycards = mysort($mycards,$gametype);
1437       echo "<div class=\"mycards\">\n";
1438       
1439       if($myturn && !myisset("card"))
1440         {
1441           echo "Hello ".$myname.", it's your turn!  <br />\n";
1442           echo "Your cards are: <br />\n";
1443           echo "<form  action=\"index.php?me=$me\" method=\"post\">\n";
1444           
1445           /* do we have to follow suite? */
1446           $followsuit = 0;
1447           if(have_suit($mycards,$firstcard))
1448             $followsuit = 1;
1449           
1450           foreach($mycards as $card) 
1451             {
1452               if($followsuit && !same_type($card,$firstcard))
1453                 display_card($card,$PREF["cardset"]);
1454               else
1455                 display_link_card($card,$PREF["cardset"]);
1456             }
1457           
1458           if( can_call(120,$me) )
1459               echo " re/contra (120):".
1460                 " <input type=\"radio\" name=\"call120\" value=\"yes\" /> ";
1461           if( can_call(90,$me) )
1462               echo " 90:".
1463                 " <input type=\"radio\" name=\"call90\" value=\"yes\" /> ";
1464           if( can_call(60,$me) )
1465               echo " 60:".
1466                 " <input type=\"radio\" name=\"call60\" value=\"yes\" /> ";
1467           if( can_call(30,$me) )
1468               echo " 30:".
1469                 " <input type=\"radio\" name=\"call30\" value=\"yes\" /> ";
1470           if( can_call(0,$me) )
1471               echo " 0:".
1472                 " <input type=\"radio\" name=\"call0\" value=\"yes\" /> ".
1473                 " no call:".
1474                 " <input type=\"radio\" name=\"call0\" value=\"no\" /> ";
1475
1476           echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
1477           echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
1478           echo "<input type=\"submit\" value=\"move\" />\n";
1479           echo "</form>\n";
1480         }
1481       else if($mystatus=='play')
1482         {
1483           echo "Your cards are: <br />\n";
1484           foreach($mycards as $card) 
1485             display_card($card,$PREF["cardset"]);
1486         }
1487       else if($mystatus=='gameover')
1488         {
1489           $oldcards = DB_get_all_hand($me);
1490           $oldcards = mysort($oldcards,$gametype);
1491           echo "Your cards were: <br />\n";
1492           foreach($oldcards as $card) 
1493             display_card($card,$PREF["cardset"]);
1494         }
1495       echo "</div>\n";
1496       
1497       /* check if we need to set status to 'gameover' is done during playing of the card */
1498       if($mystatus=='play')
1499         break;
1500       /* the following happens only when the gamestatus is 'gameover' */
1501       /* check if game is over, display results */
1502       if(DB_get_game_status_by_gameid($gameid)=='play')
1503         {
1504           echo "the game is over for you.. other people still need to play though";
1505         }
1506       else
1507         {
1508           echo "the game is over now...<br />\n";
1509           
1510           $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1511                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1512                                 " LEFT JOIN User ON Hand.user_id=User.id".
1513                                 " WHERE Hand.game_id=$gameid".
1514                                 " GROUP BY fullname" );
1515           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1516             echo " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."<br />";
1517           
1518           $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1519                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1520                                 " LEFT JOIN User ON Hand.user_id=User.id".
1521                                 " WHERE Hand.game_id=$gameid".
1522                                 " GROUP BY Hand.party" );
1523           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1524             echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />\n";
1525
1526           
1527           $session = DB_get_session_by_gameid($gameid);
1528           $result  = mysql_query("SELECT id,create_date FROM Game".
1529                                  " WHERE session=$session".
1530                                  " ORDER BY create_date DESC".
1531                                  " LIMIT 1");
1532           $r=-1;
1533           if($result)
1534             $r = mysql_fetch_array($result,MYSQL_NUM);
1535           
1536           if(!$session || $gameid==$r[0])
1537             {
1538               /* suggest a new game with the same people in it, just rotated once */
1539               $names = DB_get_all_names_by_gameid($gameid);
1540               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1541             }
1542         }
1543       break;
1544     default:
1545       echo "error in testing the status";
1546     }
1547     output_footer();
1548     DB_close();
1549     exit();
1550  } 
1551 /* user status page */ 
1552  else if(myisset("email","password"))
1553    {
1554      /* test id and password, should really be done in one step */
1555      $email     = $_REQUEST["email"];
1556      $password  = $_REQUEST["password"];
1557      
1558
1559      if(myisset("forgot"))
1560        {
1561          $ok=1;
1562
1563          $uid = DB_get_userid_by_email($email);
1564          if(!$uid)
1565            $ok=0;
1566          
1567          if($ok)
1568            {
1569              echo "Hmm, you forgot your passwort...nothing I can do at the moment:(  ";
1570              echo " you need to email Arun for now... in the future it will be all automated and an ";
1571              echo "email with a new password will go to $email.";
1572            }
1573          else
1574            {
1575              if($email=="")
1576                echo "you need to give me an email address!";
1577              else
1578                echo "couldn't find a player with this email, please contact Arun, if you think this is a mistake";
1579            } 
1580        }
1581      else 
1582      {
1583        /* verify password and email */
1584        if(strlen($password)!=32)
1585          $password = md5($password);
1586        
1587        $ok=1;
1588        $uid = DB_get_userid_by_email_and_password($email,$password);
1589        if(!$uid)
1590          $ok=0;
1591        
1592        if($ok)
1593          {
1594            DB_get_PREF($uid);
1595
1596            if(myisset("setpref"))
1597              {
1598                $setpref=$_REQUEST["setpref"];
1599                switch($setpref)
1600                  {
1601                  case "germancards":
1602                  case "englishcards":
1603                    $result = mysql_query("SELECT * from User_Prefs".
1604                                          " WHERE user_id='$uid' AND pref_key='cardset'" );
1605                    if( mysql_fetch_array($result,MYSQL_NUM))
1606                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
1607                                            " WHERE user_id='$uid' AND pref_key='cardset'" );
1608                    else
1609                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$uid','cardset',".DB_quote_smart($setpref).")");
1610                    echo "Ok, changed you preferences for the cards.\n";
1611                    break;
1612                  case "ccemail":
1613                    $result = mysql_query("SELECT * from User_Prefs".
1614                                          " WHERE user_id='$uid' AND pref_key='ccemail'" );
1615                    if( mysql_fetch_array($result,MYSQL_NUM))
1616                      if($PREF["ccemail"]=="yes")
1617                        $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart("no").
1618                                              " WHERE user_id='$uid' AND pref_key='ccemail'" );
1619                      else
1620                        $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart("yes").
1621                                              " WHERE user_id='$uid' AND pref_key='ccemail'" );
1622                    else
1623                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$uid','ccemail',".DB_quote_smart("yes").")");
1624                    echo "Ok, changed you preferences for being CC'ed on emails.\n";
1625                    break;
1626
1627                  }
1628              }
1629            else /* output default user page */
1630              {
1631                $time = DB_get_user_timestamp($uid);
1632                $unixtime =strtotime($time);
1633                
1634                $offset = DB_get_user_timezone($uid);
1635                $zone = return_timezone($offset);
1636                date_default_timezone_set($zone);
1637                
1638                /* display links to settings */
1639                output_user_settings($email,$password);
1640                
1641                echo "last login: ".date("r",$unixtime)."<br />";
1642                
1643                DB_update_user_timestamp($uid);
1644                
1645                echo "<p>these are your games that haven't started yet:<br />\n";
1646                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
1647                                      " LEFT JOIN Game On Hand.game_id=Game.id".
1648                                      " WHERE Hand.user_id='$uid' AND Game.status='pre'" );
1649                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1650                  {
1651                    echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1652                    if(time()-strtotime($r[2]) > 60*60*24*30)
1653                      echo " The game has been running for over a month.".
1654                        " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1655                        " (clicking here is final and can't be restored)";
1656                    echo "<br />";
1657                  }
1658                echo "</p>\n";
1659
1660                echo "<p>these are the games you are playing in:<br />\n";
1661                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
1662                                      " LEFT JOIN Game On Hand.game_id=Game.id".
1663                                      " WHERE Hand.user_id='$uid' AND Game.status='play'" );
1664                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1665                  {
1666                    echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1667                    if(time()-strtotime($r[2]) > 60*60*24*30)
1668                      echo " The game has been running for over a month.".
1669                        " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1670                        " (clicking here is final and can't be restored)";
1671                    echo "<br />";
1672                  }
1673                echo "</p>\n";
1674                
1675                
1676                echo "<p>and these are your games that are already done:<br />Game: \n";
1677                $output=array();
1678                $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
1679                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1680                  $output[]= "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>";
1681                echo implode(", ",$output)."</p>\n";
1682                
1683                $names = DB_get_all_names();
1684                echo "<p>registered players:<br />\n";
1685                echo implode(", ",$names)."\n";
1686                echo "</p>\n";
1687                
1688                echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
1689              }
1690          }
1691        else
1692          {
1693            echo "sorry email and password don't match <br />";
1694          }
1695      };
1696      output_footer();
1697      DB_close();
1698      exit();
1699    }
1700 /* page for registration */
1701  else if(myisset("register") )
1702    {
1703      output_register();
1704    }
1705 /* new user wants to register */
1706  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
1707    {
1708      $ok=1;
1709      if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
1710        {
1711          echo "please chose another name<br />";
1712          $ok=0;
1713        }
1714      if(DB_get_userid_by_email($_REQUEST["Remail"]))
1715        {
1716          echo "this email address is already used ?!<br />";
1717          $ok=0;
1718        }
1719      if($ok)
1720        {
1721          $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
1722                         ",".DB_quote_smart($_REQUEST["Remail"]).
1723                         ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
1724                         ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
1725          
1726          if($r)
1727            echo " added you to the database";
1728          else
1729            echo " something went wrong";
1730        }
1731    }
1732 /* default login page */
1733  else
1734    { 
1735      $pre[0]=0;$game[0]=0;$done[0]=0;
1736      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
1737      if($r) {
1738        $pre  = mysql_fetch_array($r,MYSQL_NUM);     
1739        $game = mysql_fetch_array($r,MYSQL_NUM);     
1740        $done = mysql_fetch_array($r,MYSQL_NUM);     
1741      }
1742
1743      $r=mysql_query("SELECT AVG(datediff(mod_date,create_date)) FROM Game where status='gameover' ");
1744      if($r)
1745        $avgage= mysql_fetch_array($r,MYSQL_NUM);     
1746      else
1747        $avgage[0]=0;
1748
1749      output_home_page($pre[0],$game[0],$done[0],$avgage[0]);
1750    }
1751
1752 output_footer();
1753
1754 DB_close();
1755
1756 /*
1757  *Local Variables: 
1758  *mode: php
1759  *mode: hs-minor
1760  *End:
1761  */
1762 ?>
1763
1764