0f94dcf6c6b2d2eac9f1d56d96eb49cc8cb5f505
[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 special output for schweinchen in case: 
1385                * schweinchen is in the rules, a fox has been played and the gametype is correct
1386                */
1387               if( $GAME["schweinchen"] && 
1388                   ($card == 19 || $card == 20) && 
1389                   ($gametype == "normal" || $gametype == "silent"|| $gametype=="trump"))
1390                 {
1391                   $GAME["schweinchen"]++; // count how many have been played including this one
1392                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
1393                     DB_insert_comment("Schweinchen! ",$playid,$myid);
1394                   if($RULES["schweinchen"]=="both" )
1395                     DB_insert_comment("Schweinchen! ",$playid,$myid);
1396                   if ($debug)
1397                     echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
1398                 }
1399
1400               /* if sequence == 4 check who one in case of wedding */
1401               if($sequence == 4 && $GT == "wedding")
1402                 {
1403                   /* is wedding resolve */
1404                   $resolved = DB_get_sickness_by_gameid($gameid);
1405                   if($resolved<0)
1406                     {
1407                       /* who has wedding */
1408                       $userids = DB_get_all_userid_by_gameid($gameid);
1409                       foreach($userids as $user)
1410                         {
1411                           $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1412                           if($usersick == "wedding")
1413                             $whosick = $user;
1414                         }
1415                       /* who won the trick */
1416                       $play     = DB_get_cards_by_trick($trickid);
1417                       $winner   = get_winner($play,$gametype); /* returns the position */
1418                       $winnerid = DB_get_userid_by_gameid_and_position($gameid,$winner);
1419                       /* is tricknr <=3 */
1420                       if($tricknr <=3 && $winnerid!=$whosick)
1421                         {
1422                           /* set resolved at tricknr*/
1423                           $resolved = DB_set_sickness_by_gameid($gameid,$tricknr);
1424                           /* set partner */
1425                           $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1426                           DB_set_party_by_hash($whash,"re");
1427                         }
1428                       if($tricknr == 3 && $winnerid==$whosick)
1429                         {
1430                           /* set resolved at tricknr*/
1431                           $resolved = DB_set_sickness_by_gameid($gameid,'3');
1432                         }
1433                     }
1434                 }
1435
1436               /* if sequence == 4, set winner of the trick, count points and set the next player */
1437               if($sequence==4)
1438                 {
1439                   $play   = DB_get_cards_by_trick($trickid);
1440                   $winner = get_winner($play,$gametype); /* returns the position */
1441
1442                   /* check if someone caught a fox */
1443                   /* first check if we should account for solos at all, 
1444                    * since it doesn't make sense in some games
1445                    */
1446                   $ok = 0; /* fox shouldn't be counted */
1447                   if(DB_get_gametype_by_gameid($gameid)=="solo")
1448                     {
1449                       $solo = DB_get_solo_by_gameid($gameid);
1450                       if($solo == "trump" || $solo == "silent")
1451                         $ok = 1; /* for trump solos and silent solos, foxes are ok */
1452                     }
1453                   else
1454                     $ok = 1; /* for all other games (not solos) foxes are ok too */
1455                   
1456                   if($ok==1)
1457                     foreach($play as $played)
1458                       {
1459                         if ( $played['card']==19 || $played['card']==20 )
1460                           if ($played['pos']!= $winner )
1461                             {
1462                               /* possible caught a fox, check party */
1463                               $uid1 = DB_get_userid_by_gameid_and_position($gameid,$winner);
1464                               $uid2 = DB_get_userid_by_gameid_and_position($gameid,$played['pos']);
1465
1466                               $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1467                               $party2 = DB_get_party_by_gameid_and_userid($gameid,$uid2);
1468
1469                               if($party1 != $party2)
1470                                 mysql_query("INSERT INTO Score".
1471                                             " VALUES( NULL,NULL,$gameid,'$party1',$uid1,$uid2,'fox')");
1472                             }
1473                       }
1474                   
1475                   /* check for karlchen (jack of clubs in the last trick)*/
1476                   /* same as for foxes, karlchen doesn't always make sense
1477                    * check what kind of game it is and set karlchen accordingly */
1478                   $ok = 1; /* default: karlchen should be accounted for */
1479                   if($tricknr != 12 )
1480                     $ok = 0; /* Karlchen works only in the last trick */
1481                   if($ok && DB_get_gametype_by_gameid($gameid)=="solo" )
1482                     {
1483                       $solo = DB_get_solo_by_gameid($gameid);
1484                       if($solo == "trumpless" || $solo == "jack" || $solo == "queen" )
1485                         $ok = 0; /* no Karlchen in these solos */
1486                     }
1487                   
1488                   if($ok)
1489                     foreach($play as $played)
1490                       if ( $played['card']==11 || $played['card']==12 )
1491                         if ($played['pos'] == $winner )
1492                           {
1493                             /* possible caught a fox, check party */
1494                             $uid1   = DB_get_userid_by_gameid_and_position($gameid,$winner);
1495                             $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1496
1497                             mysql_query("INSERT INTO Score".
1498                                         " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'karlchen')");
1499                           }
1500                   /* check for doppelopf (>40 points)*/
1501                   $points = 0;
1502                   foreach($play as $played)
1503                     {
1504                       $points += DB_get_card_value_by_cardid($played['card']);
1505                     }
1506                   if($points > 39)
1507                     {
1508                       $uid1   = DB_get_userid_by_gameid_and_position($gameid,$winner);
1509                       $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1510
1511                       mysql_query("INSERT INTO Score".
1512                                   " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'doko')");
1513                     }
1514
1515                   if($winner>0)
1516                     mysql_query("UPDATE Trick SET winner='$winner' WHERE id='$trickid'");
1517                   else
1518                     echo "ERROR during scoring";
1519
1520                   if($debug)
1521                     echo "DEBUG: position $winner won the trick <br />";
1522
1523                   /* who is the next player? */
1524                   $next = $winner;
1525                 }
1526               else
1527                 {
1528                   $next = DB_get_pos_by_hash($me)+1;
1529                 }
1530               if($next==5) $next=1;
1531
1532               /* check for coment */
1533               if(myisset("comment"))
1534                 {
1535                   $comment = $_REQUEST["comment"];
1536                   if($comment != "")
1537                     DB_insert_comment($comment,$playid,$myid);
1538                 };
1539
1540               /* check for note */
1541               if(myisset("note"))
1542                 {
1543                   $note = $_REQUEST["note"];
1544                   if($note != "")
1545                     DB_insert_note($note,$gameid,$myid);
1546                 };
1547
1548               /* display played card */
1549               $pos = DB_get_pos_by_hash($me);
1550               if($sequence==1)
1551                 {
1552                   echo "  <li onclick=\"hl('".($tricknr)."');\" class=\"current\"><a href=\"#\">Trick ".($tricknr)."</a>\n".
1553                     "    <div class=\"trick\" id=\"trick".($tricknr)."\">\n".
1554                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1555                 }
1556
1557               echo "      <div class=\"card".($pos-1)."\">\n        ";
1558
1559               /* display comments */
1560               display_card($card,$PREF["cardset"]);
1561               if($comment!="")
1562                 echo "\n        <span class=\"comment\"> ".$comment."</span>\n";
1563               echo "      </div>\n";
1564
1565               /*check if we still have cards left, else set status to gameover */
1566               if(sizeof(DB_get_hand($me))==0)
1567                 {
1568                   DB_set_hand_status_by_hash($me,'gameover');
1569                   $mystatus = 'gameover';
1570                 }
1571
1572               /* if all players are done, set game status to game over,
1573                * get the points of the last trick and send out an email
1574                * to all players
1575                */
1576               $userids = DB_get_all_userid_by_gameid($gameid);
1577
1578               $done=1;
1579               foreach($userids as $user)
1580                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1581                   $done=0;
1582
1583               if($done)
1584                 DB_set_game_status_by_gameid($gameid,"gameover");
1585
1586               /* email next player, if game is still running */
1587               if(DB_get_game_status_by_gameid($gameid)=='play')
1588                 {
1589                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1590                   $email     = DB_get_email_by_hash($next_hash);
1591                   $who       = DB_get_userid_by_email($email);
1592                   DB_set_player_by_gameid($gameid,$who);
1593
1594                   $message = "A card has been played in game ".DB_format_gameid($gameid).".\n\n".
1595                     "It's your turn  now.\n".
1596                     "Use this link to play a card: ".$HOST.$INDEX."?me=".$next_hash."\n\n" ;
1597                   if( DB_get_email_pref_by_uid($who)!="emailaddict" )
1598                     mymail($email,$EmailName."a card has been played in game ".DB_format_gameid($gameid),$message);
1599                 }
1600               else /* send out final email */
1601                 {
1602                   /* individual score */
1603                   $result = mysql_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1604                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1605                                 " LEFT JOIN User ON User.id=Hand.user_id".
1606                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1607                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1608                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1609                                 " WHERE Hand.game_id='$gameid'".
1610                                 " GROUP BY User.fullname" );
1611                   $message  = "The game is over. Thanks for playing :)\n";
1612                   $message .= "Final score:\n";
1613                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1614                     $message .= "   ".$r[0]."(".$r[2].") ".$r[1]."\n";
1615
1616                   $result = mysql_query("SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1617                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1618                                 " LEFT JOIN User ON User.id=Hand.user_id".
1619                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1620                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1621                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1622                                 " WHERE Hand.game_id='$gameid'".
1623                                 " GROUP BY Hand.party" );
1624                   $message .= "\nTotals:\n";
1625                   $re     = 0;
1626                   $contra = 0;
1627                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1628                     {
1629                       $message .= "    ".$r[0]." ".$r[1]."\n";
1630                       if($r[0] == "re")
1631                         $re = $r[1];
1632                       else if($r[0] == "contra")
1633                         $contra = $r[1];
1634                     }
1635
1636                   /*
1637                    * save score in database
1638                    *
1639                    */
1640
1641                   /* get calls from re/contra */
1642                   $call_re     = NULL;
1643                   $call_contra = NULL;
1644                   foreach($userids as $user)
1645                     {
1646                       $hash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1647                       $call  = DB_get_call_by_hash($hash);
1648                       $party = DB_get_party_by_hash($hash);
1649
1650                       if($call!=NULL)
1651                         {
1652                           $call = (int) $call;
1653
1654                           if($party=="re")
1655                             {
1656                               if($call_re==NULL)
1657                                 $call_re = $call;
1658                               else if( $call < $call_re)
1659                                 $call_re = $call;
1660                             }
1661                           else if($party=="contra")
1662                             {
1663                               if($call_contra==NULL)
1664                                 $call_contra = $call;
1665                               else if( $call < $call_re)
1666                                 $call_contra = $call;
1667                             }
1668                         }
1669                     }
1670
1671                   /* figure out who one */
1672                   $winning_party = NULL;
1673
1674                   if($call_re == NULL && $call_contra==NULL)
1675                     if($re>120)
1676                       $winning_party="re";
1677                     else
1678                       $winning_party="contra";
1679                   else
1680                     {
1681                       if($call_re)
1682                         {
1683                           $offset = 120 - $call_re;
1684                           if($call_re == 0)
1685                             $offset--; /* since we use a > in the next equation */
1686
1687                           if($re > 120+$offset)
1688                             $winning_party="re";
1689                           else if ( $call_contra == NULL )
1690                             $winning_party="contra";
1691                         }
1692
1693                       if($call_contra)
1694                         {
1695                           $offset = 120 - $call_contra;
1696                           if($call_contra == 0)
1697                             $offset--; /* since we use a > in the next equation */
1698
1699                           if($contra > 120+$offset)
1700                             $winning_party="contra";
1701                           else if ( $call_contra == NULL )
1702                             $winning_party="re";
1703                         }
1704                     }
1705
1706                   /* one point for each call of the other party in case the other party didn't win
1707                    * and one point each in case the party made more than points than one of the calls
1708                    */
1709                   if($winning_party!="contra" && $call_contra!=NULL)
1710                     {
1711                       for( $p=$call_contra;$p<=120; $p+=30 )
1712                         {
1713                           mysql_query("INSERT INTO Score".
1714                                       " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'against$p')");
1715                         }
1716
1717                       for( $p=$call_contra; $p<120; $p+=30)
1718                         {
1719                           if( $re >= $p )
1720                             mysql_query("INSERT INTO Score".
1721                                         " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'made$p')");
1722                         }
1723                     }
1724                   if($winning_party!="re" and $call_re!=NULL)
1725                     {
1726                       for( $p=$call_re;$p<=120; $p+=30 )
1727                         {
1728                           mysql_query("INSERT INTO Score".
1729                                       " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'against$p')");
1730                         }
1731
1732                       for( $p=$call_re; $p<120; $p+=30)
1733                         {
1734                           if( $contra>=$p )
1735                             mysql_query("INSERT INTO Score".
1736                                         " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'made$p')");
1737                         }
1738                     }
1739
1740                   /* point in case contra won */
1741                   if($winning_party=="contra")
1742                     {
1743                       mysql_query("INSERT INTO Score".
1744                                   " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'againstqueens')");
1745                     }
1746
1747                   /* one point each for winning and each 30 points + calls */
1748                   if($winning_party=="re")
1749                     {
1750                       foreach(array(120,150,180,210,240) as $p)
1751                         {
1752                           $offset = 0;
1753                           if($p==240 || $call_contra!=NULL)
1754                             $offset = 1;
1755
1756                           if($re>$p-$offset)
1757                             mysql_query("INSERT INTO Score".
1758                                         " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'".(240-$p)."')");
1759                         }
1760                       /* re called something and won */
1761                       foreach(array(0,30,60,90,120) as $p)
1762                         {
1763                           if($call_re!=NULL && $call_re<$p+1)
1764                             mysql_query("INSERT INTO Score".
1765                                         " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'call$p')");
1766                         }
1767                     }
1768                   else if( $winning_party=="contra")
1769                     {
1770                       foreach(array(120,150,180,210,240) as $p)
1771                         {
1772                           $offset = 0;
1773                           if($p==240 || $call_re!=NULL)
1774                             $offset = 1;
1775
1776                           if($contra>$p-$offset)
1777                             mysql_query("INSERT INTO Score".
1778                                         " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'".(240-$p)."')");
1779                         }
1780                       /* re called something and won */
1781                       foreach(array(0,30,60,90,120) as $p)
1782                         {
1783                           if($call_contra!=NULL && $call_contra<$p+1)
1784                             mysql_query("INSERT INTO Score".
1785                                         " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'call$p')");
1786                         }
1787                     }
1788
1789
1790                   /* add score points to email */
1791                   $message .= "\n";
1792                   $Tpoint = 0;
1793                   $message .= " Points Re: \n";
1794                   $queryresult = mysql_query("SELECT score FROM Score ".
1795                                              "  WHERE game_id=$gameid AND party='re'".
1796                                              " ");
1797                   while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
1798                     {
1799                       $message .= "   ".$r[0]."\n";
1800                       $Tpoint ++;
1801                     }
1802                   $message .= " Points Contra: \n";
1803                   $queryresult = mysql_query("SELECT score FROM Score ".
1804                                              "  WHERE game_id=$gameid AND party='contra'".
1805                                              " ");
1806                   while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
1807                     {
1808                       $message .= "   ".$r[0]."\n";
1809                       $Tpoint --;
1810                     }
1811                   $message .= " Total Points (from the Re point of view): $Tpoint\n";
1812                   $message .= "\n";
1813
1814                   $session = DB_get_session_by_gameid($gameid);
1815                   $score = generate_score_table($session);
1816                   /* convert html to ascii */
1817                   $score = str_replace("<div class=\"scoretable\">\n<table class=\"score\">\n <tr>\n","",$score);
1818                   $score = str_replace("</table></div>\n","",$score);
1819                   $score = str_replace("\n","",$score);
1820                   $score = str_replace(array("<tr>","</tr>","<td>","</td>"),array("","\n","","|"),$score);
1821                   $score = explode("\n",$score);
1822
1823                   $header = array_slice($score,0,1);
1824                   $header = explode("|",$header[0]);
1825                   for($i=0;$i<sizeof($header);$i++)
1826                     $header[$i]=str_pad($header[$i],6," ",STR_PAD_BOTH);
1827                   $header = implode("|",$header);
1828                   $header.= "\n------+------+------+------+------+\n";
1829                   if(sizeof($score)>5) $header.=   "                ...   \n";
1830
1831                   if(sizeof($score)>5) $score = array_slice($score,-5,5);
1832                   for($i=0;$i<sizeof($score);$i++)
1833                     {
1834                       $line = explode("|",$score[$i]);
1835                       for($j=0;$j<sizeof($line);$j++)
1836                         $line[$j]=str_pad($line[$j],6," ",STR_PAD_LEFT);
1837                       $score[$i] = implode("|",$line);
1838                     }
1839
1840                   $score = implode("\n",$score);
1841                   $score = $header.$score;
1842                   
1843                   $message .= "Score Table:\n";
1844                   $message .= $score;
1845
1846                   /* send out final email */
1847                   $all = array();
1848
1849                   foreach($userids as $user)
1850                     $all[] = DB_get_email_by_userid($user);
1851                   $To = implode(",",$all);
1852
1853                   $help = "\n\n (you can use reply all on this email to reach all the players.)\n";
1854                   mymail($To,$EmailName."game over (game ".DB_format_gameid($gameid).") part 1(2)",$message.$help);
1855
1856                   foreach($userids as $user)
1857                     {
1858                       $To   = DB_get_email_by_userid($user);
1859                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1860
1861                       $link = "Use this link to have a look at game ".DB_format_gameid($gameid).": ".
1862                         $HOST.$INDEX."?me=".$hash."\n\n" ;
1863                       if( DB_get_email_pref_by_uid($user) != "emailaddict" )
1864                         mymail($To,$EmailName."game over (game ".DB_format_gameid($gameid).") part 2(2)",$link);
1865                     }
1866                 }
1867             }
1868           else
1869             {
1870               echo "can't find that card?! <br />\n";
1871             }
1872         }
1873       else if(myisset("card") && !$myturn )
1874         {
1875           echo "please wait until it's your turn! <br />\n";
1876         }
1877
1878       if($seq!=4 && $trickNR>1)
1879         echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1880
1881       /* display points in case game is over */
1882       if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
1883         {
1884           echo "  <li onclick=\"hl('13');\" class=\"current\"><a href=\"#\">Score</a>\n".
1885             "    <div class=\"trick\" id=\"trick13\">\n";
1886           /* add pic for re/contra
1887            "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";*/
1888
1889           $result = mysql_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party,Hand.position FROM Hand".
1890                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1891                                 " LEFT JOIN User ON User.id=Hand.user_id".
1892                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1893                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1894                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1895                                 " WHERE Hand.game_id='$gameid'".
1896                                 " GROUP BY User.fullname" );
1897           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1898             echo "      <div class=\"card".($r[3]-1)."\">\n".
1899                  "        <div class=\"score\">".$r[2]."<br /> ".$r[1]."</div>\n".
1900                  "      </div>\n";
1901
1902           echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1903         }
1904
1905
1906       echo "</ul>\n"; /* end ul tricks*/
1907
1908       echo "<div class=\"notes\"> Personal notes: <br />\n";
1909       $notes = DB_get_notes_by_userid_and_gameid($myid,$gameid);
1910       foreach($notes as $note)
1911         echo "$note <hr \>\n";
1912       echo "Insert note:<input name=\"note\" type=\"text\" size=\"15\" maxlength=\"100\" />\n";
1913       echo "</div> \n";
1914       
1915       $mycards = DB_get_hand($me);
1916       $mycards = mysort($mycards,$gametype);
1917       echo "<div class=\"mycards\">\n";
1918
1919       if($myturn && !myisset("card") && $mystatus=='play' )
1920         {
1921           echo "Hello ".$myname.", it's your turn!  <br />\n";
1922           echo "Your cards are: <br />\n";
1923
1924           /* do we have to follow suite? */
1925           $followsuit = 0;
1926           if(have_suit($mycards,$firstcard))
1927             $followsuit = 1;
1928
1929           foreach($mycards as $card)
1930             {
1931               if($followsuit && !same_type($card,$firstcard))
1932                 display_card($card,$PREF["cardset"]);
1933               else
1934                 display_link_card($card,$PREF["cardset"]);
1935             }
1936         }
1937       else if($mystatus=='play' )
1938         {
1939           echo "Your cards are: <br />\n";
1940           foreach($mycards as $card)
1941             display_card($card,$PREF["cardset"]);
1942         }
1943       else if($mystatus=='gameover')
1944         {
1945           $oldcards = DB_get_all_hand($me);
1946           $oldcards = mysort($oldcards,$gametype);
1947           echo "Your cards were: <br />\n";
1948           foreach($oldcards as $card)
1949             display_card($card,$PREF["cardset"]);
1950
1951           $userids = DB_get_all_userid_by_gameid($gameid);
1952           foreach($userids as $user)
1953             {
1954               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1955
1956               if($userhash!=$me)
1957                 {
1958                   echo "<br />";
1959
1960                   $name = DB_get_name_by_userid($user);
1961                   $oldcards = DB_get_all_hand($userhash);
1962                   $oldcards = mysort($oldcards,$gametype);
1963                   echo "$name's cards were: <br />\n";
1964                   foreach($oldcards as $card)
1965                     display_card($card,$PREF["cardset"]);
1966                 }
1967             };
1968         }
1969       echo "</div>\n";
1970
1971       /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
1972       if($mystatus=='play')
1973         break;
1974
1975       /* the following happens only when the gamestatus is 'gameover' */
1976       /* check if game is over, display results */
1977       if(DB_get_game_status_by_gameid($gameid)=='play')
1978         {
1979           echo "The game is over for you.. other people still need to play though";
1980         }
1981       else
1982         {
1983           $result = mysql_query("SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1984                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1985                                 " LEFT JOIN User ON User.id=Hand.user_id".
1986                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1987                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1988                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1989                                 " WHERE Hand.game_id='$gameid'".
1990                                 " GROUP BY Hand.party" );
1991           echo "<div class=\"total\"> Totals:<br />\n";
1992           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1993             echo "  ".$r[0]." ".$r[1]."<br />\n";
1994
1995           $queryresult = mysql_query("SELECT timediff(mod_date,create_date) ".
1996                                      " FROM Game WHERE id='$gameid'");
1997           $r = mysql_fetch_array($queryresult,MYSQL_NUM);
1998           echo "<p>This game took ".$r[0]." hours.</p>";
1999
2000           echo "<div class=\"re\">\n Points Re: <br />\n";
2001           $queryresult = mysql_query("SELECT score FROM Score ".
2002                                      "  WHERE game_id=$gameid AND party='re'".
2003                                      " ");
2004           while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
2005             echo "   ".$r[0]."<br />\n";
2006           echo "</div>\n";
2007
2008           echo "<div class=\"contra\">\n Points Contra: <br />\n";
2009           $queryresult = mysql_query("SELECT score FROM Score ".
2010                                      "  WHERE game_id=$gameid AND party='contra'".
2011                                      " ");
2012           while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
2013             echo "   ".$r[0]."<br />\n";
2014           echo "</div>\n";
2015
2016           echo "</div>\n";
2017
2018
2019         }
2020       break;
2021     default:
2022       myerror("error in testing the status");
2023     }
2024     /* output left menu */
2025     display_user_menu();
2026
2027     /* output right menu */
2028
2029       /* display rule set for this game */
2030     echo "<div class=\"gameinfo\">\n";
2031
2032     if($gamestatus != 'pre')
2033       echo " Gametype: $GT <br />\n";
2034
2035     echo "Rules: <br />\n";
2036     echo "10ofhearts : ".$RULES["dullen"]      ."<br />\n";
2037     echo "schweinchen: ".$RULES["schweinchen"] ."<br />\n";
2038     echo "call:        ".$RULES["call"]        ."<br />\n";
2039
2040     echo "<hr />\n";
2041     if($gamestatus == 'play' )
2042       output_form_calls($me);
2043
2044     /* get time from the last action of the game */
2045     $result  = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
2046     $r       = mysql_fetch_array($result,MYSQL_NUM);
2047     $gameend = time() - strtotime($r[0]);
2048
2049     if($gamestatus == 'play' || $gameend < 60*60*24*7)
2050       {
2051         echo "<br />\nA short comment:<input name=\"comment\" type=\"text\" size=\"15\" maxlength=\"100\" />\n";
2052         echo "<hr />";
2053       }
2054
2055     echo "<input type=\"submit\" value=\"submit\" />\n";
2056
2057
2058     if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
2059       {
2060         echo "<hr />\n";
2061
2062         $session = DB_get_session_by_gameid($gameid);
2063         $result  = mysql_query("SELECT id,create_date FROM Game".
2064                                " WHERE session=$session".
2065                                " ORDER BY create_date DESC".
2066                                " LIMIT 1");
2067         $r = -1;
2068         if($result)
2069           $r = mysql_fetch_array($result,MYSQL_NUM);
2070
2071         if(!$session || $gameid==$r[0])
2072           {
2073             /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
2074             $names = DB_get_all_names_by_gameid($gameid);
2075             $type  = DB_get_gametype_by_gameid($gameid);
2076
2077             if($type=="solo")
2078               output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2079             else
2080               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2081           }
2082       }
2083
2084     $session = DB_get_session_by_gameid($gameid);
2085     $score = generate_score_table($session);
2086
2087     //  if(size_of($score)>30)
2088       echo $score;
2089
2090     echo "</div>\n";
2091
2092     echo "</form>\n";
2093     output_footer();
2094     DB_close();
2095     exit();
2096  }
2097 /* user status page */
2098 else if( myisset("email","password") || isset($_SESSION["name"]) )
2099    {
2100      /* test id and password, should really be done in one step */
2101      if(!isset($_SESSION["name"]))
2102        {
2103          $email     = $_REQUEST["email"];
2104          $password  = $_REQUEST["password"];
2105        }
2106      else
2107        {
2108          $name = $_SESSION["name"];
2109          $email     = DB_get_email_by_name($name);
2110          $password  = DB_get_passwd_by_name($name);
2111        };
2112
2113      /* user has forgotten his password */
2114      if(myisset("forgot"))
2115        {
2116          /* check if player is in the database */
2117          $ok = 1;
2118
2119          $myid = DB_get_userid_by_email($email);
2120          if(!$myid)
2121            $ok = 0;
2122
2123          if($ok)
2124            {
2125              /* check how many entries in recovery table */
2126              $number = DB_get_number_of_passwords_recovery($myid);
2127
2128              /* if less than N recent ones, add a new one and send out email */
2129              if( $number < 5 )
2130                {
2131                  echo "Ok, I send you a new password. <br />";
2132                  if($number >1)
2133                    echo "N.B. You tried this already $number times during the last day and it will only work ".
2134                      " 5 times during a day.<br />";
2135                  echo "The new password will be valid for one day, make sure you reset it to something else.<br />";
2136                  echo "Back to the  <a href=\"$INDEX\">main page</a>.";
2137
2138                  /* create temporary password, use the fist 8 letters of a md5 hash */
2139                  $TIME  = (string) time(); /* to avoid collisions */
2140                  $hash  = md5("Anewpassword".$email.$TIME);
2141                  $newpw = substr($hash,1,8);
2142
2143                  $message = "Someone (hopefully you) requested a new password. \n".
2144                    "You can use this email and the following password: \n".
2145                    "   $newpw    \n".
2146                    "to log into the server. The new password is valid for 24h, so make\n".
2147                    "sure you reset your password to something new. Your old password will\n".
2148                    " also still be valid until you set a new one\n";
2149                  mymail($email,$EmailName."recovery ",$message);
2150
2151                  /* we save these in the database */
2152                  DB_set_recovery_password($myid,md5($newpw));
2153                }
2154              else
2155                {
2156                  /* make it so that people (or a robot) can request thousands of passwords within a short time
2157                   * and spam a user this way */
2158                  echo "Sorry you already tried 5 times during the last 24h.<br />".
2159                    "You need to use one of those passwords or wait to get a new one.<br />";
2160                  echo "Back to the <a href=\"$INDEX\">main page</a>.";
2161                }
2162            }
2163          else
2164            {/* can't find user id in the database */
2165              
2166              /* no email given? */
2167              if($email=="")
2168                echo "You need to give me an email address! <br />".
2169                  "Please try <a href=\"$INDEX\">again</a>.";
2170              else /* default error message */
2171                echo "Couldn't find a player with this email! <br />".
2172                  "Please contact Arun, if you think this is a mistake <br />".
2173                  "or else try <a href=\"$INDEX\">again</a>.";
2174            }
2175        }
2176    else 
2177      { /* normal user page */
2178        /* verify password and email */
2179        if(strlen($password)!=32)
2180          $password = md5($password);
2181
2182        $ok  = 1;
2183        $myid = DB_get_userid_by_email_and_password($email,$password);
2184        if(!$myid)
2185          $ok = 0;
2186
2187        if($ok)
2188          {
2189            /* user information is ok */
2190            $myname = DB_get_name_by_email($email);
2191            $_SESSION["name"] = $myname;
2192            output_status();
2193
2194            DB_get_PREF($myid);
2195
2196            /* does the user want to change some preferences? */
2197            if(myisset("setpref"))
2198              {
2199                $setpref=$_REQUEST["setpref"];
2200                switch($setpref)
2201                  {
2202                  case "germancards":
2203                  case "englishcards":
2204                    $result = mysql_query("SELECT * from User_Prefs".
2205                                          " WHERE user_id='$myid' AND pref_key='cardset'" );
2206                    if( mysql_fetch_array($result,MYSQL_NUM))
2207                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
2208                                            " WHERE user_id='$myid' AND pref_key='cardset'" );
2209                    else
2210                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$myid','cardset',".
2211                                            DB_quote_smart($setpref).")");
2212                    echo "Ok, changed you preferences for the cards.\n";
2213                    break;
2214                  case "emailaddict":
2215                  case "emailnonaddict":
2216                    $result = mysql_query("SELECT * from User_Prefs".
2217                                          " WHERE user_id='$myid' AND pref_key='email'" );
2218                    if( mysql_fetch_array($result,MYSQL_NUM))
2219                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
2220                                            " WHERE user_id='$myid' AND pref_key='email'" );
2221                    else
2222                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$myid','email',".
2223                                            DB_quote_smart($setpref).")");
2224                    echo "Ok, changed you preferences for sending out emails.\n";
2225                    break;
2226                  }
2227              }
2228            /* user wants to change his password or request a temporary one */
2229            else if(myisset("passwd"))
2230              {
2231                if( $_REQUEST["passwd"]=="ask" )
2232                  {
2233                    /* reset password form*/
2234                    output_password_recovery($email,$password);
2235                  }
2236                else if($_REQUEST["passwd"]=="set")
2237                  {
2238                    /* reset password */
2239                    $ok = 1;
2240
2241                    /* check if old password matches */
2242                    $oldpasswd = md5($_REQUEST["password0"]);
2243                    if(!( ($password == $oldpasswd) || DB_check_recovery_passwords($oldpasswd,$email) ))
2244                      $ok = -1;
2245                    /* check if new passwords are types the same twice */
2246                    if($_REQUEST["password1"] != $_REQUEST["password2"] )
2247                      $ok = -2;
2248
2249                    switch($ok)
2250                      {
2251                      case '-2':
2252                        echo "The new passwords don't match. <br />";
2253                        break;
2254                      case '-1':
2255                        echo "The old password is not correct. <br />";
2256                        break;
2257                      case '1':
2258                        echo "Changed the password.<br />";
2259                        mysql_query("UPDATE User SET password='".md5($_REQUEST["password1"]).
2260                                    "' WHERE id=".DB_quote_smart($myid));
2261                        break;
2262                      }
2263                    /* set password */
2264                  }
2265              }
2266            else /* output default user page */
2267              {
2268                /* display links to settings */
2269                output_user_settings();
2270
2271                DB_update_user_timestamp($myid);
2272
2273                display_user_menu();
2274
2275                /* display all games the user has played */
2276                echo "<div class=\"user\">";
2277                echo "<h4>These are all your games:</h4>\n";
2278                echo "<p>Session: <br />\n";
2279                echo "<span class=\"gamestatuspre\"> p </span> =  pre-game phase ";
2280                echo "<span class=\"gamestatusplay\">P </span> =  game in progess ";
2281                echo "<span class=\"gamestatusover\">F </span> =  game finished <br />";
2282                echo "</p>\n";
2283
2284                $output = array();
2285                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date,Game.player,Game.status from Hand".
2286                                      " LEFT JOIN Game ON Game.id=Hand.game_id".
2287                                      " WHERE user_id='$myid'".
2288                                      " ORDER BY Game.session,Game.create_date" );
2289                $gamenrold = -1;
2290                echo "<table>\n <tr><td>\n";
2291                while( $r = mysql_fetch_array($result,MYSQL_NUM))
2292                  {
2293                    $game = DB_format_gameid($r[1]);
2294                    $gamenr = (int) $game;
2295                    if($gamenrold < $gamenr)
2296                      {
2297                        if($gamenrold!=-1)
2298                          echo "</td></tr>\n <tr> <td>$gamenr:</td><td> ";
2299                        else
2300                          echo "$gamenr:</td><td> ";
2301                        $gamenrold = $gamenr;
2302                      }
2303                    if($r[4]=='pre')
2304                      {
2305                        echo "\n   <span class=\"gamestatuspre\"><a href=\"".$INDEX."?me=".$r[0]."\">p </a></span> ";
2306
2307                      }
2308                    else if ($r[4]=='gameover')
2309                      echo "\n   <span class=\"gamestatusover\"><a href=\"".$INDEX."?me=".$r[0]."\">F </a></span> ";
2310                    else
2311                      {
2312                        echo "\n   <span class=\"gamestatusplay\"><a href=\"".$INDEX."?me=".$r[0]."\">P </a></span> ";
2313                      }
2314                    if($r[4] != 'gameover')
2315                      {
2316                        echo "</td><td>\n    ";
2317                        if($r[3]==$myid || !$r[3])
2318                          echo "(it's <strong>your</strong> turn)\n";
2319                        else
2320                          {
2321                            $name = DB_get_name_by_userid($r[3]);
2322                            $gameid = $r[1];
2323                            if(DB_get_reminder($r[3],$gameid)==0)
2324                              if(time()-strtotime($r[2]) > 60*60*24*7)
2325                                echo "".
2326                                  "<a href=\"$INDEX?remind=1&amp;me=".$r[0]."\">Send a reminder.</a>";
2327                            echo "(it's $name's turn)\n";
2328                          };
2329                        if(time()-strtotime($r[2]) > 60*60*24*30)
2330                          echo "".
2331                            "<a href=\"$INDEX?cancel=1&amp;me=".$r[0]."\">Cancel?</a>".
2332                            " (clicking here is final and can't be restored)";
2333
2334                      }
2335                  }
2336                echo "</td></tr>\n</table>\n";
2337
2338                /* display last 5 users that have signed up to e-DoKo */
2339                $names = DB_get_names_of_new_logins(5);
2340                echo "<h4>New Players:</h4>\n<p>\n";
2341                echo implode(", ",$names).",...\n";
2342                echo "</p>\n";
2343
2344                /* display last 5 users that logged on */
2345                $names = DB_get_names_of_last_logins(5);
2346                echo "<h4>Players last logged in:</h4>\n<p>\n";
2347                echo implode(", ",$names).",...\n";
2348                echo "</p>\n";
2349                
2350                echo "</div>\n";
2351              }
2352          }
2353        else
2354          {
2355            echo "<div class=\"message\">Sorry email and password don't match. Please <a href=\"$INDEX\">try again</a>. </div>";
2356          }
2357      };
2358      output_footer();
2359      DB_close();
2360      exit();
2361    }
2362 /* default login page */
2363  else
2364    {
2365      /* this outputs the default home page with some extra statistics on it */
2366
2367      $pre[0]=0;$game[0]=0;$done[0]=0;
2368      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
2369      if($r) {
2370        $pre  = mysql_fetch_array($r,MYSQL_NUM);
2371        $game = mysql_fetch_array($r,MYSQL_NUM);
2372        $done = mysql_fetch_array($r,MYSQL_NUM);
2373      }
2374
2375      $r=mysql_query("SELECT AVG(datediff(mod_date,create_date)) FROM Game where status='gameover' ");
2376      if($r)
2377        $avgage= mysql_fetch_array($r,MYSQL_NUM);
2378      else
2379        $avgage[0]=0;
2380
2381      output_home_page($pre[0],$game[0],$done[0],$avgage[0]);
2382    }
2383
2384 output_footer();
2385
2386 DB_close();
2387
2388 /*
2389  *Local Variables:
2390  *mode: php
2391  *mode: hs-minor
2392  *End:
2393  */
2394 ?>
2395
2396