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