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