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