minor 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 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       
627       display_links($r[0],$r[1]);
628       
629       /* end display useful things*/
630       
631       /* has the game started? No, then just wait here...*/
632       if($gamestatus == 'pre')
633         {
634           echo "you need to wait for the others... <br />";
635           break; /* not sure this works... the idea is that you can 
636                   * only  play a card after everyone is ready to play */
637         }
638       
639       /* display the table and the names */
640       $result = mysql_query("SELECT  User.fullname as name,".
641                             "        Hand.position as position, ".
642                             "        User.id ".
643                             "FROM Hand ".
644                             "LEFT JOIN User ON User.id=Hand.user_id ".
645                             "WHERE Hand.game_id='".$gameid."' ".
646                             "ORDER BY position ASC");
647       
648       echo "<div class=\"table\">\n".
649         "  <img src=\"pics/table.png\" alt=\"table\" />\n";
650       while($r = mysql_fetch_array($result,MYSQL_NUM))
651         {
652           $name = $r[0];
653           $pos  = $r[1];
654           $user = $r[2];
655
656           $offset = DB_get_user_timezone($user);
657           $zone   = return_timezone($offset);
658           date_default_timezone_set($zone);
659
660           echo " <span class=\"table".($pos-1)."\">\n";
661           echo " $name <br />\n";
662           echo " local time: ".date("Y-m-d H:i:s")."\n";
663           echo " </span>\n";
664
665         }
666       echo  "</div>\n";
667
668       /* get everything relevant to display the tricks */
669       $result = mysql_query("SELECT Hand_Card.card_id as card,".
670                             "       Hand.position as position,".
671                             "       Play.sequence as sequence, ".
672                             "       Trick.id, ".
673                             "       Comment.comment ".
674                             "FROM Trick ".
675                             "LEFT JOIN Play ON Trick.id=Play.trick_id ".
676                             "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
677                             "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
678                             "LEFT JOIN Comment ON Play.id=Comment.play_id ".
679                             "WHERE Trick.game_id='".$gameid."' ".
680                             "ORDER BY Trick.id,sequence ASC");
681       $trickNR = 1;
682       
683       $lasttrick = DB_get_max_trickid($gameid);
684       
685       $play = array(); /* needed to calculate winner later  */
686       $seq  = 1;          
687       $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
688       $firstcard = ""; /* first card in a trick */
689       
690       echo "\n<ul class=\"tricks\">\n";
691       echo "  <li class=\"nohighlight\"> Game $gameid: </li>\n";
692       
693       while($r = mysql_fetch_array($result,MYSQL_NUM))
694         {
695           $pos     = $r[1];
696           $seq     = $r[2];
697           $trick   = $r[3];
698           $comment = $r[4];
699           
700           /* check if first schweinchen has been played */
701           if($r[0] == 19 || $r[0] == 20 )
702             $GAME["schweinchen"]++;
703           
704           /* save card to be able to find the winner of the trick later */
705           $play[$seq] = array("card"=>$r[0],"pos"=>$pos); 
706           
707           if($seq==1)
708             {
709               /* first card in a trick, output some html */
710               if($trick!=$lasttrick)
711                 {
712                   /* start of an old trick? */
713                   echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">Trick $trickNR</a>\n".
714                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
715                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
716                 }
717               else if($trick==$lasttrick)
718                 {
719                   /* start of a last trick? */
720                   echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">Trick $trickNR</a>\n".
721                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
722                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
723                 };
724               
725               /* remember first card, so that we are able to check, what cards can be played */
726               $firstcard = $r[0];
727             };
728           
729           /* display card */
730           echo "      <div class=\"card".($pos-1)."\">\n";
731           
732           /* display comments */
733           if($comment!="")
734             echo "        <span class=\"comment\">".$comment."</span>\n";
735           
736           echo "        ";
737           display_card($r[0]);
738           
739           echo "      </div>\n"; /* end div card */
740           
741           /* end of trick? */
742           if($seq==4)
743             {
744               $trickNR++;
745               echo "    </div>\n  </li>\n";  /* end div table, end li table */
746             }
747         }
748       
749       if($seq!=4 && $trickNR>1) 
750         echo "    </div>\n  </li>\n";  /* end div table, end li table */
751       
752       echo "</ul>\n";
753       
754       /* whos turn is it? */
755       if($seq==4)
756         {
757           $winner = get_winner($play,$gametype); /* returns the position */
758           $next = $winner;
759           $firstcard = ""; /* new trick, no first card */
760         }
761       else
762         {
763           $next = $pos+1;
764           if($next==5) $next=1;
765         }
766       
767       /* my turn?, display cards as links, ask for comments*/
768       if(DB_get_pos_by_hash($me) == $next)
769         $myturn = 1;
770       else
771         $myturn = 0;
772       
773       /* do we want to play a card? */
774       if(myisset("card") && $myturn)
775         {
776           $card   = $_REQUEST["card"];
777           $handid = DB_get_handid_by_hash($me); 
778           
779           /* check if we have card and that we haven't played it yet*/
780           /* set played in hand_card to true where hand_id and card_id*/
781           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
782                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
783           $r = mysql_fetch_array($result,MYSQL_NUM);
784           $handcardid = $r[0];
785           
786           if($handcardid)
787             {
788               $comment = "";
789
790               /* mark card as played */
791               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
792                           DB_quote_smart($card));
793               
794               /* check for schweinchen */
795               echo "schweinchen = ".$GAME["schweinchen"]." --$card-<br />";
796               if($card == 19 || $card == 20 )
797                 {
798                   $GAME["schweinchen"]++;
799                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
800                     $comment="Schweinchen! ";
801                   if($RULES["schweinchen"]=="both" )
802                     $comment="Schweinchen! ";
803                   echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
804                 }
805
806               /* get trick id or start new trick */
807               $a = DB_get_current_trickid($gameid);
808               $trickid  = $a[0];
809               $sequence = $a[1];
810               
811               $playid = DB_play_card($trickid,$handcardid,$sequence);
812               
813               /* check for coment */
814               if(myisset("comment"))
815                 {
816                   $comment.=$_REQUEST["comment"];
817                 };  
818               if($comment != "")
819                 DB_insert_comment($comment,$playid,$myid);
820
821               /* display played card */
822               echo "<div class=\"card\">";
823               echo " you played  <br />";
824               display_card($card);
825               echo "</div>\n";
826               
827               /*check if we still have cards left, else set status to gameover */
828               if(sizeof(DB_get_hand($me))==0)
829                 {
830                   DB_set_hand_status_by_hash($me,'gameover');
831                   $mystatus='gameover';
832                 }
833               
834               /* if all players are done, set game status to game over, 
835                * get the points of the last trick and send out an email 
836                * to all players
837                */
838               $userids = DB_get_all_userid_by_gameid($gameid);
839               
840               $done=1;
841               foreach($userids as $user)
842                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
843                   $done=0;
844               
845               if($done)
846                 {
847                   DB_set_game_status_by_gameid($gameid,"gameover");
848                   /* get score for last trick 
849                    * all other tricks are handled a few lines further down*/
850                   $play   = DB_get_cards_by_trick($trickid);
851                   $winner = get_winner($play,$gametype); /* returns the position */
852                   /* get points of last trick and save it */
853                   $points = 0;
854                   foreach($play as $card)
855                     $points = $points + card_value($card["card"]);
856                   $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
857                   if($winnerid>0)
858                     mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
859                   else
860                     echo "ERROR during scoring";
861                   
862                   /* email all players */
863                   /* individual score */
864                   $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
865                                         " LEFT JOIN Hand ON Hand.id=hand_id".
866                                         " LEFT JOIN User ON Hand.user_id=User.id".
867                                         " WHERE Hand.game_id=$gameid".
868                                         " GROUP BY fullname" );
869                   $message = "The game is over. Thanks for playing :)\n";
870                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
871                     $message .= " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."\n";
872                   $message .= "\nIf your not in the list above your score is zero...\n\n";
873
874                   $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
875                                         " LEFT JOIN Hand ON Hand.id=hand_id".
876                                         " LEFT JOIN User ON Hand.user_id=User.id".
877                                         " WHERE Hand.game_id=$gameid".
878                                         " GROUP BY Hand.party" );
879                   $message .= "\n";
880                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
881                     $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
882
883                   foreach($userids as $user)
884                     {
885                       $To = DB_get_email_by_userid($user);
886                       mymail($To,$EmailName."game over",$message);
887                     }
888                 }
889               
890               
891               /* email next player */
892               if(DB_get_game_status_by_gameid($gameid)=='play')
893                 {
894                   if($sequence==4)
895                     {
896                       $play   = DB_get_cards_by_trick($trickid);
897                       $winner = get_winner($play,$gametype); /* returns the position */
898                       
899                       /* get points of last trick and save it, last trick is handled 
900                        * a few lines further up  */
901                       $points = 0;
902                       foreach($play as $card)
903                         $points = $points + card_value($card["card"]);
904                       
905                       $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
906                       if($winnerid>0)
907                         mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
908                       else
909                         echo "ERROR during scoring";
910                       
911                       if($debug)
912                         echo "DEBUG: $winner got $points <br />";
913                       
914                       /* who is the next player? */
915                       $next = $winner;
916                     }
917                   else
918                     {
919                       $next = DB_get_pos_by_hash($me)+1;
920                     }
921                   if($next==5) $next=1;
922                   
923                   /* email next player */
924                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
925                   $email     = DB_get_email_by_hash($next_hash);
926                   
927                   $message = "It's your turn  now.\n".
928                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
929                   mymail($email,$EmailName."a card has been played",$message);
930                   
931                   if($debug)
932                     echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
933                       "\"> next player </a> <br />\n";
934                   
935                 }
936             }
937           else
938             {
939               echo "can't find that card?! <br />\n";
940             }
941         }
942       else if(myisset("card") && !$myturn )
943         {
944           echo "please wait until it's your turn! <br />\n";
945         }
946       
947       $mycards = DB_get_hand($me);
948       $mycards = mysort($mycards,$gametype);
949       echo "<div class=\"mycards\">\n";
950       
951       if($myturn && !myisset("card"))
952         {
953           echo "Hello ".$myname.", it's your turn!  <br />\n";
954           echo "Your cards are: <br />\n";
955           echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
956           
957           /* do we have to follow suite? */
958           $followsuit = 0;
959           if(have_suit($mycards,$firstcard))
960             $followsuit = 1;
961           
962           foreach($mycards as $card) 
963             {
964               if($followsuit && !same_type($card,$firstcard))
965                 display_card($card);
966               else
967                 display_link_card($card);
968             }
969           
970           echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
971           echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
972           echo "<input type=\"submit\" value=\"move\" />\n";
973           echo "</form>\n";
974         }
975       else if($mystatus=='play')
976         {
977           echo "Your cards are: <br />\n";
978           foreach($mycards as $card) 
979             display_card($card);
980         }
981       else if($mystatus=='gameover')
982         {
983           $oldcards = DB_get_all_hand($me);
984           $oldcards = mysort($oldcards,$gametype);
985           echo "Your cards were: <br />\n";
986           foreach($oldcards as $card) 
987             display_card($card);
988         }
989       echo "</div>\n";
990       
991       /* check if we need to set status to 'gameover' is done during playing of the card */
992       if($mystatus=='play')
993         break;
994       /* the following happens only when the gamestatus is 'gameover' */
995       /* check if game is over, display results */
996       if(DB_get_game_status_by_gameid($gameid)=='play')
997         {
998           echo "the game is over for you.. other people still need to play though";
999         }
1000       else
1001         {
1002           echo "the game is over now...<br />\n";
1003           
1004           $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1005                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1006                                 " LEFT JOIN User ON Hand.user_id=User.id".
1007                                 " WHERE Hand.game_id=$gameid".
1008                                 " GROUP BY fullname" );
1009           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1010             echo " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."<br />";
1011           
1012           $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1013                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1014                                 " LEFT JOIN User ON Hand.user_id=User.id".
1015                                 " WHERE Hand.game_id=$gameid".
1016                                 " GROUP BY Hand.party" );
1017           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1018             echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />\n";
1019
1020           
1021           $session = DB_get_session_by_gameid($gameid);
1022           $result  = mysql_query("SELECT id,create_date FROM Game".
1023                                  " WHERE session=$session".
1024                                  " ORDER BY create_date DESC".
1025                                  " LIMIT 1");
1026           $r=-1;
1027           if($result)
1028             $r = mysql_fetch_array($result,MYSQL_NUM);
1029           
1030           if(!$session || $gameid==$r[0])
1031             {
1032               /* suggest a new game with the same people in it, just rotated once */
1033               $names = DB_get_all_names_by_gameid($gameid);
1034               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1035             }
1036         }
1037       break;
1038     default:
1039       echo "error in testing the status";
1040     }
1041     output_footer();
1042   exit();
1043  } 
1044 /* user status page */ 
1045  else if(myisset("email","password"))
1046    {
1047      /* test id and password, should really be done in one step */
1048      $email     = $_REQUEST["email"];
1049      $password  = $_REQUEST["password"];
1050      
1051      if(strlen($password)!=32)
1052        $password = md5($password);
1053      
1054      $ok=1;
1055      $uid = DB_get_userid_by_email_and_password($email,$password);
1056      if(!$uid)
1057        $ok=0;
1058      
1059      if($ok)
1060        {
1061          $time = DB_get_user_timestamp($uid);
1062          $unixtime =strtotime($time);
1063          
1064          $offset = DB_get_user_timezone($uid);
1065          $zone = return_timezone($offset);
1066          date_default_timezone_set($zone);
1067          
1068          echo "last login: ".date("r",$unixtime)."<br />";
1069          
1070          DB_update_user_timestamp($uid);
1071          
1072          echo "<p>these are the games you are playing in:<br />\n";
1073          $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
1074                                " LEFT JOIN Game On Hand.game_id=Game.id".
1075                                " WHERE Hand.user_id='$uid' AND Game.status<>'gameover'" );
1076          while( $r = mysql_fetch_array($result,MYSQL_NUM))
1077            {
1078              echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1079              if(time()-strtotime($r[2]) > 60*60*24*30)
1080                echo " The game has been running for over a month.".
1081                  " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1082                  " (clicking here is final and can't be restored)";
1083              echo "<br />";
1084            }
1085          echo "</p>\n";
1086          
1087          
1088          echo "<p>and these are your games that are already done:<br />Game: \n";
1089          $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
1090          while( $r = mysql_fetch_array($result,MYSQL_NUM))
1091            echo "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>, ";
1092          echo "</p>\n";
1093          
1094          $names = DB_get_all_names();
1095          echo "<p>registered players:<br />\n";
1096          foreach ($names as $name)
1097            echo "$name, \n";
1098          echo "</p>\n";
1099          
1100          echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
1101        }
1102      else
1103        {
1104          echo "sorry email and password don't match <br />";
1105        }
1106      output_footer();
1107      exit();
1108    }
1109 /* page for registration */
1110  else if(myisset("register") )
1111    {
1112      output_register();
1113    }
1114 /* new user wants to register */
1115  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
1116    {
1117      $ok=1;
1118      if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
1119        {
1120          echo "please chose another name<br />";
1121          $ok=0;
1122        }
1123      if(DB_get_userid_by_email($_REQUEST["Remail"]))
1124        {
1125          echo "this email address is already used ?!<br />";
1126          $ok=0;
1127        }
1128      if($ok)
1129        {
1130          $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
1131                         ",".DB_quote_smart($_REQUEST["Remail"]).
1132                         ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
1133                         ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
1134          
1135          if($r)
1136            echo " added you to the database";
1137          else
1138            echo " something went wrong";
1139        }
1140    }
1141 /* default login page */
1142  else
1143    { 
1144      $pre=0;$game=0;$done=0;
1145      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
1146      if($r) {
1147        $pre = mysql_fetch_array($r,MYSQL_NUM);     
1148        $game = mysql_fetch_array($r,MYSQL_NUM);     
1149        $done = mysql_fetch_array($r,MYSQL_NUM);     
1150      }
1151      output_home_page($pre[0],$game[0],$done[0]);
1152    }
1153
1154 output_footer();
1155
1156 DB_close();
1157
1158 /*
1159  *Local Variables: 
1160  *mode: php
1161  *mode: hs-minor
1162  *End:
1163  */
1164 ?>
1165
1166