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