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