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