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