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