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