83c8cb7c2a553480ab8c4f05bb4982b9a6ff081d
[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,'false','false',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,'false','false',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,'false','false',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,'false','false',NULL)");
130     $hand_idD = mysql_insert_id();
131     
132     /* save cards */
133     for($i=0;$i<12;$i++)
134       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idA', '".$randomNR[$i]."', 'false')");
135     for($i=12;$i<24;$i++)
136       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idB', '".$randomNR[$i]."', 'false')");
137     for($i=24;$i<36;$i++)
138       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idC', '".$randomNR[$i]."', 'false')");
139     for($i=36;$i<48;$i++)
140       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idD', '".$randomNR[$i]."', 'false')");
141     
142     /* send out email, TODO: check for error with email */
143     $message = "\n".
144       "you are invited to play a game of DoKo (that is to debug the program ;).\n".
145       "Place comments and bug reports here:\n".
146       "http://wiki.nubati.net/index.php?title=EmailDoko\n\n".
147       "The whole round would consist of the following players:\n".
148       "$PlayerA\n".
149       "$PlayerB\n".
150       "$PlayerC\n".
151       "$PlayerD\n\n".
152       "If you want to join this game, please follow this link:\n\n".
153       " ".$host."?me=";
154     
155     mymail($EmailA,"You are invited to a game of DoKo","Hello $PlayerA,\n".$message.$hashA);
156     mymail($EmailB,"You are invited to a game of DoKo","Hello $PlayerB,\n".$message.$hashB);
157     mymail($EmailC,"You are invited to a game of DoKo","Hello $PlayerC,\n".$message.$hashC);
158     mymail($EmailD,"You are invited to a game of DoKo","Hello $PlayerD,\n".$message.$hashD);
159     
160     echo "You started a new game. The emails have been sent out!";    
161   }    /* end set up a new game */
162 /* cancle a game, if nothing has happend in the last N minutes */
163 else if(myisset("cancle","me"))
164   {
165     $me = $_REQUEST["me"];
166     
167     /* test for valid ID */
168     $myid = DB_get_userid_by_hash($me);
169     if(!$myid)
170       {
171         echo "Can't find you in the database, please check the url.<br />\n";
172         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
173         output_footer();
174         exit();
175       }
176     
177     DB_update_user_timestamp($myid);
178     
179     /* get some information from the DB */
180     $gameid   = DB_get_gameid_by_hash($me);
181     $myname   = DB_get_name_by_hash($me);
182     
183     /* check if game really is old enough */
184     $result = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
185     $r = mysql_fetch_array($result,MYSQL_NUM);
186     if(time()-strtotime($r[0]) > 60*60*24*30) /* = 1 month */
187       {
188         $message = "Hello, \n\n".
189           "Game $gameid has been cancled since nothing happend for a while and $myname requested it.\n";
190         
191         $userids = DB_get_all_userid_by_gameid($gameid);
192         foreach($userids as $user)
193           {
194             $To = DB_get_email_by_userid($user);
195             mymail($To,$EmailName."game cancled (timed out)",$message);
196           }
197         
198         /* delete everything from the dB */
199         DB_cancel_game($me);
200         
201         echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
202       }
203     else
204       echo "<p>You need to wait longer before you can cancle a game...</p>\n";
205   }
206 /* handle request from one specific player for one game,
207  * (the hash is set on a per game base) */
208 else if(myisset("me"))
209   {
210     $me = $_REQUEST["me"];
211     
212     /* test for valid ID */
213     $myid = DB_get_userid_by_hash($me);
214     if(!$myid)
215       {
216         echo "Can't find you in the database, please check the url.<br />\n";
217         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
218         output_footer();
219         exit();
220       }
221
222     /* the user had done something, update the timestamp */
223     DB_update_user_timestamp($myid);
224     
225     /* get some information from the DB */
226     $gameid   = DB_get_gameid_by_hash($me);
227     $myname   = DB_get_name_by_hash($me);
228     $mystatus = DB_get_status_by_hash($me);
229     $mypos    = DB_get_pos_by_hash($me);
230     $myhand   = DB_get_handid_by_hash($me);
231
232     /* get prefs and save them */
233     $result = mysql_query("SELECT value from User_Prefs".
234                           " WHERE user_id='$myid' AND pref_key='cardset'" );
235     $r = mysql_fetch_array($result,MYSQL_NUM);
236     if($r)
237       {
238         if($r[0]=="germancards" && (time()-strtotime( "2009-12-31 23:59:59")<0) ) /* licence only valid until then */
239           $PREF["cardset"]="altenburg";
240       else
241         $PREF["cardset"]="english";
242       }
243     else
244       $PREF["cardset"]="english";
245       
246       
247     /* get rule set for this game */
248     $result = mysql_query("SELECT * FROM Rulesets".
249                           " LEFT JOIN Game ON Game.ruleset=Rulesets.id ".
250                           " WHERE Game.id='$gameid'" );
251     $r      = mysql_fetch_array($result,MYSQL_NUM);
252
253     $RULES["dullen"]      = $r[2];
254     $RULES["schweinchen"] = $r[3];
255     
256     /* get some infos about the game */
257     $gametype   = DB_get_gametype_by_gameid($gameid);
258     $gamestatus = DB_get_game_status_by_gameid($gameid);
259     $GT         = $gametype;
260     if($gametype=="solo")
261       {
262         $gametype = DB_get_solo_by_gameid($gameid);
263         $GT  = $gametype." ".$GT;
264       }
265
266     /* display rule set for this game */
267     echo "<div class=\"ruleset\">\n";
268
269     if($gamestatus != 'pre')
270       echo " Gametype: $GT <br />\n";
271     
272     echo "Rules: <br />\n";
273     echo "10ofhearts : ".$r[2]."<br />\n";
274     echo "schweinchen: ".$r[3]."<br />\n";
275     echo "</div>\n";
276     
277     /* does anyone have both foxes */
278     $GAME["schweinchen"]=0; 
279     for($i=1;$i<5;$i++)
280       {
281         $hash  = DB_get_hash_from_game_and_pos($gameid,$i);
282         $cards = DB_get_all_hand($hash);
283         if( in_array("19",$cards) && in_array("20",$cards) )
284           {
285             $GAME["schweinchen"]=1;
286             $GAME["schweinchen-who"]=$hash;
287           }
288       };
289
290     /* mystatus gets the player through the different stages of a game.
291      * start:    yes/no
292      * init:     check values from start,
293      *           check for sickness
294      * check:    check for return values from init
295      * poverty:  handle poverty, wait here until all player have reached this state
296      *           display sickness and move on to game
297      * play:     game in progress
298      * gameover: are we revisiting a game
299      */
300     switch($mystatus)
301       {
302       case 'start':
303         check_want_to_play($me);
304         /* move on to the next stage*/
305         DB_set_hand_status_by_hash($me,'init');
306         break;
307       case 'init':
308         /* first check if everything went ok  in the last step
309          * if not, send user back, if yes, check what he did
310          */
311         if( !myisset("in") )
312           {
313             echo "<p> you need to answer the <a href=\"$host?me=$me\">question</a>.</p>";
314             DB_set_hand_status_by_hash($me,'start');
315           }
316         else
317           {
318             if($_REQUEST["in"] == "no")
319               {
320                 /* cancle the game */
321                 $message = "Hello, \n\n".
322                   "the game has been canceled due to the request of one of the players.\n";
323                 
324                 $userids = DB_get_all_userid_by_gameid($gameid);
325                 foreach($userids as $user)
326                   {
327                     $To = DB_get_email_by_userid($user);
328                     mymail($To,$EmailName."game canceled",$message);
329                   }
330                 
331                 /* delete everything from the dB */
332                 DB_cancel_game($me);
333               }
334             else
335               {
336                 echo "thanks for joining the game...";
337                 
338                 $mycards = DB_get_hand($me);
339                 sort($mycards);
340                 echo "<p class=\"mycards\" style=\"margin-top:8em;\">your cards are: <br />\n";
341                 foreach($mycards as $card) 
342                   display_card($card,$PREF["cardset"]);
343                 echo "</p>\n";   
344                 
345                 check_for_sickness($me,$mycards);
346                 
347                 /* move on to the next stage*/
348                 DB_set_hand_status_by_hash($me,'check');
349               }
350           }
351         break;
352
353     case 'check':
354       /* ok, user is in the game, saw his cards and selected his vorbehalt
355        * so first we check what he selected
356        */
357       echo "Processing what you selected in the last step...<br />";
358
359       if(!myisset("solo","wedding","poverty","nines") )
360         {
361           /* all these variables have a pre-selected default,
362            * so we should never get here,
363            * unless a user tries to cheat ;) */
364           echo "something went wrong...please contact the admin.";
365         }
366       else
367         {
368           /* check if this sickness needs to be handled first */
369           $gametype    = DB_get_gametype_by_gameid($gameid);
370           $startplayer = DB_get_startplayer_by_gameid($gameid);
371           
372           if( $_REQUEST["solo"]!="No")
373             {
374               /* user wants to play a solo */
375
376               /* store the info in the user's hand info */
377               DB_set_solo_by_hash($me,$_REQUEST["solo"]);
378               DB_set_sickness_by_hash($me,"solo");
379
380               echo "<br />Seems like you want to play a ".$_REQUEST["solo"]." solo. Got it.<br />\n";
381               
382               if($gametype == "solo" && $startplayer<$mypos)
383                 {}/* do nothing, since someone else already is playing solo */
384               else
385                 {
386                   /* this solo comes first 
387                    * store info in game table
388                    */
389                   DB_set_gametype_by_gameid($gameid,"solo");
390                   DB_set_startplayer_by_gameid($gameid,$mypos);
391                   DB_set_solo_by_gameid($gameid,$_REQUEST["solo"]);
392                 };
393             }
394           else if($_REQUEST["wedding"] == "yes")
395             {
396               /* TODO: add silent solo somewhere*/
397               echo "Ok, you don't want to play a silent solo...wedding was chosen.<br />\n";
398               DB_set_sickness_by_hash($me,"wedding");
399             }
400           else if($_REQUEST["poverty"] == "yes")
401             {
402               echo "Don't think you can win with just a few trump...? ok, poverty chosen <br />\n";
403               DB_set_sickness_by_hash($me,"poverty");
404             }
405           else if($_REQUEST["nines"] == "yes")
406             {
407               echo "What? You just don't want to play a game because you have a few nines? Well, if no one".
408                 " is playing solo, this game will be canceled.<br />\n";
409               DB_set_sickness_by_hash($me,"nines");
410             }
411         }
412
413       echo " Ok, done with checking, please go to the <a href=\"$host?me=$me\">next step of the setup</a>.<br />";
414
415       /* move on to the next stage*/
416       DB_set_hand_status_by_hash($me,'poverty');
417       break;
418
419     case 'poverty':
420       /* here we need to check if there is a solo or some other form of sickness.
421        * If so, which one is the most important one
422        * set that one in the Game table
423        * tell people about it.
424        */
425       echo "<br /> Checking if someone else selected solo, nines or wedding or poverty.<br />";
426       
427       /* check if everyone has reached this stage */
428       $userids = DB_get_all_userid_by_gameid($gameid);
429       $ok=1;
430       foreach($userids as $user)
431         {
432           $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
433           if($userstat!='poverty' && $userstat!='play')
434             $ok=0;
435         };
436
437       if(!$ok)
438         {
439           echo "This step can only be handled after everyone finished the last step. ".
440             "Seems like this is not the case, so you need to wait a bit... please check back later....<br />";
441         }
442       else
443         {
444           echo "Everyone has finished checking their cards, let's see what they said...<br />";
445
446           /* check what kind of game we are playing,  in case there are any solos this already 
447            *will have the correct information in it */
448           $gametype    = DB_get_gametype_by_gameid($gameid);
449           $startplayer = DB_get_startplayer_by_gameid($gameid);
450
451           /* check for different sickness and just output a general info */
452
453           
454           $nines = 0;
455           $poverty = 0;
456           $wedding = 0;
457           $solo = 0;
458           foreach($userids as $user)
459             {
460               $name = DB_get_name_by_userid($user);
461               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
462               if($usersick == 'nines')
463                 {
464                   $nines = $user;
465                   echo "$name has a Vorbehalt. <br />";
466                   break;
467                 }
468               else if($usersick == 'poverty')
469                 {
470                   $poverty++;
471                   echo "$name has a Vorbehalt. <br />";
472                 }
473               else if($usersick == 'wedding')
474                 {
475                   $wedding=$user;
476                   echo "$name has a Vorbehalt. <br />"  ;
477                 }
478               else if($usersick == 'solo')
479                 {
480                   $solo++;
481                   echo "$name has a Vorbehalt. <br />"  ;
482                 }
483             }
484
485           /* now check which sickness comes first and set the gametype to it */
486
487           /* gamestatus == normal, => cancel game */
488           if($gametype == "solo")
489             {
490               /* do nothing */
491             }
492           else if($nines)
493             {
494               /* cancle game */
495               /* TODO: should we keep statistics of this? */
496               $message = "Hello, \n\n".
497                 "the game has been canceled because ".DB_get_name_by_userid($nines).
498                 " has five or more nines and nobody is playing solo.\n";
499               
500               /* TODO: add info about redeal in case this is a game of a series */
501               
502               $userids = DB_get_all_userid_by_gameid($gameid);
503               foreach($userids as $user)
504                 {
505                   $To = DB_get_email_by_userid($user);
506                   mymail($To,$EmailName."game canceled",$message);
507                 }
508               
509               /* delete everything from the dB */
510               DB_cancel_game($me);
511               
512               echo "The game has been canceled because ".DB_get_name_by_userid($nines).
513                 " has five or more nines and nobody is playing solo.\n";
514               output_footer();
515               exit();
516             }
517           else if($poverty==1)
518             {
519               DB_set_gametype_by_gameid($gameid,"poverty");
520               $gametype = "poverty";
521               $who=DB_get_sickness_by_gameid($gameid);
522               if(!$who)
523                 {
524                   $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
525                   if($firstsick == "poverty")
526                     DB_set_sickness_by_gameid($gameid,2); /* who needs to be asked first */
527                   else
528                     DB_set_sickness_by_gameid($gameid,1); /* who needs to be asked first */
529                 }
530             }
531           else if($poverty==2)
532             {
533               DB_set_gametype_by_gameid($gameid,"dpoverty");
534               $gametype = "dpoverty";
535               $who=DB_get_sickness_by_gameid($gameid);
536               if(!$who)
537                 {
538                   $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
539                   if($firstsick == "poverty")
540                     {
541                       $seconsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
542                       if($secondsick == "poverty")
543                         DB_set_sickness_by_gameid($gameid,30); /* who needs to be asked first */
544                       else
545                         DB_set_sickness_by_gameid($gameid,20); /* who needs to be asked first */
546                     }
547                   else
548                     DB_set_sickness_by_gameid($gameid,10); /* who needs to be asked first */
549                 }
550             }
551           else if($wedding> 0)
552             {
553               DB_set_gametype_by_gameid($gameid,"wedding");
554               $gametype = "wedding";
555             };
556
557           echo "<br />\n";
558
559           /* now the gametype is set correctly (shouldn't matter that this is calculated for every user)
560            * output what kind of game we have */
561           
562           $poverty = 0;
563           foreach($userids as $user)
564             {
565               /* userids are sorted by position... 
566                * so output whatever the firstone has, then whatever the next one has
567                * stop when the sickness is the same as the gametype 
568                */
569               
570               $name     = DB_get_name_by_userid($user);
571               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
572
573               if($usersick)
574                 echo "$name has $usersick. <br />"; /*TODO: perhaps save this in a string and store in Game? */
575
576               if($usersick=="poverty")
577                 $poverty++;
578               if($usersick == "wedding" && $gametype =="wedding")
579                 break;
580               if($usersick == "poverty" && $gametype =="poverty")
581                 break;
582               if($usersick == "poverty" && $gametype =="dpoverty" && $poverty==2)
583                 break;
584               if($usersick == "solo" && $gametype =="solo")
585                 break;
586             };
587
588           /* output Schweinchen in case the rules need it */
589           if( $gametype != "solo")
590             if($GAME["schweinchen"] && $RULES["schweinchen"]=="both" )
591               echo DB_get_name_by_hash($GAME["schweinchen-who"])." has Schweinchen. <br />";
592           
593           echo "<br />\n";
594           
595           /* finished the setup, set re/contra parties if possible, go to next stage unless there is a case of poverty*/
596           switch($gametype)
597             {
598             case "solo":
599               /* are we the solo player? set us to re, else set us to contra */
600               $pos = DB_get_pos_by_hash($me);
601               if($pos == $startplayer)
602                 DB_set_party_by_hash($me,"re");
603               else
604                 DB_set_party_by_hash($me,"contra");
605               DB_set_hand_status_by_hash($me,'play');
606               break;
607
608             case "wedding":
609               /* set person with the wedding to re, do the rest during the game */
610               $usersick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
611               if($usersick == "wedding")
612                 DB_set_party_by_hash($me,"re");
613               
614               echo "Don't know who will be Re and Contra, you need to ".
615                 "figure that out at the end of the game yourself <br />\n";
616               DB_set_hand_status_by_hash($me,'play');
617               break;
618
619             case "normal":
620               $hand = DB_get_all_hand($me);
621               
622               if(in_array('3',$hand)||in_array('4',$hand))
623                 DB_set_party_by_hash($me,"re");
624               else
625                 DB_set_party_by_hash($me,"contra");
626               DB_set_hand_status_by_hash($me,'play');
627               break;
628             case "poverty":
629             case "dpoverty":
630               /* check if poverty resolved (e.g. DB.Game who set to NULL)
631                *   yes? =>trump was taken, start game; break; 
632                */
633               $who=DB_get_sickness_by_gameid($gameid);
634               if($who<0)
635                 { /* trump has been taken */
636                   DB_set_hand_status_by_hash($me,'play');
637                   break;
638                 };
639               
640               if($who>9) /*= two people still have trump on the table*/
641                 $add=10;
642               else
643                 $add=1;
644
645               /* check if we are being asked now
646                *    no, display wait message, e.g. player X is asked at the moment 
647                */
648               $usersick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
649               if(myisset("trump") && $_REQUEST["trump"]=="no" && ($who==$mypos || $who==$mypos*10))
650                 {
651                   /* user doesn't want to take trump */
652                   /* set next player who needs to be asked */
653                   $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
654                   $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
655                   
656                   if($firstsick=="poverty")
657                     {
658                       if($secondsick=="poverty")
659                         DB_set_sickness_by_gameid($gameid,$who+$add*3);
660                       else
661                         DB_set_sickness_by_gameid($gameid,$who+$add*2);
662                     }
663                   else
664                     DB_set_sickness_by_gameid($gameid,$who+$add);
665
666                   /* this user is done */
667                   DB_set_hand_status_by_hash($me,'play');
668                   break;                
669                 }
670               else if(myisset("trump") && !myisset("exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
671                 {
672                   /* user wants to take trump */
673                   $trump = $_REQUEST["trump"];
674
675                   /* get hand id for user $trump */
676                   $userhand=DB_get_handid_by_gameid_and_userid($gameid,$trump);
677                   /* copy trump from player A to B */
678                   $result = mysql_query("UPDATE Hand_Card SET hand_id='$myhand' WHERE hand_id='$userhand' AND card_id<'27'" );
679                   
680                   /* set re/contra, if it is  not already set */
681                   $party = DB_get_party_by_hash($me);
682                   if(!$party)
683                     {
684                       foreach($userids as $user)
685                         {
686                           $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
687                           if($user == $trump || $user == $myid)
688                             DB_set_party_by_hash($hash,"re");
689                           else
690                             DB_set_party_by_hash($hash,"contra");
691                         }
692                     }
693                   /* add hidden button with trump in it to get to the next point */
694                   echo "<form action=\"index.php\" method=\"post\">\n";
695                   echo "  <input type=\"hidden\" name=\"exchange\" value=\"-1\" />\n";
696                   echo "  <input type=\"hidden\" name=\"trump\" value=\"".$trump."\" />\n";
697                   echo "  <input type=\"hidden\" name=\"me\" value=\"".$me."\" />\n";
698                   echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select cards to give back\" />\n";
699                   echo "</form>\n";
700                 }
701               else if(myisset("trump","exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
702                 {
703                   $trump    = $_REQUEST["trump"];
704                   $exchange = $_REQUEST["exchange"];
705                   $userhand = DB_get_handid_by_gameid_and_userid($gameid,$trump);
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
1058               /* update Game timestamp */
1059               DB_update_game_timestamp($gameid);
1060
1061               /* check for schweinchen */
1062               //echo "schweinchen = ".$GAME["schweinchen"]." --$card-<br />";
1063               if($card == 19 || $card == 20 )
1064                 {
1065                   $GAME["schweinchen"]++;
1066                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
1067                     $comment="Schweinchen! ";
1068                   if($RULES["schweinchen"]=="both" )
1069                     $comment="Schweinchen! ";
1070                   echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
1071                 }
1072
1073               /* get trick id or start new trick */
1074               $a = DB_get_current_trickid($gameid);
1075               $trickid  = $a[0];
1076               $sequence = $a[1];
1077               
1078               $playid = DB_play_card($trickid,$handcardid,$sequence);
1079               
1080               /* check for coment */
1081               if(myisset("comment"))
1082                 {
1083                   $comment.=$_REQUEST["comment"];
1084                 };  
1085               if($comment != "")
1086                 DB_insert_comment($comment,$playid,$myid);
1087
1088               /* display played card */
1089               echo "<div class=\"card\">";
1090               echo " you played  <br />";
1091               display_card($card,$PREF["cardset"]);
1092               echo "</div>\n";
1093               
1094               /*check if we still have cards left, else set status to gameover */
1095               if(sizeof(DB_get_hand($me))==0)
1096                 {
1097                   DB_set_hand_status_by_hash($me,'gameover');
1098                   $mystatus='gameover';
1099                 }
1100               
1101               /* if all players are done, set game status to game over, 
1102                * get the points of the last trick and send out an email 
1103                * to all players
1104                */
1105               $userids = DB_get_all_userid_by_gameid($gameid);
1106               
1107               $done=1;
1108               foreach($userids as $user)
1109                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1110                   $done=0;
1111               
1112               if($done)
1113                 {
1114                   DB_set_game_status_by_gameid($gameid,"gameover");
1115                   /* get score for last trick 
1116                    * all other tricks are handled a few lines further down*/
1117                   $play   = DB_get_cards_by_trick($trickid);
1118                   $winner = get_winner($play,$gametype); /* returns the position */
1119                   /* get points of last trick and save it */
1120                   $points = 0;
1121                   foreach($play as $card)
1122                     $points = $points + card_value($card["card"]);
1123                   $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
1124                   if($winnerid>0)
1125                     mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
1126                   else
1127                     echo "ERROR during scoring";
1128                   
1129                   /* email all players */
1130                   /* individual score */
1131                   $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1132                                         " LEFT JOIN Hand ON Hand.id=hand_id".
1133                                         " LEFT JOIN User ON Hand.user_id=User.id".
1134                                         " WHERE Hand.game_id=$gameid".
1135                                         " GROUP BY fullname" );
1136                   $message = "The game is over. Thanks for playing :)\n";
1137                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1138                     $message .= " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."\n";
1139                   $message .= "\nIf your not in the list above your score is zero...\n\n";
1140
1141                   $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1142                                         " LEFT JOIN Hand ON Hand.id=hand_id".
1143                                         " LEFT JOIN User ON Hand.user_id=User.id".
1144                                         " WHERE Hand.game_id=$gameid".
1145                                         " GROUP BY Hand.party" );
1146                   $message .= "\n";
1147                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1148                     $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
1149
1150                   foreach($userids as $user)
1151                     {
1152                       $To = DB_get_email_by_userid($user);
1153                       mymail($To,$EmailName."game over",$message);
1154                     }
1155                 }
1156               
1157               
1158               /* email next player */
1159               if(DB_get_game_status_by_gameid($gameid)=='play')
1160                 {
1161                   if($sequence==4)
1162                     {
1163                       $play   = DB_get_cards_by_trick($trickid);
1164                       $winner = get_winner($play,$gametype); /* returns the position */
1165                       
1166                       /* get points of last trick and save it, last trick is handled 
1167                        * a few lines further up  */
1168                       $points = 0;
1169                       foreach($play as $card)
1170                         $points = $points + card_value($card["card"]);
1171                       
1172                       $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
1173                       if($winnerid>0)
1174                         mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
1175                       else
1176                         echo "ERROR during scoring";
1177                       
1178                       if($debug)
1179                         echo "DEBUG: $winner got $points <br />";
1180                       
1181                       /* who is the next player? */
1182                       $next = $winner;
1183                     }
1184                   else
1185                     {
1186                       $next = DB_get_pos_by_hash($me)+1;
1187                     }
1188                   if($next==5) $next=1;
1189                   
1190                   /* email next player */
1191                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1192                   $email     = DB_get_email_by_hash($next_hash);
1193                   
1194                   $message = "It's your turn  now.\n".
1195                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
1196                   mymail($email,$EmailName."a card has been played",$message);
1197                   
1198                   if($debug)
1199                     echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
1200                       "\"> next player </a> <br />\n";
1201                   
1202                 }
1203             }
1204           else
1205             {
1206               echo "can't find that card?! <br />\n";
1207             }
1208         }
1209       else if(myisset("card") && !$myturn )
1210         {
1211           echo "please wait until it's your turn! <br />\n";
1212         }
1213       
1214       $mycards = DB_get_hand($me);
1215       $mycards = mysort($mycards,$gametype);
1216       echo "<div class=\"mycards\">\n";
1217       
1218       if($myturn && !myisset("card"))
1219         {
1220           echo "Hello ".$myname.", it's your turn!  <br />\n";
1221           echo "Your cards are: <br />\n";
1222           echo "<form  action=\"index.php?me=$me\" method=\"post\">\n";
1223           
1224           /* do we have to follow suite? */
1225           $followsuit = 0;
1226           if(have_suit($mycards,$firstcard))
1227             $followsuit = 1;
1228           
1229           foreach($mycards as $card) 
1230             {
1231               if($followsuit && !same_type($card,$firstcard))
1232                 display_card($card,$PREF["cardset"]);
1233               else
1234                 display_link_card($card,$PREF["cardset"]);
1235             }
1236           
1237           echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
1238           echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
1239           echo "<input type=\"submit\" value=\"move\" />\n";
1240           echo "</form>\n";
1241         }
1242       else if($mystatus=='play')
1243         {
1244           echo "Your cards are: <br />\n";
1245           foreach($mycards as $card) 
1246             display_card($card,$PREF["cardset"]);
1247         }
1248       else if($mystatus=='gameover')
1249         {
1250           $oldcards = DB_get_all_hand($me);
1251           $oldcards = mysort($oldcards,$gametype);
1252           echo "Your cards were: <br />\n";
1253           foreach($oldcards as $card) 
1254             display_card($card,$PREF["cardset"]);
1255         }
1256       echo "</div>\n";
1257       
1258       /* check if we need to set status to 'gameover' is done during playing of the card */
1259       if($mystatus=='play')
1260         break;
1261       /* the following happens only when the gamestatus is 'gameover' */
1262       /* check if game is over, display results */
1263       if(DB_get_game_status_by_gameid($gameid)=='play')
1264         {
1265           echo "the game is over for you.. other people still need to play though";
1266         }
1267       else
1268         {
1269           echo "the game is over now...<br />\n";
1270           
1271           $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1272                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1273                                 " LEFT JOIN User ON Hand.user_id=User.id".
1274                                 " WHERE Hand.game_id=$gameid".
1275                                 " GROUP BY fullname" );
1276           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1277             echo " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."<br />";
1278           
1279           $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1280                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1281                                 " LEFT JOIN User ON Hand.user_id=User.id".
1282                                 " WHERE Hand.game_id=$gameid".
1283                                 " GROUP BY Hand.party" );
1284           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1285             echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />\n";
1286
1287           
1288           $session = DB_get_session_by_gameid($gameid);
1289           $result  = mysql_query("SELECT id,create_date FROM Game".
1290                                  " WHERE session=$session".
1291                                  " ORDER BY create_date DESC".
1292                                  " LIMIT 1");
1293           $r=-1;
1294           if($result)
1295             $r = mysql_fetch_array($result,MYSQL_NUM);
1296           
1297           if(!$session || $gameid==$r[0])
1298             {
1299               /* suggest a new game with the same people in it, just rotated once */
1300               $names = DB_get_all_names_by_gameid($gameid);
1301               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1302             }
1303         }
1304       break;
1305     default:
1306       echo "error in testing the status";
1307     }
1308     output_footer();
1309     exit();
1310  } 
1311 /* user status page */ 
1312  else if(myisset("email","password"))
1313    {
1314      /* test id and password, should really be done in one step */
1315      $email     = $_REQUEST["email"];
1316      $password  = $_REQUEST["password"];
1317
1318      if(myisset("forgot"))
1319        {
1320          $ok=1;
1321
1322          $uid = DB_get_userid_by_email($email);
1323          if(!$uid)
1324            $ok=0;
1325          
1326          if($ok)
1327            {
1328              echo "Hmm, you forgot your passwort...nothing I can do at the moment:(  ";
1329              echo " you need to email Arun for now... in the future it will be all automated and an ";
1330              echo "email with a new password will go to $email.";
1331            }
1332          else
1333            {
1334              if($email=="")
1335                echo "you need to give me an email address!";
1336              else
1337                echo "couldn't find a player with this email, please contact Arun, if you think this is a mistake";
1338            } 
1339        }
1340      else 
1341      {
1342        /* verify password and email */
1343        if(strlen($password)!=32)
1344          $password = md5($password);
1345        
1346        $ok=1;
1347        $uid = DB_get_userid_by_email_and_password($email,$password);
1348        if(!$uid)
1349          $ok=0;
1350        
1351        if($ok)
1352          {
1353            if(myisset("setpref"))
1354              {
1355                $setpref=$_REQUEST["setpref"];
1356                switch($setpref)
1357                  {
1358                  case "germancards":
1359                  case "englishcards":
1360                    $result = mysql_query("SELECT * from User_Prefs".
1361                                          " WHERE user_id='$uid' AND pref_key='cardset'" );
1362                    if( mysql_fetch_array($result,MYSQL_NUM))
1363                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
1364                                            " WHERE user_id='$uid' AND pref_key='cardset'" );
1365                    else
1366                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$uid','cardset',".DB_quote_smart($setpref).")");
1367                    echo "Ok, changed you preferences for the cards.\n";
1368                    break;
1369                  }
1370              }
1371            else /* output default user page */
1372              {
1373                $time = DB_get_user_timestamp($uid);
1374                $unixtime =strtotime($time);
1375                
1376                $offset = DB_get_user_timezone($uid);
1377                $zone = return_timezone($offset);
1378                date_default_timezone_set($zone);
1379                
1380                /* display links to settings */
1381                output_user_settings($email,$password);
1382                
1383                echo "last login: ".date("r",$unixtime)."<br />";
1384                
1385                DB_update_user_timestamp($uid);
1386                
1387                echo "<p>these are the games you are playing in:<br />\n";
1388                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
1389                                      " LEFT JOIN Game On Hand.game_id=Game.id".
1390                                      " WHERE Hand.user_id='$uid' AND Game.status<>'gameover'" );
1391                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1392                  {
1393                    echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1394                    if(time()-strtotime($r[2]) > 60*60*24*30)
1395                      echo " The game has been running for over a month.".
1396                        " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1397                        " (clicking here is final and can't be restored)";
1398                    echo "<br />";
1399                  }
1400                echo "</p>\n";
1401                
1402                
1403                echo "<p>and these are your games that are already done:<br />Game: \n";
1404                $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
1405                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1406                  echo "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>, ";
1407                echo "</p>\n";
1408                
1409                $names = DB_get_all_names();
1410                echo "<p>registered players:<br />\n";
1411                foreach ($names as $name)
1412                  echo "$name, \n";
1413                echo "</p>\n";
1414                
1415                echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
1416              }
1417          }
1418        else
1419          {
1420            echo "sorry email and password don't match <br />";
1421          }
1422      };
1423      output_footer();
1424      exit();
1425    }
1426 /* page for registration */
1427  else if(myisset("register") )
1428    {
1429      output_register();
1430    }
1431 /* new user wants to register */
1432  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
1433    {
1434      $ok=1;
1435      if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
1436        {
1437          echo "please chose another name<br />";
1438          $ok=0;
1439        }
1440      if(DB_get_userid_by_email($_REQUEST["Remail"]))
1441        {
1442          echo "this email address is already used ?!<br />";
1443          $ok=0;
1444        }
1445      if($ok)
1446        {
1447          $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
1448                         ",".DB_quote_smart($_REQUEST["Remail"]).
1449                         ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
1450                         ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
1451          
1452          if($r)
1453            echo " added you to the database";
1454          else
1455            echo " something went wrong";
1456        }
1457    }
1458 /* default login page */
1459  else
1460    { 
1461      $pre=0;$game=0;$done=0;
1462      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
1463      if($r) {
1464        $pre = mysql_fetch_array($r,MYSQL_NUM);     
1465        $game = mysql_fetch_array($r,MYSQL_NUM);     
1466        $done = mysql_fetch_array($r,MYSQL_NUM);     
1467      }
1468      output_home_page($pre[0],$game[0],$done[0]);
1469    }
1470
1471 output_footer();
1472
1473 DB_close();
1474
1475 /*
1476  *Local Variables: 
1477  *mode: php
1478  *mode: hs-minor
1479  *End:
1480  */
1481 ?>
1482
1483