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