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