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