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