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