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