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