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