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