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