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