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