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