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