bd5702e3fe558b890374f3a53dec460bff18c889
[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 "wedding was chosen, can't handle it at the moment, you need to send out".
332                 " an email by hand to the other players<br />\n";
333               DB_set_sickness_by_hash($me,"wedding");
334             }
335           else if($_REQUEST["poverty"] == "yes")
336             {
337               echo "poverty was chosen. Unfortunately this is not implemented yet,".
338                 " so you need to play a normal game... sorry<br />\n";
339               DB_set_sickness_by_hash($me,"poverty");
340             }
341           else if($_REQUEST["nines"] == "yes")
342             {
343               echo "Nines was chosen. If no is playing solo, this game will be canceled.<br />\n";
344               DB_set_sickness_by_hash($me,"nines");
345             }
346         }
347       
348       /* move on to the next stage*/
349       DB_set_hand_status_by_hash($me,'poverty');
350       
351       
352       break;
353     case 'poverty':
354       /* here we need to check if there is a solo or some other form of sickness.
355        * If so, which one counts
356        * set that one in the Game table
357        * tell people about it.
358        */
359       echo "<br />checking if someone else selected solo or nines... wedding and poverty not handled at the moment<br />".
360         " Please click <a href=\"$host?me=$me\">here</a> to finish the setup.<br />";    
361       
362       /* check if everyone has reached this stage */
363       $userids = DB_get_all_userid_by_gameid($gameid);
364       $ok=1;
365       foreach($userids as $user)
366         {
367           $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
368           if($userstat!='poverty' && $userstat!='play')
369             $ok=0;
370         };
371
372       if($ok)
373         {
374           echo "Everyone has finished checking their cards, the game can now start...<br />";
375           /* check what kind of game we are playing */
376           $gametype    = DB_get_gametype_by_gameid($gameid);
377           $startplayer = DB_get_startplayer_by_gameid($gameid);
378           
379           /* nines? */
380           $nines = 0;
381           /* check for nines */
382           foreach($userids as $user)
383             if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'nines')
384               $nines = $user;
385           
386           /* gamestatus == normal, => cancel game */
387           if($nines && $gamestatus == "normal")
388             {
389               /* TODO: set game type to nines to be able to keep statistics? */
390               $message = "Hello, \n\n".
391                 "the game has been canceled because ".DB_get_name_by_userid($nines)." has five or more nines.\n";
392               
393               $userids = DB_get_all_userid_by_gameid($gameid);
394               foreach($userids as $user)
395                 {
396                   $To = DB_get_email_by_userid($user);
397                   mymail($To,$EmailName."game canceled",$message);
398                 }
399               
400               /* delete everything from the dB */
401               DB_cancel_game($me);
402             }
403           
404           /* check players for poverty */
405           $poverty = 0;
406           foreach($userids as $user)
407             {
408               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'poverty')
409                 {
410                   $poverty++;
411                   $name = DB_get_name_by_userid($user);
412                   echo "$name has a Vorbehalt. <br />";
413                 }
414             }
415           /* if gamestatus == normal, set poverty or dpovert (in case two people have poverty) */
416           
417           /* check players for wedding */
418           $wedding = 0;
419           foreach($userids as $user)
420             {
421               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'wedding')
422                 {
423                   $wedding++;
424                   $name = DB_get_name_by_userid($user);
425                   echo "$name has a Vorbehalt. <br />"  ;
426                 }
427             }
428           /* if gamestatus == normal, set wedding  */
429           
430           /* check for solo, output vorbehalt */
431           $solo = 0;
432           foreach($userids as $user)
433             {
434               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'solo')
435                 {
436                   $solo++;
437                   $name = DB_get_name_by_userid($user);
438                   echo "$name has a Vorbehalt. <br />"  ;
439                 }
440             }
441
442           /* finished the setup, go to next stage */
443           DB_set_hand_status_by_hash($me,'play');
444         }
445       else
446         {
447           echo "You need to wait for the others, the game can only start after everyone finished checking their cards.<br />";
448         };
449       
450       /* check if all players are ready to play */
451       $ok=1;
452       foreach($userids as $user)
453         if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
454           $ok=0;
455
456       if($ok)
457         {
458           /* only set this after all poverty, etc. are handled*/
459           DB_set_game_status_by_gameid($gameid,'play');
460         }
461       
462       break;
463     case 'play':
464     case 'gameover': 
465       /* both entries here,  so that the tricks are visible for both.
466        * in case of 'play' there is a break later that skips the last part
467        */
468       
469       /* figure out what kind of game we are playing, 
470        * set the global variables $TRUMP,$DIAMONDS,$HEARTS,$CLUBS,$SPADES
471        * accordingly
472        */
473       
474       $gametype = DB_get_gametype_by_gameid($gameid);
475       $GT = $gametype;
476       if($gametype=="solo")
477         {
478           $gametype = DB_get_solo_by_gameid($gameid);
479           $GT = $gametype." ".$GT;
480         }
481       else
482         $gametype="normal";
483       
484       set_gametype($gametype);
485       
486       /* get some infos about the game */
487       $gamestatus = DB_get_game_status_by_gameid($gameid);
488       
489       /* display useful things in divs */
490       
491       /* display local time */
492       echo "<div class=\"time\">\n Local times:<table>";
493       $users = array();
494       $users = DB_get_all_userid_by_gameid($gameid);
495       foreach($users as $user)
496         {
497           $offset = DB_get_user_timezone($user);
498           $zone   = return_timezone($offset);
499           date_default_timezone_set($zone);
500           $name   = DB_get_name_by_userid($user);
501           
502           echo "<tr> <td>$name</td> <td>".date("Y-m-d H:i:s")."</td></tr>\n";
503         };
504       echo "</table>\n</div>\n";
505       
506       if($gamestatus != 'pre')
507         display_status($GT);
508       
509       /* display links to the users status page */
510       $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
511       $r      = mysql_fetch_array($result,MYSQL_NUM);
512       output_link_to_user_page($r[0],$r[1]);
513       
514       display_news();
515       
516       /* end display useful things*/
517       
518       /* has the game started? No, then just wait here...*/
519       if($gamestatus == 'pre')
520         {
521           echo "you need to wait for the others... <br />";
522           break; /* not sure this works... the idea is that you can 
523                   * only  play a card after everyone is ready to play */
524         }
525       
526       /* display the table and the names */
527       $result = mysql_query("SELECT  User.fullname as name,".
528                             "        Hand.position as position ".
529                             "FROM Hand ".
530                             "LEFT JOIN User ON User.id=Hand.user_id ".
531                             "WHERE Hand.game_id='".$gameid."' ".
532                             "ORDER BY position ASC");
533       
534       echo "<div class=\"table\">\n".
535         "  <img src=\"pics/table.png\" alt=\"table\" />\n";
536       while($r = mysql_fetch_array($result,MYSQL_NUM))
537         {
538           $name = $r[0];
539           $pos  = $r[1];
540           
541           echo " <span class=\"table".($pos-1)."\">$name</span>\n";
542         }
543       echo  "</div>\n";
544       
545       /* get everything relevant to display the tricks */
546       $result = mysql_query("SELECT Hand_Card.card_id as card,".
547                             "       Hand.position as position,".
548                             "       Play.sequence as sequence, ".
549                             "       Trick.id, ".
550                             "       Comment.comment ".
551                             "FROM Trick ".
552                             "LEFT JOIN Play ON Trick.id=Play.trick_id ".
553                             "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
554                             "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
555                             "LEFT JOIN Comment ON Play.id=Comment.play_id ".
556                             "WHERE Trick.game_id='".$gameid."' ".
557                             "ORDER BY Trick.id,sequence ASC");
558       $trickNR = 1;
559       
560       $lasttrick = DB_get_max_trickid($gameid);
561       
562       $play = array(); /* needed to calculate winner later  */
563       $seq  = 1;          
564       $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
565       $firstcard = ""; /* first card in a trick */
566       
567       echo "\n<ul class=\"tricks\">\n";
568       echo "  <li> Hello $myname!   History: </li>\n";
569       
570       while($r = mysql_fetch_array($result,MYSQL_NUM))
571         {
572           $pos     = $r[1];
573           $seq     = $r[2];
574           $trick   = $r[3];
575           $comment = $r[4];
576           
577           /* save card to be able to find the winner of the trick later */
578           $play[$seq] = array("card"=>$r[0],"pos"=>$pos); 
579           
580           if($seq==1)
581             {
582               /* first card in a trick, output some html */
583               if($trick!=$lasttrick)
584                 {
585                   /* start of an old trick? */
586                   echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Trick $trickNR</a>\n".
587                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
588                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
589                 }
590               else if($trick==$lasttrick)
591                 {
592                   /* start of a last trick? */
593                   echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Current Trick</a>\n".
594                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
595                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
596                 };
597               
598               /* remember first card, so that we are able to check, what cards can be played */
599               $firstcard = $r[0];
600             };
601           
602           /* display card */
603           echo "      <div class=\"card".($pos-1)."\">\n";
604           
605           /* display comments */
606           if($comment!="")
607             echo "        <span class=\"comment\">".$comment."</span>\n";
608           
609           echo "        ";
610           display_card($r[0]);
611           
612           echo "      </div>\n"; /* end div card */
613           
614           /* end of trick? */
615           if($seq==4)
616             {
617               $trickNR++;
618               echo "    </div>\n  </li>\n";  /* end div table, end li table */
619             }
620         }
621       
622       if($seq!=4 && $trickNR>1) 
623         echo "    </div>\n  </li>\n";  /* end div table, end li table */
624       
625       echo "</ul>\n";
626       
627       /* whos turn is it? */
628       if($seq==4)
629         {
630           $winner = get_winner($play,$gametype); /* returns the position */
631           $next = $winner;
632           $firstcard = ""; /* new trick, no first card */
633         }
634       else
635         {
636           $next = $pos+1;
637           if($next==5) $next=1;
638         }
639       
640       /* my turn?, display cards as links, ask for comments*/
641       if(DB_get_pos_by_hash($me) == $next)
642         $myturn = 1;
643       else
644         $myturn = 0;
645       
646       /* do we want to play a card? */
647       if(myisset("card") && $myturn)
648         {
649           $card   = $_REQUEST["card"];
650           $handid = DB_get_handid_by_hash($me); 
651           
652           /* check if we have card and that we haven't played it yet*/
653           /* set played in hand_card to true where hand_id and card_id*/
654           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
655                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
656           $r = mysql_fetch_array($result,MYSQL_NUM);
657           $handcardid = $r[0];
658           
659           if($handcardid)
660             {
661               /* mark card as played */
662               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
663                           DB_quote_smart($card));
664               
665               /* get trick id or start new trick */
666               $a = DB_get_current_trickid($gameid);
667               $trickid  = $a[0];
668               $sequence = $a[1];
669               
670               $playid = DB_play_card($trickid,$handcardid,$sequence);
671               
672               /* check for coment */
673               if(myisset("comment"))
674                 {
675                   DB_insert_comment($_REQUEST["comment"],$playid,$myid);
676                 };  
677               
678               /* display played card */
679               echo "<div class=\"card\">";
680               echo " you played  <br />";
681               display_card($card);
682               echo "</div>\n";
683               
684               /*check if we still have cards left, else set status to gameover */
685               if(sizeof(DB_get_hand($me))==0)
686                 {
687                   DB_set_hand_status_by_hash($me,'gameover');
688                   $mystatus='gameover';
689                 }
690               
691               /* if all players are done, set game status to game over, 
692                * get the points of the last trick and send out an email 
693                * to all players
694                */
695               $userids = DB_get_all_userid_by_gameid($gameid);
696               
697               $done=1;
698               foreach($userids as $user)
699                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
700                   $done=0;
701               
702               if($done)
703                 {
704                   DB_set_game_status_by_gameid($gameid,"gameover");
705                   /* get score for last trick 
706                    * all other tricks are handled a few lines further down*/
707                   $play   = DB_get_cards_by_trick($trickid);
708                   $winner = get_winner($play,$gametype); /* returns the position */
709                   /* get points of last trick and save it */
710                   $points = 0;
711                   foreach($play as $card)
712                     $points = $points + card_value($card["card"]);
713                   $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
714                   if($winnerid>0)
715                     mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
716                   else
717                     echo "ERROR during scoring";
718                   
719                   /* email all players */
720                   $result = mysql_query("SELECT fullname, SUM(score) FROM Score".
721                                         " LEFT JOIN Hand ON Hand.id=hand_id".
722                                         " LEFT JOIN User ON Hand.user_id=User.id".
723                                         " WHERE Hand.game_id=$gameid".
724                                         " GROUP BY fullname" );
725                   $message = "The game is over. Thanks for playing :)\n";
726                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
727                     $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
728                   $message .= "\nIf your not in the list above your score is zero...\n";
729                   foreach($userids as $user)
730                     {
731                       $To = DB_get_email_by_userid($user);
732                       mymail($To,$EmailName."game over",$message);
733                     }
734                 }
735               
736               
737               /* email next player */
738               if(DB_get_game_status_by_gameid($gameid)=='play')
739                 {
740                   if($sequence==4)
741                     {
742                       $play   = DB_get_cards_by_trick($trickid);
743                       $winner = get_winner($play,$gametype); /* returns the position */
744                       
745                       /* get points of last trick and save it, last trick is handled 
746                        * a few lines further up  */
747                       $points = 0;
748                       foreach($play as $card)
749                         $points = $points + card_value($card["card"]);
750                       
751                       $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
752                       if($winnerid>0)
753                         mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
754                       else
755                         echo "ERROR during scoring";
756                       
757                       if($debug)
758                         echo "DEBUG: $winner got $points <br />";
759                       
760                       /* who is the next player? */
761                       $next = $winner;
762                     }
763                   else
764                     {
765                       $next = DB_get_pos_by_hash($me)+1;
766                     }
767                   if($next==5) $next=1;
768                   
769                   /* email next player */
770                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
771                   $email     = DB_get_email_by_hash($next_hash);
772                   
773                   $message = "It's your turn  now.\n".
774                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
775                   mymail($email,$EmailName."a card has been played",$message);
776                   
777                   if($debug)
778                     echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
779                       "\"> next player </a> <br />\n";
780                   
781                 }
782             }
783           else
784             {
785               echo "can't find that card?! <br />\n";
786             }
787         }
788       else if(myisset("card") && !$myturn )
789         {
790           echo "please wait until it's your turn! <br />\n";
791         }
792       
793       $mycards = DB_get_hand($me);
794       $mycards = mysort($mycards,$gametype);
795       echo "<div class=\"mycards\">\n";
796       
797       if($myturn && !myisset("card"))
798         {
799           echo "Hello ".$myname.", it's your turn!  <br />\n";
800           echo "Your cards are: <br />\n";
801           echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
802           
803           /* do we have to follow suite? */
804           $followsuit = 0;
805           if(have_suit($mycards,$firstcard))
806             $followsuit = 1;
807           
808           foreach($mycards as $card) 
809             {
810               if($followsuit && !same_type($card,$firstcard))
811                 display_card($card);
812               else
813                 display_link_card($card);
814             }
815           
816           echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
817           echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
818           echo "<input type=\"submit\" value=\"move\" />\n";
819           echo "</form>\n";
820         }
821       else if($mystatus=='play')
822         {
823           echo "Your cards are: <br />\n";
824           foreach($mycards as $card) 
825             display_card($card);
826         }
827       else if($mystatus=='gameover')
828         {
829           $oldcards = DB_get_all_hand($me);
830           $oldcards = mysort($oldcards,$gametype);
831           echo "Your cards were: <br />\n";
832           foreach($oldcards as $card) 
833             display_card($card);
834         }
835       echo "</div>\n";
836       
837       /* check if we need to set status to 'gameover' is done during playing of the card */
838       if($mystatus=='play')
839         break;
840       /* the following happens only when the gamestatus is 'gameover' */
841       /* check if game is over, display results */
842       if(DB_get_game_status_by_gameid($gameid)=='play')
843         {
844           echo "the game is over for you.. other people still need to play though";
845         }
846       else
847         {
848           echo "the game is over now...<br />\n";
849           
850           $result = mysql_query("SELECT fullname, SUM(score) FROM Score".
851                                 " LEFT JOIN Hand ON Hand.id=hand_id".
852                                 " LEFT JOIN User ON Hand.user_id=User.id".
853                                 " WHERE Hand.game_id=$gameid".
854                                 " GROUP BY fullname" );
855           while( $r = mysql_fetch_array($result,MYSQL_NUM))
856             echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />";
857           
858           
859           $session = DB_get_session_by_gameid($gameid);
860           $result  = mysql_query("SELECT id,create_date FROM Game".
861                                  " WHERE session=$session".
862                                  " ORDER BY create_date DESC".
863                                  " LIMIT 1");
864           $r=-1;
865           if($result)
866             $r = mysql_fetch_array($result,MYSQL_NUM);
867           
868           if(!$session || $gameid==$r[0])
869             {
870               /* suggest a new game with the same people in it, just rotated once */
871               $names = DB_get_all_names_by_gameid($gameid);
872               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
873             }
874         }
875       break;
876     default:
877       echo "error in testing the status";
878     }
879   exit();
880  } 
881 /* user status page */ 
882  else if(myisset("email","password"))
883    {
884      /* test id and password, should really be done in one step */
885      $email     = $_REQUEST["email"];
886      $password  = $_REQUEST["password"];
887      
888      if(strlen($password)!=32)
889        $password = md5($password);
890      
891      $ok=1;
892      $uid = DB_get_userid_by_email_and_password($email,$password);
893      if(!$uid)
894        $ok=0;
895      
896      if($ok)
897        {
898          $time = DB_get_user_timestamp($uid);
899          $unixtime =strtotime($time);
900          
901          $offset = DB_get_user_timezone($uid);
902          $zone = return_timezone($offset);
903          date_default_timezone_set($zone);
904          
905          echo "last login: ".date("r",$unixtime)."<br />";
906          
907          DB_update_user_timestamp($uid);
908          
909          echo "<p>these are the games you are playing in:<br />\n";
910          $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
911                                " LEFT JOIN Game On Hand.game_id=Game.id".
912                                " WHERE Hand.user_id='$uid' AND Game.status<>'gameover'" );
913          while( $r = mysql_fetch_array($result,MYSQL_NUM))
914            {
915              echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
916              if(time()-strtotime($r[2]) > 60*60*24*30)
917                echo " The game has been running for over a month.".
918                  " Do you want to cancel it? <a href=\"$host?cancle=1&me=".$r[0]."\">yes</a>".
919                  " (clicking here is final and can't be restored)";
920              echo "<br />";
921            }
922          echo "</p>\n";
923          
924          
925          echo "<p>and these are your games that are already done:<br />Game: \n";
926          $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
927          while( $r = mysql_fetch_array($result,MYSQL_NUM))
928            echo "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>, ";
929          echo "</p>\n";
930          
931          $names = DB_get_all_names();
932          echo "<p>registered players:<br />\n";
933          foreach ($names as $name)
934            echo "$name, \n";
935          echo "</p>\n";
936          
937          echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
938        }
939      else
940        {
941          echo "sorry email and password don't match <br />";
942        }
943      exit();
944    }
945 /* page for registration */
946  else if(myisset("register") )
947    {
948      output_register();
949    }
950 /* new user wants to register */
951  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
952    {
953      $ok=1;
954      if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
955        {
956          echo "please chose another name<br />";
957          $ok=0;
958        }
959      if(DB_get_userid_by_email($_REQUEST["Remail"]))
960        {
961          echo "this email address is already used ?!<br />";
962          $ok=0;
963        }
964      if($ok)
965        {
966          $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
967                         ",".DB_quote_smart($_REQUEST["Remail"]).
968                         ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
969                         ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
970          
971          if($r)
972            echo " added you to the database";
973          else
974            echo " something went wrong";
975        }
976    }
977 /* default login page */
978  else
979    { 
980      output_home_page();
981    }
982
983 output_footer();
984
985 DB_close();
986
987 /*
988  *Local Variables: 
989  *mode: php
990  *mode: hs-minor
991  *End:
992  */
993 ?>
994
995