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