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