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