fixed bug in shuffle function
[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 $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         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 $gameid 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 in game $gameid, 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 $gameid canceled",$message);
530                 }
531               
532               /* delete everything from the dB */
533               DB_cancel_game($me);
534               
535               echo "The game has been canceled because ".DB_get_name_by_userid($nines).
536                 " has five or more nines and nobody is playing solo.\n";
537               output_footer();
538               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                   /* email next player */
693                   $who = DB_get_sickness_by_gameid($gameid);
694                   if($who>9) $who = $who/10;
695                   
696                   if($who<=4)
697                     {
698                       $To       = DB_get_email_by_pos_and_gameid($who,$gameid);
699                       $userhash = DB_get_hash_from_game_and_pos($gameid,$who);
700                       
701                       $message = "Someone has poverty, it's your turn to decide, if you want to take the trump. Please visit:".
702                         " ".$host."?me=".$userhash."\n\n" ;
703                       mymail($To,$EmailName." poverty",$message);
704                     }
705
706                   /* this user is done */
707                   DB_set_hand_status_by_hash($me,'play');
708                   break;                
709                 }
710               else if(myisset("trump") && !myisset("exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
711                 {
712                   /* user wants to take trump */
713                   $trump = $_REQUEST["trump"];
714
715                   /* get hand id for user $trump */
716                   $userhand = DB_get_handid_by_gameid_and_userid($gameid,$trump);
717                   /* copy trump from player A to B */
718                   $result = mysql_query("UPDATE Hand_Card SET hand_id='$myhand' WHERE hand_id='$userhand' AND card_id<'27'" );
719                   
720                   /* add hidden button with trump in it to get to the next point */
721                   echo "<form action=\"index.php\" method=\"post\">\n";
722                   echo "  <input type=\"hidden\" name=\"exchange\" value=\"-1\" />\n";
723                   echo "  <input type=\"hidden\" name=\"trump\" value=\"".$trump."\" />\n";
724                   echo "  <input type=\"hidden\" name=\"me\" value=\"".$me."\" />\n";
725                   echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select cards to give back\" />\n";
726                   echo "</form>\n";
727                 }
728               else if(myisset("trump","exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
729                 {
730                   $trump    = $_REQUEST["trump"];
731                   $exchange = $_REQUEST["exchange"];
732                   $userhand = DB_get_handid_by_gameid_and_userid($gameid,$trump);
733
734                   /* if exchange is set to a value>0, exchange that card back to user $trump */
735                   if($exchange >0)
736                     {
737                       $result = mysql_query("UPDATE Hand_Card SET hand_id='$userhand'".
738                                             " WHERE hand_id='$myhand' AND card_id='$exchange'" );
739                     };
740                   
741                   /* if number of cards == 12, set status to play for both users */
742                   $result = mysql_query("SELECT COUNT(*) FROM Hand_Card  WHERE hand_id='$myhand'" );
743                   $r      = mysql_fetch_array($result,MYSQL_NUM);
744                   if(!$r)
745                     {
746                       die("error in poverty");
747                     };
748                   if($r[0]==12)
749                     {
750                       if($gametype=="poverty" || $who<9)
751                         {
752                           DB_set_sickness_by_gameid($gameid,-1); /* done with poverty */                          
753                         }
754                       else /* reduce poverty count by one, that is go to single digits $who */
755                         {
756                           $add = 1;
757                           $who = $who/10;
758
759                           /* whom to ask next */
760                           $firstsick  = DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
761                           $secondsick = DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
762
763                           if($firstsick!="poverty")
764                             DB_set_sickness_by_gameid($gameid,$who+$add);
765                           else
766                             {
767                               if($secondsick!="poverty")
768                                 DB_set_sickness_by_gameid($gameid,$who+$add*2);
769                               else
770                                 DB_set_sickness_by_gameid($gameid,$who+$add*3);
771                             };
772
773                           /* email next player */
774                           $who = DB_get_sickness_by_gameid($gameid);
775                           if($who<=4)
776                             {
777                               $To       = DB_get_email_by_pos_and_gameid($who,$gameid);
778                               $userhash = DB_get_hash_from_game_and_pos($gameid,$who);
779                               
780                               $message = "Someone has poverty, it's your turn to decide, if you want to take the trump. Please visit:".
781                                 " ".$host."?me=".$userhash."\n\n" ;
782                               mymail($To,$EmailName." poverty",$message);
783                             }
784
785                         }
786                       
787                       /* this user is done */
788                       DB_set_hand_status_by_hash($me,'play');
789                       /* and so is his partner */
790                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$trump);
791                       DB_set_hand_status_by_hash($hash,'play');
792
793                       /* set party to re, unless we had dpoverty, in that case check if we need to set re/contra*/
794                       $re_set=0;
795                       foreach($userids as $user)
796                         {
797                           $userhash =DB_get_hash_from_gameid_and_userid($gameid,$user);
798                           $party=DB_get_party_by_hash($userhash);
799                           if($party=="re")
800                             $re_set=1;
801                         }
802                       if($re_set)
803                         {
804                           DB_set_party_by_hash($me,"contra");
805                           DB_set_party_by_hash($hash,"contra");
806                         }
807                       else
808                         {
809                           foreach($userids as $user)
810                             {
811                               $userhash =DB_get_hash_from_gameid_and_userid($gameid,$user);
812                               if($userhash==$hash||$userhash==$me)
813                                 DB_set_party_by_hash($userhash,"re");
814                               else
815                                 DB_set_party_by_hash($userhash,"contra");
816                             }
817                         }
818
819
820                       break;
821                     }
822                   else
823                     {
824                       /* else show all trump, have lowest card pre-selected, have hidden setting for */
825                       echo "you need to get rid of a few cards<br />\n";
826                       
827                       set_gametype($gametype); /* this sets the $CARDS variable */
828                       $mycards = DB_get_hand($me);
829                       $mycards = mysort($mycards,$gametype);
830
831                       echo "<form class=\"exchange\" action=\"index.php\" method=\"post\">\n";
832                       $type="exchange";
833                       foreach($mycards as $card) 
834                         display_link_card($card,$PREF["cardset"],$type);
835                       echo "  <input type=\"hidden\" name=\"trump\" value=\"".$trump."\" />\n";
836                       echo "  <input type=\"hidden\" name=\"me\" value=\"".$me."\" />\n";
837                       echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select one card to give back\" />\n";
838                       echo "</form>\n";
839                     }
840                 }
841               else if($who == $mypos || $who == $mypos*10)
842                 {
843                   foreach($userids as $user)
844                     {
845                       $name = DB_get_name_by_userid($user);
846                       $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
847                       
848                       if($usersick=="poverty")
849                         {
850                           $hash =DB_get_hash_from_gameid_and_userid($gameid,$user);
851                           $cards=DB_get_hand($hash);
852                           $nrtrump=count_trump($cards);
853                           /* count trump */
854                           if($nrtrump<4)
855                             echo "Player $name has $nrtrump trump. Do you want to take them?".
856                               "<a href=\"index.php?me=$me&amp;trump=$user\">yes</a> <br />";
857                         }
858                     }
859                   echo "I don't want to take any trump: ".
860                     "<a href=\"index.php?me=$me&amp;trump=no\">yes</a> <br />";
861
862                   echo "Your cards are: <br />\n";
863                   $mycards = DB_get_hand($me);
864                   sort($mycards);
865                   echo "<p class=\"mycards\" style=\"margin-top:8em;\">your cards are: <br />\n";
866                   foreach($mycards as $card) 
867                     display_card($card,$PREF["cardset"]);
868                   echo "</p>\n";   
869                 }
870               else
871                 {
872                   $mysick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
873                   if($mysick=="poverty")
874                     echo "The others are asked if they want to take your trump, you have to wait (you'll get an email).";
875                   else
876                     echo "it's not your turn yet to decide if you want to take the trump or not.";
877                 }
878               /*
879                *    yes, display number of trump and user's hand, ask if he wants to take it 
880                *      no, set whom-to-ask to next player, email next player, cancle game if no next player
881                *      yes -> link to new page:display all cards, ask for N return cards
882                *          set re/contra 
883                *        
884                */
885             };
886         }
887       /* check if no one wanted to take trump, in that case the gamesickness would be set to 5 or 50 */
888       $who = DB_get_sickness_by_gameid($gameid);
889       if($who==5 || $who==50)
890         {
891           $message = "Hello, \n\n".
892             "Game $gameid has been cancled since nobody wanted to take the trump.\n";
893           
894           $userids = DB_get_all_userid_by_gameid($gameid);
895           foreach($userids as $user)
896             {
897               $To = DB_get_email_by_userid($user);
898               mymail($To,$EmailName."game $gameid cancled (poverty not resolved)",$message);
899             }
900           
901           /* delete everything from the dB */
902           DB_cancel_game($me);
903           
904           echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
905           output_footer();
906           exit();
907         }
908
909       /* check if all players are ready to play */
910       $ok=1;
911       foreach($userids as $user)
912         if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
913           $ok=0;
914
915       if($ok)
916         {
917           /* only set this after all poverty, etc. are handled*/
918           DB_set_game_status_by_gameid($gameid,'play');
919
920           /* email startplayer */
921           $startplayer = DB_get_startplayer_by_gameid($gameid);
922           $email       = DB_get_email_by_pos_and_gameid($startplayer,$gameid);
923           $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
924           
925           if($hash!=$me)
926             {
927               /* email startplayer) */
928               $message = "It's your turn now in game $gameid.\n".
929                 "Use this link to play a card: ".$host."?me=".$hash."\n\n" ;
930               mymail($email,$EmailName."ready, set, go... ",$message);
931             }
932           else
933             echo " Please, <a href=\"$host?me=$me\">start</a> the game.<br />";  
934         }
935       else
936         echo "\n <br />";        
937
938       break;
939     case 'play':
940     case 'gameover': 
941       /* both entries here,  so that the tricks are visible for both.
942        * in case of 'play' there is a break later that skips the last part
943        */
944       
945       /* figure out what kind of game we are playing, 
946        * set the global variables $CARDS["trump"],$CARDS["diamonds"],$CARDS["hearts"],
947        * $CARDS["clubs"],$CARDS["spades"],$CARDS["foxes"]
948        * accordingly
949        */
950       
951       $gametype = DB_get_gametype_by_gameid($gameid);
952       $GT = $gametype;
953       if($gametype=="solo")
954         {
955           $gametype = DB_get_solo_by_gameid($gameid);
956           $GT = $gametype." ".$GT;
957         }
958       else
959         $gametype="normal";
960       
961       set_gametype($gametype); /* this sets the $CARDS variable */
962       
963       /* get some infos about the game */
964       $gamestatus = DB_get_game_status_by_gameid($gameid);
965       
966       /* display useful things in divs */
967       
968       /* display links to the users status page */
969       $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
970       $r      = mysql_fetch_array($result,MYSQL_NUM);
971       
972       display_links($r[0],$r[1]);
973       
974       /* end display useful things*/
975       
976       /* has the game started? No, then just wait here...*/
977       if($gamestatus == 'pre')
978         {
979           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 />";
980           break; /* not sure this works... the idea is that you can 
981                   * only  play a card after everyone is ready to play */
982         }
983       
984       /* display the table and the names */
985       $result = mysql_query("SELECT  User.fullname as name,".
986                             "        Hand.position as position, ".
987                             "        User.id, ".
988                             "        Hand.party as party, ".
989                             "        Hand.sickness as sickness, ".
990                             "        Hand.point_call ".
991                             "FROM Hand ".
992                             "LEFT JOIN User ON User.id=Hand.user_id ".
993                             "WHERE Hand.game_id='".$gameid."' ".
994                             "ORDER BY position ASC");
995       
996       echo "<div class=\"table\">\n".
997         "  <img src=\"pics/table.png\" alt=\"table\" />\n";
998       while($r = mysql_fetch_array($result,MYSQL_NUM))
999         {
1000           $name  = $r[0];
1001           $pos   = $r[1];
1002           $user  = $r[2];
1003           $party = $r[3];
1004           $sickness= $r[4];
1005           $call  = $r[5];
1006           
1007           $offset = DB_get_user_timezone($user);
1008           $zone   = return_timezone($offset);
1009           date_default_timezone_set($zone);
1010
1011           echo " <span class=\"table".($pos-1)."\">\n";
1012           echo " $name ";
1013           /* add hints for poverty, wedding, solo, etc */
1014           if($GT=="poverty" && $party=="re")
1015             if($sickness=="poverty")
1016               echo "(poverty <)";
1017             else
1018               echo "(poverty >)";
1019
1020           if($GT=="dpoverty")
1021             if($party=="re")
1022               if($sickness=="poverty")
1023                 echo "(poverty A <)";
1024               else
1025                 echo "(poverty A >)";
1026             else
1027               if($sickness=="poverty")
1028                 echo "(poverty B <)";
1029               else
1030                 echo "(poverty B >)";
1031               
1032           if($GT=="wedding" && $party=="re")
1033               if($sickness=="wedding")
1034                 echo "(wedding  +)";
1035               else
1036                 echo "(wedding)";
1037           /* add point calls */
1038           if($call!=NULL)
1039             echo " $party $call ";
1040
1041           echo "<br />\n";
1042           echo " local time: ".date("Y-m-d H:i:s")."\n";
1043           echo " </span>\n";
1044
1045         }
1046       echo  "</div>\n";
1047
1048       /* get everything relevant to display the tricks */
1049       $result = mysql_query("SELECT Hand_Card.card_id as card,".
1050                             "       Hand.position as position,".
1051                             "       Play.sequence as sequence, ".
1052                             "       Trick.id, ".
1053                             "       Comment.comment ".
1054                             "FROM Trick ".
1055                             "LEFT JOIN Play ON Trick.id=Play.trick_id ".
1056                             "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
1057                             "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
1058                             "LEFT JOIN Comment ON Play.id=Comment.play_id ".
1059                             "WHERE Trick.game_id='".$gameid."' ".
1060                             "ORDER BY Trick.id,sequence ASC");
1061       $trickNR = 1;
1062       
1063       $lasttrick = DB_get_max_trickid($gameid);
1064       
1065       $play = array(); /* needed to calculate winner later  */
1066       $seq  = 1;          
1067       $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
1068       $firstcard = ""; /* first card in a trick */
1069       
1070       echo "\n<ul class=\"tricks\">\n";
1071       echo "  <li class=\"nohighlight\"> Game $gameid: </li>\n";
1072       
1073       while($r = mysql_fetch_array($result,MYSQL_NUM))
1074         {
1075           $pos     = $r[1];
1076           $seq     = $r[2];
1077           $trick   = $r[3];
1078           $comment = $r[4];
1079           
1080           /* check if first schweinchen has been played */
1081           if($r[0] == 19 || $r[0] == 20 )
1082             $GAME["schweinchen"]++;
1083           
1084           /* save card to be able to find the winner of the trick later */
1085           $play[$seq] = array("card"=>$r[0],"pos"=>$pos); 
1086           
1087           if($seq==1)
1088             {
1089               /* first card in a trick, output some html */
1090               if($trick!=$lasttrick)
1091                 {
1092                   /* start of an old trick? */
1093                   echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">Trick $trickNR</a>\n".
1094                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1095                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1096                 }
1097               else if($trick==$lasttrick)
1098                 {
1099                   /* start of a last trick? */
1100                   echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">Trick $trickNR</a>\n".
1101                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1102                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1103                 };
1104               
1105               /* remember first card, so that we are able to check, what cards can be played */
1106               $firstcard = $r[0];
1107             };
1108           
1109           /* display card */
1110           echo "      <div class=\"card".($pos-1)."\">\n";
1111           
1112           /* display comments */
1113           if($comment!="")
1114             echo "        <span class=\"comment\">".$comment."</span>\n";
1115           
1116           echo "        ";
1117           display_card($r[0],$PREF["cardset"]);
1118           
1119           echo "      </div>\n"; /* end div card */
1120           
1121           /* end of trick? */
1122           if($seq==4)
1123             {
1124               $trickNR++;
1125               echo "    </div>\n  </li>\n";  /* end div table, end li table */
1126             }
1127         }
1128       
1129       if($seq!=4 && $trickNR>1) 
1130         echo "    </div>\n  </li>\n";  /* end div table, end li table */
1131       
1132       echo "</ul>\n";
1133       
1134       /* whos turn is it? */
1135       if($seq==4)
1136         {
1137           $winner = get_winner($play,$gametype); /* returns the position */
1138           $next = $winner;
1139           $firstcard = ""; /* new trick, no first card */
1140         }
1141       else
1142         {
1143           $next = $pos+1;
1144           if($next==5) $next=1;
1145         }
1146       
1147       /* my turn?, display cards as links, ask for comments*/
1148       if(DB_get_pos_by_hash($me) == $next)
1149         $myturn = 1;
1150       else
1151         $myturn = 0;
1152       
1153       /* do we want to play a card? */
1154       if(myisset("card") && $myturn)
1155         {
1156           $card   = $_REQUEST["card"];
1157           $handid = DB_get_handid_by_hash($me); 
1158           
1159           /* check if we have card and that we haven't played it yet*/
1160           /* set played in hand_card to true where hand_id and card_id*/
1161           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
1162                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1163           $r = mysql_fetch_array($result,MYSQL_NUM);
1164           $handcardid = $r[0];
1165           
1166           if($handcardid) /* everything ok, play card  */
1167             {
1168               $comment = "";
1169
1170               /* mark card as played */
1171               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
1172                           DB_quote_smart($card));
1173
1174               /* update Game timestamp */
1175               DB_update_game_timestamp($gameid);
1176
1177               /* check if a call was made */
1178               if(myisset("call120") && $_REQUEST["call120"] == "yes")
1179                 $result = mysql_query("UPDATE Hand SET point_call='120' WHERE hash='$me' ");
1180               if(myisset("call90")  && $_REQUEST["call90"]  == "yes")
1181                 $result = mysql_query("UPDATE Hand SET point_call='90'  WHERE hash='$me' ");
1182               if(myisset("call60")  && $_REQUEST["call60"]  == "yes")
1183                 $result = mysql_query("UPDATE Hand SET point_call='60'  WHERE hash='$me' ");
1184               if(myisset("call30")  && $_REQUEST["call30"]  == "yes")
1185                 $result = mysql_query("UPDATE Hand SET point_call='30'  WHERE hash='$me' ");
1186               if(myisset("call0")   && $_REQUEST["call0"]   == "yes")
1187                 $result = mysql_query("UPDATE Hand SET point_call='0'   WHERE hash='$me' ");
1188                 
1189
1190               /* check for schweinchen */
1191               //echo "schweinchen = ".$GAME["schweinchen"]." --$card-<br />";
1192               if($card == 19 || $card == 20 )
1193                 {
1194                   $GAME["schweinchen"]++;
1195                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
1196                     $comment="Schweinchen! ";
1197                   if($RULES["schweinchen"]=="both" )
1198                     $comment="Schweinchen! ";
1199                   if ($debug) echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
1200                 }
1201
1202               /* get trick id or start new trick */
1203               $a = DB_get_current_trickid($gameid);
1204               $trickid  = $a[0];
1205               $sequence = $a[1];
1206               $tricknr  = $a[2];
1207               
1208               $playid = DB_play_card($trickid,$handcardid,$sequence);
1209               
1210               /* if sequence == 4 check who one in case of wedding */
1211               if($sequence == 4 && $GT == "wedding") 
1212                 {
1213                   /* is wedding resolve */
1214                   $resolved = DB_get_sickness_by_gameid($gameid); 
1215                   if($resolved<0)
1216                     {
1217                       /* who has wedding */
1218                       $userids = DB_get_all_userid_by_gameid($gameid);
1219                       foreach($userids as $user)
1220                         {
1221                           $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1222                           if($usersick == "wedding")
1223                             $whosick = $user;
1224                         }
1225                       /* who won the trick */
1226                       $play     = DB_get_cards_by_trick($trickid);
1227                       $winner   = get_winner($play,$gametype); /* returns the position */
1228                       $winnerid = DB_get_userid_by_gameid_and_position($gameid,$winner);
1229                       /* is tricknr <=3 */
1230                       if($tricknr <=3 && $winnerid!=$whosick)
1231                         {
1232                           /* set resolved at tricknr*/
1233                           $resolved = DB_set_sickness_by_gameid($gameid,$tricknr); 
1234                           /* set partner */
1235                           $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1236                           DB_set_party_by_hash($whash,"re");
1237                         }
1238                       if($tricknr == 3 && $winnerid==$whosick)
1239                         {
1240                           /* set resolved at tricknr*/
1241                           $resolved = DB_set_sickness_by_gameid($gameid,'3'); 
1242                         }
1243                     }
1244                 }
1245               
1246               /* check for coment */
1247               if(myisset("comment"))
1248                 {
1249                   $comment.=$_REQUEST["comment"];
1250                 };  
1251               if($comment != "")
1252                 DB_insert_comment($comment,$playid,$myid);
1253
1254               /* display played card */
1255               echo "<div class=\"card\">";
1256               echo " you played  <br />";
1257               display_card($card,$PREF["cardset"]);
1258               echo "</div>\n";
1259               
1260               /*check if we still have cards left, else set status to gameover */
1261               if(sizeof(DB_get_hand($me))==0)
1262                 {
1263                   DB_set_hand_status_by_hash($me,'gameover');
1264                   $mystatus='gameover';
1265                 }
1266               
1267               /* if all players are done, set game status to game over, 
1268                * get the points of the last trick and send out an email 
1269                * to all players
1270                */
1271               $userids = DB_get_all_userid_by_gameid($gameid);
1272               
1273               $done=1;
1274               foreach($userids as $user)
1275                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1276                   $done=0;
1277               
1278               if($done)
1279                 {
1280                   DB_set_game_status_by_gameid($gameid,"gameover");
1281                   /* get score for last trick 
1282                    * all other tricks are handled a few lines further down*/
1283                   $play   = DB_get_cards_by_trick($trickid);
1284                   $winner = get_winner($play,$gametype); /* returns the position */
1285                   /* get points of last trick and save it */
1286                   $points = 0;
1287                   foreach($play as $card)
1288                     $points = $points + card_value($card["card"]);
1289                   $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
1290                   if($winnerid>0)
1291                     mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
1292                   else
1293                     echo "ERROR during scoring";
1294                   
1295                   /* email all players */
1296                   /* individual score */
1297                   $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1298                                         " LEFT JOIN Hand ON Hand.id=hand_id".
1299                                         " LEFT JOIN User ON Hand.user_id=User.id".
1300                                         " WHERE Hand.game_id=$gameid".
1301                                         " GROUP BY fullname" );
1302                   $message = "The game is over. Thanks for playing :)\n";
1303                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1304                     $message .= " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."\n";
1305                   $message .= "\nIf your not in the list above your score is zero...\n\n";
1306
1307                   $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1308                                         " LEFT JOIN Hand ON Hand.id=hand_id".
1309                                         " LEFT JOIN User ON Hand.user_id=User.id".
1310                                         " WHERE Hand.game_id=$gameid".
1311                                         " GROUP BY Hand.party" );
1312                   $message .= "\n";
1313                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1314                     $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
1315
1316                   foreach($userids as $user)
1317                     {
1318                       $To = DB_get_email_by_userid($user);
1319                       mymail($To,$EmailName."game over (game $gameid)",$message);
1320                     }
1321                 }
1322               
1323               
1324               /* email next player */
1325               if(DB_get_game_status_by_gameid($gameid)=='play')
1326                 {
1327                   if($sequence==4)
1328                     {
1329                       $play   = DB_get_cards_by_trick($trickid);
1330                       $winner = get_winner($play,$gametype); /* returns the position */
1331                       
1332                       /* get points of last trick and save it, last trick is handled 
1333                        * a few lines further up  */
1334                       $points = 0;
1335                       foreach($play as $card)
1336                         $points = $points + card_value($card["card"]);
1337                       
1338                       $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
1339                       if($winnerid>0)
1340                         mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
1341                       else
1342                         echo "ERROR during scoring";
1343                       
1344                       if($debug)
1345                         echo "DEBUG: $winner got $points <br />";
1346                       
1347                       /* who is the next player? */
1348                       $next = $winner;
1349                     }
1350                   else
1351                     {
1352                       $next = DB_get_pos_by_hash($me)+1;
1353                     }
1354                   if($next==5) $next=1;
1355                   
1356                   /* email next player */
1357                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1358                   $email     = DB_get_email_by_hash($next_hash);
1359                   
1360                   $message = "A card has been played in game $gameid.\n\n".
1361                     "It's your turn  now.\n".
1362                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
1363                   mymail($email,$EmailName."a card has been played",$message);            
1364                 }
1365             }
1366           else
1367             {
1368               echo "can't find that card?! <br />\n";
1369             }
1370         }
1371       else if(myisset("card") && !$myturn )
1372         {
1373           echo "please wait until it's your turn! <br />\n";
1374         }
1375       
1376       $mycards = DB_get_hand($me);
1377       $mycards = mysort($mycards,$gametype);
1378       echo "<div class=\"mycards\">\n";
1379       
1380       if($myturn && !myisset("card"))
1381         {
1382           echo "Hello ".$myname.", it's your turn!  <br />\n";
1383           echo "Your cards are: <br />\n";
1384           echo "<form  action=\"index.php?me=$me\" method=\"post\">\n";
1385           
1386           /* do we have to follow suite? */
1387           $followsuit = 0;
1388           if(have_suit($mycards,$firstcard))
1389             $followsuit = 1;
1390           
1391           foreach($mycards as $card) 
1392             {
1393               if($followsuit && !same_type($card,$firstcard))
1394                 display_card($card,$PREF["cardset"]);
1395               else
1396                 display_link_card($card,$PREF["cardset"]);
1397             }
1398           
1399           if( can_call(120,$me) )
1400               echo " re/contra (120):".
1401                 " <input type=\"radio\" name=\"call120\" value=\"yes\" /> ";
1402           if( can_call(90,$me) )
1403               echo " 90:".
1404                 " <input type=\"radio\" name=\"call90\" value=\"yes\" /> ";
1405           if( can_call(60,$me) )
1406               echo " 60:".
1407                 " <input type=\"radio\" name=\"call60\" value=\"yes\" /> ";
1408           if( can_call(30,$me) )
1409               echo " 30:".
1410                 " <input type=\"radio\" name=\"call30\" value=\"yes\" /> ";
1411           if( can_call(0,$me) )
1412               echo " 0:".
1413                 " <input type=\"radio\" name=\"call0\" value=\"yes\" /> ";
1414
1415           echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
1416           echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
1417           echo "<input type=\"submit\" value=\"move\" />\n";
1418           echo "</form>\n";
1419         }
1420       else if($mystatus=='play')
1421         {
1422           echo "Your cards are: <br />\n";
1423           foreach($mycards as $card) 
1424             display_card($card,$PREF["cardset"]);
1425         }
1426       else if($mystatus=='gameover')
1427         {
1428           $oldcards = DB_get_all_hand($me);
1429           $oldcards = mysort($oldcards,$gametype);
1430           echo "Your cards were: <br />\n";
1431           foreach($oldcards as $card) 
1432             display_card($card,$PREF["cardset"]);
1433         }
1434       echo "</div>\n";
1435       
1436       /* check if we need to set status to 'gameover' is done during playing of the card */
1437       if($mystatus=='play')
1438         break;
1439       /* the following happens only when the gamestatus is 'gameover' */
1440       /* check if game is over, display results */
1441       if(DB_get_game_status_by_gameid($gameid)=='play')
1442         {
1443           echo "the game is over for you.. other people still need to play though";
1444         }
1445       else
1446         {
1447           echo "the game is over now...<br />\n";
1448           
1449           $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1450                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1451                                 " LEFT JOIN User ON Hand.user_id=User.id".
1452                                 " WHERE Hand.game_id=$gameid".
1453                                 " GROUP BY fullname" );
1454           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1455             echo " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."<br />";
1456           
1457           $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1458                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1459                                 " LEFT JOIN User ON Hand.user_id=User.id".
1460                                 " WHERE Hand.game_id=$gameid".
1461                                 " GROUP BY Hand.party" );
1462           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1463             echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />\n";
1464
1465           
1466           $session = DB_get_session_by_gameid($gameid);
1467           $result  = mysql_query("SELECT id,create_date FROM Game".
1468                                  " WHERE session=$session".
1469                                  " ORDER BY create_date DESC".
1470                                  " LIMIT 1");
1471           $r=-1;
1472           if($result)
1473             $r = mysql_fetch_array($result,MYSQL_NUM);
1474           
1475           if(!$session || $gameid==$r[0])
1476             {
1477               /* suggest a new game with the same people in it, just rotated once */
1478               $names = DB_get_all_names_by_gameid($gameid);
1479               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1480             }
1481         }
1482       break;
1483     default:
1484       echo "error in testing the status";
1485     }
1486     output_footer();
1487     exit();
1488  } 
1489 /* user status page */ 
1490  else if(myisset("email","password"))
1491    {
1492      /* test id and password, should really be done in one step */
1493      $email     = $_REQUEST["email"];
1494      $password  = $_REQUEST["password"];
1495
1496      if(myisset("forgot"))
1497        {
1498          $ok=1;
1499
1500          $uid = DB_get_userid_by_email($email);
1501          if(!$uid)
1502            $ok=0;
1503          
1504          if($ok)
1505            {
1506              echo "Hmm, you forgot your passwort...nothing I can do at the moment:(  ";
1507              echo " you need to email Arun for now... in the future it will be all automated and an ";
1508              echo "email with a new password will go to $email.";
1509            }
1510          else
1511            {
1512              if($email=="")
1513                echo "you need to give me an email address!";
1514              else
1515                echo "couldn't find a player with this email, please contact Arun, if you think this is a mistake";
1516            } 
1517        }
1518      else 
1519      {
1520        /* verify password and email */
1521        if(strlen($password)!=32)
1522          $password = md5($password);
1523        
1524        $ok=1;
1525        $uid = DB_get_userid_by_email_and_password($email,$password);
1526        if(!$uid)
1527          $ok=0;
1528        
1529        if($ok)
1530          {
1531            if(myisset("setpref"))
1532              {
1533                $setpref=$_REQUEST["setpref"];
1534                switch($setpref)
1535                  {
1536                  case "germancards":
1537                  case "englishcards":
1538                    $result = mysql_query("SELECT * from User_Prefs".
1539                                          " WHERE user_id='$uid' AND pref_key='cardset'" );
1540                    if( mysql_fetch_array($result,MYSQL_NUM))
1541                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
1542                                            " WHERE user_id='$uid' AND pref_key='cardset'" );
1543                    else
1544                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$uid','cardset',".DB_quote_smart($setpref).")");
1545                    echo "Ok, changed you preferences for the cards.\n";
1546                    break;
1547                  }
1548              }
1549            else /* output default user page */
1550              {
1551                $time = DB_get_user_timestamp($uid);
1552                $unixtime =strtotime($time);
1553                
1554                $offset = DB_get_user_timezone($uid);
1555                $zone = return_timezone($offset);
1556                date_default_timezone_set($zone);
1557                
1558                /* display links to settings */
1559                output_user_settings($email,$password);
1560                
1561                echo "last login: ".date("r",$unixtime)."<br />";
1562                
1563                DB_update_user_timestamp($uid);
1564                
1565                echo "<p>these are the games you are playing in:<br />\n";
1566                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
1567                                      " LEFT JOIN Game On Hand.game_id=Game.id".
1568                                      " WHERE Hand.user_id='$uid' AND Game.status<>'gameover'" );
1569                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1570                  {
1571                    echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1572                    if(time()-strtotime($r[2]) > 60*60*24*30)
1573                      echo " The game has been running for over a month.".
1574                        " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1575                        " (clicking here is final and can't be restored)";
1576                    echo "<br />";
1577                  }
1578                echo "</p>\n";
1579                
1580                
1581                echo "<p>and these are your games that are already done:<br />Game: \n";
1582                $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
1583                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1584                  echo "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>, ";
1585                echo "</p>\n";
1586                
1587                $names = DB_get_all_names();
1588                echo "<p>registered players:<br />\n";
1589                foreach ($names as $name)
1590                  echo "$name, \n";
1591                echo "</p>\n";
1592                
1593                echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
1594              }
1595          }
1596        else
1597          {
1598            echo "sorry email and password don't match <br />";
1599          }
1600      };
1601      output_footer();
1602      exit();
1603    }
1604 /* page for registration */
1605  else if(myisset("register") )
1606    {
1607      output_register();
1608    }
1609 /* new user wants to register */
1610  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
1611    {
1612      $ok=1;
1613      if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
1614        {
1615          echo "please chose another name<br />";
1616          $ok=0;
1617        }
1618      if(DB_get_userid_by_email($_REQUEST["Remail"]))
1619        {
1620          echo "this email address is already used ?!<br />";
1621          $ok=0;
1622        }
1623      if($ok)
1624        {
1625          $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
1626                         ",".DB_quote_smart($_REQUEST["Remail"]).
1627                         ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
1628                         ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
1629          
1630          if($r)
1631            echo " added you to the database";
1632          else
1633            echo " something went wrong";
1634        }
1635    }
1636 /* default login page */
1637  else
1638    { 
1639      $pre=0;$game=0;$done=0;
1640      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
1641      if($r) {
1642        $pre = mysql_fetch_array($r,MYSQL_NUM);     
1643        $game = mysql_fetch_array($r,MYSQL_NUM);     
1644        $done = mysql_fetch_array($r,MYSQL_NUM);     
1645      }
1646      output_home_page($pre[0],$game[0],$done[0]);
1647    }
1648
1649 output_footer();
1650
1651 DB_close();
1652
1653 /*
1654  *Local Variables: 
1655  *mode: php
1656  *mode: hs-minor
1657  *End:
1658  */
1659 ?>
1660
1661