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