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