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