lots of small fixes and cleanup
[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 DB_open();
29 output_header();
30
31 /* check if we want to start a new game */
32 if(myisset("new"))
33   {
34     $names = DB_get_all_names();
35     output_form_for_new_game($names);
36   }
37 /*check if everything is ready to set up a new game */
38  else if( myisset("PlayerA", "PlayerB","PlayerC","PlayerD","dullen","schweinchen" ))
39   {
40     $PlayerA = $_REQUEST["PlayerA"];
41     $PlayerB = $_REQUEST["PlayerB"];
42     $PlayerC = $_REQUEST["PlayerC"];
43     $PlayerD = $_REQUEST["PlayerD"];
44
45     $dullen      = $_REQUEST["dullen"];
46     $schweinchen = $_REQUEST["schweinchen"];
47     
48     $EmailA  = DB_get_email_by_name($PlayerA);
49     $EmailB  = DB_get_email_by_name($PlayerB);
50     $EmailC  = DB_get_email_by_name($PlayerC);
51     $EmailD  = DB_get_email_by_name($PlayerD);
52     
53     if($EmailA=="" || $EmailB=="" || $EmailC=="" || $EmailD=="")
54       {
55         echo "couldn't find one of the names, please start a new game";
56         output_footer();
57         exit();
58       }
59     
60     $useridA  = DB_get_userid_by_name($PlayerA);
61     $useridB  = DB_get_userid_by_name($PlayerB);
62     $useridC  = DB_get_userid_by_name($PlayerC);
63     $useridD  = DB_get_userid_by_name($PlayerD);
64     
65     /* create random numbers */
66     $randomNR       = create_array_of_random_numbers();
67     $randomNRstring = join(":",$randomNR);
68     
69     /* get ruleset information or create new one */
70     $ruleset = DB_get_ruleset($dullen,$schweinchen);
71     if($ruleset <0) 
72       {
73         echo "Error defining ruleset: $ruleset";
74         output_footer();
75         exit();
76       };
77     
78     /* create game */
79     $followup = NULL;
80     if(myisset("followup") )
81       {
82         $followup= $_REQUEST["followup"];
83         $session = DB_get_session_by_gameid($followup);
84         $ruleset = DB_get_ruleset_by_gameid($followup); /* just copy ruleset from old game, 
85                                                          this way no manipulation is possible */
86         if($session)
87           mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre',".
88                       "'$ruleset','$session' ,NULL)");
89         else
90           {
91             /* get max session */
92             $max = DB_get_max_session();
93             $max++;
94             mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre',".
95                         "'$ruleset','$max' ,NULL)");
96             mysql_query("UPDATE Game SET session='".$max."' WHERE id=".DB_quote_smart($followup));
97           }
98       }
99     else
100       mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre', ".
101                   "'$ruleset',NULL ,NULL)");
102     $game_id = mysql_insert_id();
103     
104     /* create hash */
105     $hashA = md5("AGameOfDoko".$game_id.$PlayerA.$EmailA);
106     $hashB = md5("AGameOfDoko".$game_id.$PlayerB.$EmailB);
107     $hashC = md5("AGameOfDoko".$game_id.$PlayerC.$EmailC);
108     $hashD = md5("AGameOfDoko".$game_id.$PlayerD.$EmailD);
109     
110     /* create hands */
111     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridA).
112                 ", ".DB_quote_smart($hashA).", 'start','1',NULL,NULL,NULL,'false','false',NULL)");
113     $hand_idA = mysql_insert_id();                                                             
114     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridB).
115                 ", ".DB_quote_smart($hashB).", 'start','2',NULL,NULL,NULL,'false','false',NULL)");
116     $hand_idB = mysql_insert_id();                                                             
117     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridC).
118                 ", ".DB_quote_smart($hashC).", 'start','3',NULL,NULL,NULL,'false','false',NULL)");
119     $hand_idC = mysql_insert_id();                                                             
120     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridD).
121                 ", ".DB_quote_smart($hashD).", 'start','4',NULL,NULL,NULL,'false','false',NULL)");
122     $hand_idD = mysql_insert_id();
123     
124     /* save cards */
125     for($i=0;$i<12;$i++)
126       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idA', '".$randomNR[$i]."', 'false')");
127     for($i=12;$i<24;$i++)
128       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idB', '".$randomNR[$i]."', 'false')");
129     for($i=24;$i<36;$i++)
130       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idC', '".$randomNR[$i]."', 'false')");
131     for($i=36;$i<48;$i++)
132       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idD', '".$randomNR[$i]."', 'false')");
133     
134     /* send out email, TODO: check for error with email */
135     $message = "\n".
136       "you are invited to play a game of DoKo (that is to debug the program ;).\n".
137       "Place comments and bug reports here:\n".
138       "http://wiki.nubati.net/index.php?title=EmailDoko\n\n".
139       "The whole round would consist of the following players:\n".
140       "$PlayerA\n".
141       "$PlayerB\n".
142       "$PlayerC\n".
143       "$PlayerD\n\n".
144       "If you want to join this game, please follow this link:\n\n".
145       " ".$host."?me=";
146     
147     mymail($EmailA,"You are invited to a game of DoKo","Hello $PlayerA,\n".$message.$hashA);
148     mymail($EmailB,"You are invited to a game of DoKo","Hello $PlayerB,\n".$message.$hashB);
149     mymail($EmailC,"You are invited to a game of DoKo","Hello $PlayerC,\n".$message.$hashC);
150     mymail($EmailD,"You are invited to a game of DoKo","Hello $PlayerD,\n".$message.$hashD);
151     
152     echo "You started a new game. The emails have been sent out!";    
153   }    /* end set up a new game */
154 /* cancle a game, if nothing has happend in the last N minutes */
155 else if(myisset("cancle","me"))
156   {
157     $me = $_REQUEST["me"];
158     
159     /* test for valid ID */
160     $myid = DB_get_userid_by_hash($me);
161     if(!$myid)
162       {
163         echo "Can't find you in the database, please check the url.<br />\n";
164         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
165         output_footer();
166         exit();
167       }
168     
169     DB_update_user_timestamp($myid);
170     
171     /* get some information from the DB */
172     $gameid   = DB_get_gameid_by_hash($me);
173     $myname   = DB_get_name_by_hash($me);
174     
175     /* check if game really is old enough */
176     $result = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
177     $r = mysql_fetch_array($result,MYSQL_NUM);
178     if(time()-strtotime($r[0]) > 60*60*24*30) /* = 1 month */
179       {
180         $message = "Hello, \n\n".
181           "Game $gameid has been cancled since nothing happend for a while and $myname requested it.\n";
182         
183         $userids = DB_get_all_userid_by_gameid($gameid);
184         foreach($userids as $user)
185           {
186             $To = DB_get_email_by_userid($user);
187             mymail($To,$EmailName."game cancled (timed out)",$message);
188           }
189         
190         /* delete everything from the dB */
191         DB_cancel_game($me);
192         
193         echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
194       }
195     else
196       echo "<p>You need to wait longer before you can cancle a game...</p>\n";
197   }
198 /* handle request from one specific player for one game,
199  * (the hash is set on a per game base) */
200 else if(myisset("me"))
201   {
202     $me = $_REQUEST["me"];
203     
204     /* test for valid ID */
205     $myid = DB_get_userid_by_hash($me);
206     if(!$myid)
207       {
208         echo "Can't find you in the database, please check the url.<br />\n";
209         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
210         output_footer();
211         exit();
212       }
213
214     /* the user had done something, update the timestamp */
215     DB_update_user_timestamp($myid);
216     
217     /* get some information from the DB */
218     $gameid   = DB_get_gameid_by_hash($me);
219     $myname   = DB_get_name_by_hash($me);
220     $mystatus = DB_get_status_by_hash($me);
221     $mypos    = DB_get_pos_by_hash($me);
222     
223
224     /* get rule set for this game */
225     $result = mysql_query("SELECT * FROM Rulesets".
226                           " LEFT JOIN Game ON Game.ruleset=Rulesets.id ".
227                           " WHERE Game.id='$gameid'" );
228     $r      = mysql_fetch_array($result,MYSQL_NUM);
229
230     $RULES["dullen"]      = $r[2];
231     $RULES["schweinchen"] = $r[3];
232     
233     /* get some infos about the game */
234     $gametype   = DB_get_gametype_by_gameid($gameid);
235     $gamestatus = DB_get_game_status_by_gameid($gameid);
236     $GT         = $gametype;
237     if($gametype=="solo")
238       {
239         $gametype = DB_get_solo_by_gameid($gameid);
240         $GT  = $gametype." ".$GT;
241       }
242
243     /* display rule set for this game */
244     echo "<div class=\"ruleset\">\n";
245
246     if($gamestatus != 'pre')
247       echo " Gametype: $GT <br />\n";
248     
249     echo "Rules: <br />\n";
250     echo "10ofhearts : ".$r[2]."<br />\n";
251     echo "schweinchen: ".$r[3]."<br />\n";
252     echo "</div>\n";
253     
254     /* does anyone have both foxes */
255     $GAME["schweinchen"]=0; 
256     for($i=1;$i<5;$i++)
257       {
258         $hash  = DB_get_hash_from_game_and_pos($gameid,$i);
259         $cards = DB_get_all_hand($hash);
260         if( in_array("19",$cards) && in_array("20",$cards) )
261           {
262             $GAME["schweinchen"]=1;
263             $GAME["schweinchen-who"]=$hash;
264           }
265       };
266
267     /* mystatus gets the player through the different stages of a game.
268      * start:    yes/no
269      * init:     check values from start,
270      *           check for sickness
271      * check:    check for return values from init
272      * poverty:  handle poverty, wait here until all player have reached this state
273      *           display sickness and move on to game
274      * play:     game in progress
275      * gameover: are we revisiting a game
276      */
277     switch($mystatus)
278       {
279       case 'start':
280         check_want_to_play($me);
281         /* move on to the next stage*/
282         DB_set_hand_status_by_hash($me,'init');
283         break;
284       case 'init':
285         /* first check if everything went ok  in the last step
286          * if not, send user back, if yes, check what he did
287          */
288         if( !myisset("in") )
289           {
290             echo "you need to answer the <a href=\"$host?me=$me\">question</a>.";
291             DB_set_hand_status_by_hash($me,'start');
292           }
293         else
294           {
295             if($_REQUEST["in"] == "no")
296               {
297                 /* cancle the game */
298                 $message = "Hello, \n\n".
299                   "the game has been canceled due to the request of one of the players.\n";
300                 
301                 $userids = DB_get_all_userid_by_gameid($gameid);
302                 foreach($userids as $user)
303                   {
304                     $To = DB_get_email_by_userid($user);
305                     mymail($To,$EmailName."game canceled",$message);
306                   }
307                 
308                 /* delete everything from the dB */
309                 DB_cancel_game($me);
310               }
311             else
312               {
313                 echo "thanks for joining the game...";
314                 
315                 $mycards = DB_get_hand($me);
316                 sort($mycards);
317                 echo "<p class=\"mycards\" style=\"margin-top:8em;\">your cards are: <br />\n";
318                 foreach($mycards as $card) 
319                   display_card($card);
320                 echo "</p>\n";   
321                 
322                 check_for_sickness($me,$mycards);
323                 
324                 /* move on to the next stage*/
325                 DB_set_hand_status_by_hash($me,'check');
326               }
327           }
328         break;
329
330     case 'check':
331       /* ok, user is in the game, saw his cards and selected his vorbehalt
332        * so first we check what he selected
333        */
334       echo "Processing what you selected in the last step...<br />";
335
336       if(!myisset("solo","wedding","poverty","nines") )
337         {
338           /* all these variables have a pre-selected default,
339            * so we should never get here,
340            * unless a user tries to cheat ;) */
341           echo "something went wrong...please contact the admin.";
342         }
343       else
344         {
345           /* check if this sickness needs to be handled first */
346           $gametype    = DB_get_gametype_by_gameid($gameid);
347           $startplayer = DB_get_startplayer_by_gameid($gameid);
348           
349           if( $_REQUEST["solo"]!="No")
350             {
351               /* user wants to play a solo */
352
353               /* store the info in the user's hand info */
354               DB_set_solo_by_hash($me,$_REQUEST["solo"]);
355               DB_set_sickness_by_hash($me,"solo");
356
357               echo "<br />Seems like you want to play a ".$_REQUEST["solo"]." solo. Got it.<br />\n";
358               
359               if($gametype == "solo" && $startplayer<$mypos)
360                 {}/* do nothing, since someone else already is playing solo */
361               else
362                 {
363                   /* this solo comes first 
364                    * store info in game table
365                    */
366                   DB_set_gametype_by_gameid($gameid,"solo");
367                   DB_set_startplayer_by_gameid($gameid,$mypos);
368                   DB_set_solo_by_gameid($gameid,$_REQUEST["solo"]);
369                 };
370             }
371           else if($_REQUEST["wedding"] == "yes")
372             {
373               /* TODO: add silent solo somewhere*/
374               echo "Ok, you don't want to play a silent solo...wedding was chosen.<br />\n";
375               DB_set_sickness_by_hash($me,"wedding");
376             }
377           else if($_REQUEST["poverty"] == "yes")
378             {
379               echo "So you got poverty. You might as well have said nothing, since this is not implemented yet,".
380                 " you need to play a normal game...to make it a bit harder, I'll tell the other people that".
381                 " you only have a few trump... should make the game more interesting (although perhaps not for you:))<br />\n";
382               DB_set_sickness_by_hash($me,"poverty");
383             }
384           else if($_REQUEST["nines"] == "yes")
385             {
386               echo "What? You just don't want to play a game because you have a few nines? Well, if no one".
387                 " is playing solo, this game will be canceled.<br />\n";
388               DB_set_sickness_by_hash($me,"nines");
389             }
390         }
391
392       echo " Ok, done with checking, please go to the <a href=\"$host?me=$me\">next step of the setup</a>.<br />";
393
394       /* move on to the next stage*/
395       DB_set_hand_status_by_hash($me,'poverty');
396       break;
397
398     case 'poverty':
399       /* here we need to check if there is a solo or some other form of sickness.
400        * If so, which one is the most important one
401        * set that one in the Game table
402        * tell people about it.
403        */
404       echo "<br /> Checking if someone else selected solo, nines or wedding... Poverty not handled at the moment<br />";
405       
406       /* check if everyone has reached this stage */
407       $userids = DB_get_all_userid_by_gameid($gameid);
408       $ok=1;
409       foreach($userids as $user)
410         {
411           $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
412           if($userstat!='poverty' && $userstat!='play')
413             $ok=0;
414         };
415
416       if(!$ok)
417         {
418           echo "This step can only be handled after everyone finished the last step. ".
419             "Seems like this is not the case, so you need to wait a bit... please check back later....<br />";
420         }
421       else
422         {
423           echo "Everyone has finished checking their cards, let's see what they said...<br />";
424
425           /* check what kind of game we are playing,  in case there are any solos this already 
426            *will have the correct information in it */
427           $gametype    = DB_get_gametype_by_gameid($gameid);
428           $startplayer = DB_get_startplayer_by_gameid($gameid);
429
430           /* check for different sickness and just output a general info */
431
432           /* check for nines */
433           $nines = 0;
434           foreach($userids as $user)
435             if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'nines')
436               {
437                 $nines = $user;
438                 $name = DB_get_name_by_userid($user);
439                 echo "$name has a Vorbehalt. <br />";
440                 break;
441               }
442                   
443           /* check players for poverty */
444           $poverty = 0;
445           foreach($userids as $user)
446             {
447               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'poverty')
448                 {
449                   $poverty++;
450                   $name = DB_get_name_by_userid($user);
451                   echo "$name has a Vorbehalt. <br />";
452                 }
453             }
454
455           /* check players for wedding */
456           $wedding = 0;
457           foreach($userids as $user)
458             {
459               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'wedding')
460                 {
461                   $wedding=$user;
462                   $name = DB_get_name_by_userid($user);
463                   echo "$name has a Vorbehalt. <br />"  ;
464                 }
465             };
466
467           /* check for solo, output vorbehalt */
468           $solo = 0;
469           foreach($userids as $user)
470             {
471               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'solo')
472                 {
473                   $solo++;
474                   $name = DB_get_name_by_userid($user);
475                   echo "$name has a Vorbehalt. <br />"  ;
476                 }
477             }
478
479           /* now check which sickness comes first and set the gametype to it */
480
481           /* gamestatus == normal, => cancel game */
482           if($gametype == "solo")
483             {
484               /* do nothing */
485             }
486           else if($nines)
487             {
488               /* cancle game */
489               /* TODO: should we keep statistics of this? */
490               $message = "Hello, \n\n".
491                 "the game has been canceled because ".DB_get_name_by_userid($nines).
492                 " has five or more nines and nobody is playing solo.\n";
493               
494               /* TODO: add info about redeal in case this is a game of a series */
495               
496               $userids = DB_get_all_userid_by_gameid($gameid);
497               foreach($userids as $user)
498                 {
499                   $To = DB_get_email_by_userid($user);
500                   mymail($To,$EmailName."game canceled",$message);
501                 }
502               
503               /* delete everything from the dB */
504               DB_cancel_game($me);
505               
506               echo "The game has been canceled because ".DB_get_name_by_userid($nines).
507                 " has five or more nines and nobody is playing solo.\n";
508               output_footer();
509               exit();
510             }
511           else if($poverty==1 && $gametype !="poverty")
512             {
513               DB_set_gametype_by_gameid($gameid,"poverty");
514               $gametype = "poverty";
515             }
516           else if($poverty==2 && $gametype !="dpoverty")
517             {
518               DB_set_gametype_by_gameid($gameid,"dpoverty");
519               $gametype = "dpoverty";
520             }
521           else if($wedding> 0 && $gametype !="wedding")
522             {
523               DB_set_gametype_by_gameid($gameid,"wedding");
524               $gametype = "wedding";
525             };
526
527           echo "<br />\n";
528
529           /* now the gametype is set correctly (shouldn't matter that this is calculated for every user)
530            * output what kind of game we have */
531           
532           $poverty = 0;
533           foreach($userids as $user)
534             {
535               /* userids are sorted by position... 
536                * so output whatever the firstone has, then whatever the next one has
537                * stop when the sickness is the same as the gametype 
538                */
539               
540               $name     = DB_get_name_by_userid($user);
541               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
542
543               if($usersick)
544                 echo "$name has $usersick <br />"; /*TODO: perhaps save this in a string and store in Game? */
545
546               if($usersick=="poverty")
547                 $poverty++;
548               if($usersick == "wedding" && $gametype =="wedding")
549                 break;
550               if($usersick == "poverty" && $gametype =="poverty")
551                 break;
552               if($usersick == "poverty" && $gametype =="dpoverty" && $poverty==2)
553                 break;
554               if($usersick == "solo" && $gametype =="solo")
555                 break;
556             };
557
558           /* output Schweinchen in case the rules need it */
559           if( $gametype != "solo")
560             if($GAME["schweinchen"] && $RULES["schweinchen"]=="both" )
561               echo DB_get_name_by_hash($GAME["schweinchen-who"])." has Schweinchen. <br />";
562           
563           echo "<br />\n";
564           
565           /* finished the setup, set re/contra parties if possible, go to next stage unless there is a case of poverty*/
566           switch($gametype)
567             {
568             case "solo":
569               /* are we the solo player? set us to re, else set us to contra */
570               $pos = DB_get_pos_by_hash($me);
571               if($pos == $startplayer)
572                 DB_set_party_by_hash($me,"re");
573               else
574                 DB_set_party_by_hash($me,"contra");
575               DB_set_hand_status_by_hash($me,'play');
576               break;
577
578             case "wedding":
579               /* set person with the wedding to re, do the rest during the game */
580               $usersick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
581               if($usersick == "wedding")
582                 DB_set_party_by_hash($me,"re");
583               
584               echo "Don't know who will be Re and Contra, you need to ".
585                 "figure that out at the end of the game yourself <br />\n";
586               DB_set_hand_status_by_hash($me,'play');
587               break;
588
589             case "normal":
590               $hand = DB_get_all_hand($me);
591               
592               if(in_array('3',$hand)||in_array('4',$hand))
593                 DB_set_party_by_hash($me,"re");
594               else
595                 DB_set_party_by_hash($me,"contra");
596               DB_set_hand_status_by_hash($me,'play');
597               break;
598             case "poverty":
599               /* use extra column in DB.Game to store whom to ask, 
600                * should be set for poverty and dpoverty(use two digits for dpoverty?) earlier*/
601
602               /* check if poverty resolved (e.g. DB.Game who set to NULL)
603                *   yes? =>trump was taken, start game; break; 
604                *   
605                * check if we are being asked now
606                *    no, display wait message, e.g. player X is asked at the moment
607                *    yes, display number of trump and user's hand, ask if he wants to take it 
608                *      no, set whom-to-ask to next player, email next player, cancle game if no next player
609                *      yes -> link to new page:display all cards, ask for N return cards
610                *          set re/contra 
611                *        
612                */
613             case "dpoverty":
614               echo "TODO: handle poverty here (almost done in my developing version)";
615               DB_set_hand_status_by_hash($me,'play');
616             };
617         }
618       
619       /* check if all players are ready to play */
620       $ok=1;
621       foreach($userids as $user)
622         if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
623           $ok=0;
624
625       if($ok)
626         {
627           /* only set this after all poverty, etc. are handled*/
628           DB_set_game_status_by_gameid($gameid,'play');
629
630           /* email startplayer */
631           $startplayer = DB_get_startplayer_by_gameid($gameid);
632           $email       = DB_get_email_by_pos_and_gameid($startplayer,$gameid);
633           $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
634           
635           if($hash!=$me)
636             {
637               /* email startplayer) */
638               $message = "It's your turn now.\n".
639                 "Use this link to play a card: ".$host."?me=".$hash."\n\n" ;
640               mymail($email,$EmailName."ready, set, go... ",$message);
641             }
642           else
643             echo " Please, <a href=\"$host?me=$me\">start</a> the game.<br />";  
644         }
645       else
646         echo "You finished the setup, once everyone else has done the same you'll get an email when it is your turn..<br />";    
647
648       break;
649     case 'play':
650     case 'gameover': 
651       /* both entries here,  so that the tricks are visible for both.
652        * in case of 'play' there is a break later that skips the last part
653        */
654       
655       /* figure out what kind of game we are playing, 
656        * set the global variables $CARDS["trump"],$CARDS["diamonds"],$CARDS["hearts"],
657        * $CARDS["clubs"],$CARDS["spades"],$CARDS["foxes"]
658        * accordingly
659        */
660       
661       $gametype = DB_get_gametype_by_gameid($gameid);
662       $GT = $gametype;
663       if($gametype=="solo")
664         {
665           $gametype = DB_get_solo_by_gameid($gameid);
666           $GT = $gametype." ".$GT;
667         }
668       else
669         $gametype="normal";
670       
671       set_gametype($gametype); /* this sets the $CARDS variable */
672       
673       /* get some infos about the game */
674       $gamestatus = DB_get_game_status_by_gameid($gameid);
675       
676       /* display useful things in divs */
677       
678       /* display links to the users status page */
679       $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
680       $r      = mysql_fetch_array($result,MYSQL_NUM);
681       
682       display_links($r[0],$r[1]);
683       
684       /* end display useful things*/
685       
686       /* has the game started? No, then just wait here...*/
687       if($gamestatus == 'pre')
688         {
689           echo "You finished the setup, but not everyone else finished it...so you need to wait for the others... <br />";
690           break; /* not sure this works... the idea is that you can 
691                   * only  play a card after everyone is ready to play */
692         }
693       
694       /* display the table and the names */
695       $result = mysql_query("SELECT  User.fullname as name,".
696                             "        Hand.position as position, ".
697                             "        User.id ".
698                             "FROM Hand ".
699                             "LEFT JOIN User ON User.id=Hand.user_id ".
700                             "WHERE Hand.game_id='".$gameid."' ".
701                             "ORDER BY position ASC");
702       
703       echo "<div class=\"table\">\n".
704         "  <img src=\"pics/table.png\" alt=\"table\" />\n";
705       while($r = mysql_fetch_array($result,MYSQL_NUM))
706         {
707           $name = $r[0];
708           $pos  = $r[1];
709           $user = $r[2];
710
711           $offset = DB_get_user_timezone($user);
712           $zone   = return_timezone($offset);
713           date_default_timezone_set($zone);
714
715           echo " <span class=\"table".($pos-1)."\">\n";
716           echo " $name <br />\n";
717           echo " local time: ".date("Y-m-d H:i:s")."\n";
718           echo " </span>\n";
719
720         }
721       echo  "</div>\n";
722
723       /* get everything relevant to display the tricks */
724       $result = mysql_query("SELECT Hand_Card.card_id as card,".
725                             "       Hand.position as position,".
726                             "       Play.sequence as sequence, ".
727                             "       Trick.id, ".
728                             "       Comment.comment ".
729                             "FROM Trick ".
730                             "LEFT JOIN Play ON Trick.id=Play.trick_id ".
731                             "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
732                             "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
733                             "LEFT JOIN Comment ON Play.id=Comment.play_id ".
734                             "WHERE Trick.game_id='".$gameid."' ".
735                             "ORDER BY Trick.id,sequence ASC");
736       $trickNR = 1;
737       
738       $lasttrick = DB_get_max_trickid($gameid);
739       
740       $play = array(); /* needed to calculate winner later  */
741       $seq  = 1;          
742       $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
743       $firstcard = ""; /* first card in a trick */
744       
745       echo "\n<ul class=\"tricks\">\n";
746       echo "  <li class=\"nohighlight\"> Game $gameid: </li>\n";
747       
748       while($r = mysql_fetch_array($result,MYSQL_NUM))
749         {
750           $pos     = $r[1];
751           $seq     = $r[2];
752           $trick   = $r[3];
753           $comment = $r[4];
754           
755           /* check if first schweinchen has been played */
756           if($r[0] == 19 || $r[0] == 20 )
757             $GAME["schweinchen"]++;
758           
759           /* save card to be able to find the winner of the trick later */
760           $play[$seq] = array("card"=>$r[0],"pos"=>$pos); 
761           
762           if($seq==1)
763             {
764               /* first card in a trick, output some html */
765               if($trick!=$lasttrick)
766                 {
767                   /* start of an old trick? */
768                   echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">Trick $trickNR</a>\n".
769                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
770                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
771                 }
772               else if($trick==$lasttrick)
773                 {
774                   /* start of a last trick? */
775                   echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">Trick $trickNR</a>\n".
776                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
777                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
778                 };
779               
780               /* remember first card, so that we are able to check, what cards can be played */
781               $firstcard = $r[0];
782             };
783           
784           /* display card */
785           echo "      <div class=\"card".($pos-1)."\">\n";
786           
787           /* display comments */
788           if($comment!="")
789             echo "        <span class=\"comment\">".$comment."</span>\n";
790           
791           echo "        ";
792           display_card($r[0]);
793           
794           echo "      </div>\n"; /* end div card */
795           
796           /* end of trick? */
797           if($seq==4)
798             {
799               $trickNR++;
800               echo "    </div>\n  </li>\n";  /* end div table, end li table */
801             }
802         }
803       
804       if($seq!=4 && $trickNR>1) 
805         echo "    </div>\n  </li>\n";  /* end div table, end li table */
806       
807       echo "</ul>\n";
808       
809       /* whos turn is it? */
810       if($seq==4)
811         {
812           $winner = get_winner($play,$gametype); /* returns the position */
813           $next = $winner;
814           $firstcard = ""; /* new trick, no first card */
815         }
816       else
817         {
818           $next = $pos+1;
819           if($next==5) $next=1;
820         }
821       
822       /* my turn?, display cards as links, ask for comments*/
823       if(DB_get_pos_by_hash($me) == $next)
824         $myturn = 1;
825       else
826         $myturn = 0;
827       
828       /* do we want to play a card? */
829       if(myisset("card") && $myturn)
830         {
831           $card   = $_REQUEST["card"];
832           $handid = DB_get_handid_by_hash($me); 
833           
834           /* check if we have card and that we haven't played it yet*/
835           /* set played in hand_card to true where hand_id and card_id*/
836           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
837                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
838           $r = mysql_fetch_array($result,MYSQL_NUM);
839           $handcardid = $r[0];
840           
841           if($handcardid)
842             {
843               $comment = "";
844
845               /* mark card as played */
846               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
847                           DB_quote_smart($card));
848               /* update Game timestamp */
849               DB_update_game_timestamp($gameid);
850
851               /* check for schweinchen */
852               //echo "schweinchen = ".$GAME["schweinchen"]." --$card-<br />";
853               if($card == 19 || $card == 20 )
854                 {
855                   $GAME["schweinchen"]++;
856                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
857                     $comment="Schweinchen! ";
858                   if($RULES["schweinchen"]=="both" )
859                     $comment="Schweinchen! ";
860                   echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
861                 }
862
863               /* get trick id or start new trick */
864               $a = DB_get_current_trickid($gameid);
865               $trickid  = $a[0];
866               $sequence = $a[1];
867               
868               $playid = DB_play_card($trickid,$handcardid,$sequence);
869               
870               /* check for coment */
871               if(myisset("comment"))
872                 {
873                   $comment.=$_REQUEST["comment"];
874                 };  
875               if($comment != "")
876                 DB_insert_comment($comment,$playid,$myid);
877
878               /* display played card */
879               echo "<div class=\"card\">";
880               echo " you played  <br />";
881               display_card($card);
882               echo "</div>\n";
883               
884               /*check if we still have cards left, else set status to gameover */
885               if(sizeof(DB_get_hand($me))==0)
886                 {
887                   DB_set_hand_status_by_hash($me,'gameover');
888                   $mystatus='gameover';
889                 }
890               
891               /* if all players are done, set game status to game over, 
892                * get the points of the last trick and send out an email 
893                * to all players
894                */
895               $userids = DB_get_all_userid_by_gameid($gameid);
896               
897               $done=1;
898               foreach($userids as $user)
899                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
900                   $done=0;
901               
902               if($done)
903                 {
904                   DB_set_game_status_by_gameid($gameid,"gameover");
905                   /* get score for last trick 
906                    * all other tricks are handled a few lines further down*/
907                   $play   = DB_get_cards_by_trick($trickid);
908                   $winner = get_winner($play,$gametype); /* returns the position */
909                   /* get points of last trick and save it */
910                   $points = 0;
911                   foreach($play as $card)
912                     $points = $points + card_value($card["card"]);
913                   $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
914                   if($winnerid>0)
915                     mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
916                   else
917                     echo "ERROR during scoring";
918                   
919                   /* email all players */
920                   /* individual score */
921                   $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
922                                         " LEFT JOIN Hand ON Hand.id=hand_id".
923                                         " LEFT JOIN User ON Hand.user_id=User.id".
924                                         " WHERE Hand.game_id=$gameid".
925                                         " GROUP BY fullname" );
926                   $message = "The game is over. Thanks for playing :)\n";
927                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
928                     $message .= " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."\n";
929                   $message .= "\nIf your not in the list above your score is zero...\n\n";
930
931                   $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
932                                         " LEFT JOIN Hand ON Hand.id=hand_id".
933                                         " LEFT JOIN User ON Hand.user_id=User.id".
934                                         " WHERE Hand.game_id=$gameid".
935                                         " GROUP BY Hand.party" );
936                   $message .= "\n";
937                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
938                     $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
939
940                   foreach($userids as $user)
941                     {
942                       $To = DB_get_email_by_userid($user);
943                       mymail($To,$EmailName."game over",$message);
944                     }
945                 }
946               
947               
948               /* email next player */
949               if(DB_get_game_status_by_gameid($gameid)=='play')
950                 {
951                   if($sequence==4)
952                     {
953                       $play   = DB_get_cards_by_trick($trickid);
954                       $winner = get_winner($play,$gametype); /* returns the position */
955                       
956                       /* get points of last trick and save it, last trick is handled 
957                        * a few lines further up  */
958                       $points = 0;
959                       foreach($play as $card)
960                         $points = $points + card_value($card["card"]);
961                       
962                       $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
963                       if($winnerid>0)
964                         mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
965                       else
966                         echo "ERROR during scoring";
967                       
968                       if($debug)
969                         echo "DEBUG: $winner got $points <br />";
970                       
971                       /* who is the next player? */
972                       $next = $winner;
973                     }
974                   else
975                     {
976                       $next = DB_get_pos_by_hash($me)+1;
977                     }
978                   if($next==5) $next=1;
979                   
980                   /* email next player */
981                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
982                   $email     = DB_get_email_by_hash($next_hash);
983                   
984                   $message = "It's your turn  now.\n".
985                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
986                   mymail($email,$EmailName."a card has been played",$message);
987                   
988                   if($debug)
989                     echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
990                       "\"> next player </a> <br />\n";
991                   
992                 }
993             }
994           else
995             {
996               echo "can't find that card?! <br />\n";
997             }
998         }
999       else if(myisset("card") && !$myturn )
1000         {
1001           echo "please wait until it's your turn! <br />\n";
1002         }
1003       
1004       $mycards = DB_get_hand($me);
1005       $mycards = mysort($mycards,$gametype);
1006       echo "<div class=\"mycards\">\n";
1007       
1008       if($myturn && !myisset("card"))
1009         {
1010           echo "Hello ".$myname.", it's your turn!  <br />\n";
1011           echo "Your cards are: <br />\n";
1012           echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
1013           
1014           /* do we have to follow suite? */
1015           $followsuit = 0;
1016           if(have_suit($mycards,$firstcard))
1017             $followsuit = 1;
1018           
1019           foreach($mycards as $card) 
1020             {
1021               if($followsuit && !same_type($card,$firstcard))
1022                 display_card($card);
1023               else
1024                 display_link_card($card);
1025             }
1026           
1027           echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
1028           echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
1029           echo "<input type=\"submit\" value=\"move\" />\n";
1030           echo "</form>\n";
1031         }
1032       else if($mystatus=='play')
1033         {
1034           echo "Your cards are: <br />\n";
1035           foreach($mycards as $card) 
1036             display_card($card);
1037         }
1038       else if($mystatus=='gameover')
1039         {
1040           $oldcards = DB_get_all_hand($me);
1041           $oldcards = mysort($oldcards,$gametype);
1042           echo "Your cards were: <br />\n";
1043           foreach($oldcards as $card) 
1044             display_card($card);
1045         }
1046       echo "</div>\n";
1047       
1048       /* check if we need to set status to 'gameover' is done during playing of the card */
1049       if($mystatus=='play')
1050         break;
1051       /* the following happens only when the gamestatus is 'gameover' */
1052       /* check if game is over, display results */
1053       if(DB_get_game_status_by_gameid($gameid)=='play')
1054         {
1055           echo "the game is over for you.. other people still need to play though";
1056         }
1057       else
1058         {
1059           echo "the game is over now...<br />\n";
1060           
1061           $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1062                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1063                                 " LEFT JOIN User ON Hand.user_id=User.id".
1064                                 " WHERE Hand.game_id=$gameid".
1065                                 " GROUP BY fullname" );
1066           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1067             echo " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."<br />";
1068           
1069           $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1070                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1071                                 " LEFT JOIN User ON Hand.user_id=User.id".
1072                                 " WHERE Hand.game_id=$gameid".
1073                                 " GROUP BY Hand.party" );
1074           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1075             echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />\n";
1076
1077           
1078           $session = DB_get_session_by_gameid($gameid);
1079           $result  = mysql_query("SELECT id,create_date FROM Game".
1080                                  " WHERE session=$session".
1081                                  " ORDER BY create_date DESC".
1082                                  " LIMIT 1");
1083           $r=-1;
1084           if($result)
1085             $r = mysql_fetch_array($result,MYSQL_NUM);
1086           
1087           if(!$session || $gameid==$r[0])
1088             {
1089               /* suggest a new game with the same people in it, just rotated once */
1090               $names = DB_get_all_names_by_gameid($gameid);
1091               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1092             }
1093         }
1094       break;
1095     default:
1096       echo "error in testing the status";
1097     }
1098     output_footer();
1099     exit();
1100  } 
1101 /* user status page */ 
1102  else if(myisset("email","password"))
1103    {
1104      /* test id and password, should really be done in one step */
1105      $email     = $_REQUEST["email"];
1106      $password  = $_REQUEST["password"];
1107
1108      if(myisset("forgot"))
1109        {
1110          $ok=1;
1111
1112          $uid = DB_get_userid_by_email($email);
1113          if(!$uid)
1114            $ok=0;
1115          
1116          if($ok)
1117            {
1118              echo "Hmm, you forgot your passwort...nothing I can do at the moment:(  ";
1119              echo " you need to email Arun for now... in the future it will be all automated and an ";
1120              echo "email with a new password will go to $email.";
1121            }
1122          else
1123            {
1124              if($email=="")
1125                echo "you need to give me an email address!";
1126              else
1127                echo "couldn't find a player with this email, please contact Arun, if you think this is a mistake";
1128            } 
1129        }
1130      else 
1131      {
1132        if(strlen($password)!=32)
1133          $password = md5($password);
1134        
1135        $ok=1;
1136        $uid = DB_get_userid_by_email_and_password($email,$password);
1137        if(!$uid)
1138          $ok=0;
1139        
1140        if($ok)
1141          {
1142            $time = DB_get_user_timestamp($uid);
1143            $unixtime =strtotime($time);
1144            
1145            $offset = DB_get_user_timezone($uid);
1146            $zone = return_timezone($offset);
1147            date_default_timezone_set($zone);
1148            
1149            echo "last login: ".date("r",$unixtime)."<br />";
1150            
1151            DB_update_user_timestamp($uid);
1152            
1153            echo "<p>these are the games you are playing in:<br />\n";
1154            $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
1155                                  " LEFT JOIN Game On Hand.game_id=Game.id".
1156                                  " WHERE Hand.user_id='$uid' AND Game.status<>'gameover'" );
1157            while( $r = mysql_fetch_array($result,MYSQL_NUM))
1158              {
1159                echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1160                if(time()-strtotime($r[2]) > 60*60*24*30)
1161                  echo " The game has been running for over a month.".
1162                    " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1163                    " (clicking here is final and can't be restored)";
1164                echo "<br />";
1165              }
1166            echo "</p>\n";
1167            
1168            
1169            echo "<p>and these are your games that are already done:<br />Game: \n";
1170            $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
1171            while( $r = mysql_fetch_array($result,MYSQL_NUM))
1172              echo "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>, ";
1173            echo "</p>\n";
1174            
1175            $names = DB_get_all_names();
1176            echo "<p>registered players:<br />\n";
1177            foreach ($names as $name)
1178              echo "$name, \n";
1179            echo "</p>\n";
1180            
1181            echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
1182          }
1183        else
1184          {
1185            echo "sorry email and password don't match <br />";
1186          }
1187      };
1188      output_footer();
1189      exit();
1190    }
1191 /* page for registration */
1192  else if(myisset("register") )
1193    {
1194      output_register();
1195    }
1196 /* new user wants to register */
1197  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
1198    {
1199      $ok=1;
1200      if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
1201        {
1202          echo "please chose another name<br />";
1203          $ok=0;
1204        }
1205      if(DB_get_userid_by_email($_REQUEST["Remail"]))
1206        {
1207          echo "this email address is already used ?!<br />";
1208          $ok=0;
1209        }
1210      if($ok)
1211        {
1212          $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
1213                         ",".DB_quote_smart($_REQUEST["Remail"]).
1214                         ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
1215                         ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
1216          
1217          if($r)
1218            echo " added you to the database";
1219          else
1220            echo " something went wrong";
1221        }
1222    }
1223 /* default login page */
1224  else
1225    { 
1226      $pre=0;$game=0;$done=0;
1227      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
1228      if($r) {
1229        $pre = mysql_fetch_array($r,MYSQL_NUM);     
1230        $game = mysql_fetch_array($r,MYSQL_NUM);     
1231        $done = mysql_fetch_array($r,MYSQL_NUM);     
1232      }
1233      output_home_page($pre[0],$game[0],$done[0]);
1234    }
1235
1236 output_footer();
1237
1238 DB_close();
1239
1240 /*
1241  *Local Variables: 
1242  *mode: php
1243  *mode: hs-minor
1244  *End:
1245  */
1246 ?>
1247
1248