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