cbcc2f2f0d699a5c460ea41650065e0b7db621c3
[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" ))
35 {
36   $PlayerA = $_REQUEST["PlayerA"];
37   $PlayerB = $_REQUEST["PlayerB"];
38   $PlayerC = $_REQUEST["PlayerC"];
39   $PlayerD = $_REQUEST["PlayerD"];
40   
41   $EmailA  = DB_get_email_by_name($PlayerA);
42   $EmailB  = DB_get_email_by_name($PlayerB);
43   $EmailC  = DB_get_email_by_name($PlayerC);
44   $EmailD  = DB_get_email_by_name($PlayerD);
45   
46   if($EmailA=="" || $EmailB=="" || $EmailC=="" || $EmailD=="")
47     {
48       echo "couldn't find one of the names, please start a new game";
49       exit();
50     }
51   
52   $useridA  = DB_get_userid_by_name($PlayerA);
53   $useridB  = DB_get_userid_by_name($PlayerB);
54   $useridC  = DB_get_userid_by_name($PlayerC);
55   $useridD  = DB_get_userid_by_name($PlayerD);
56   
57   /* create random numbers */
58   $randomNR       = create_array_of_random_numbers();
59   $randomNRstring = join(":",$randomNR);
60   
61   /* create game */
62   $followup = NULL;
63   if(myisset("followup") )
64     {
65       $followup= $_REQUEST["followup"];
66       mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre','$followup' ,NULL)");
67     }
68   else
69     mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre', NULL ,NULL)");
70   $game_id = mysql_insert_id();
71   
72   /* create hash */
73   $hashA = md5("AGameOfDoko".$game_id.$PlayerA.$EmailA);
74   $hashB = md5("AGameOfDoko".$game_id.$PlayerB.$EmailB);
75   $hashC = md5("AGameOfDoko".$game_id.$PlayerC.$EmailC);
76   $hashD = md5("AGameOfDoko".$game_id.$PlayerD.$EmailD);
77   
78   /* create hands */
79   mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridA).
80               ", ".DB_quote_smart($hashA).", 'start','1',NULL,NULL,NULL,'false','false',NULL)");
81   $hand_idA = mysql_insert_id();                                                               
82   mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridB).
83               ", ".DB_quote_smart($hashB).", 'start','2',NULL,NULL,NULL,'false','false',NULL)");
84   $hand_idB = mysql_insert_id();                                                               
85   mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridC).
86               ", ".DB_quote_smart($hashC).", 'start','3',NULL,NULL,NULL,'false','false',NULL)");
87   $hand_idC = mysql_insert_id();                                                               
88   mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridD).
89               ", ".DB_quote_smart($hashD).", 'start','4',NULL,NULL,NULL,'false','false',NULL)");
90   $hand_idD = mysql_insert_id();
91   
92   /* save cards */
93   for($i=0;$i<12;$i++)
94     mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idA', '".$randomNR[$i]."', 'false')");
95   for($i=12;$i<24;$i++)
96     mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idB', '".$randomNR[$i]."', 'false')");
97   for($i=24;$i<36;$i++)
98     mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idC', '".$randomNR[$i]."', 'false')");
99   for($i=36;$i<48;$i++)
100     mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idD', '".$randomNR[$i]."', 'false')");
101   
102   /* send out email, TODO: check for error with email */
103   $message = "\n".
104     "you are invited to play a game of DoKo (that is to debug the program ;).\n".
105     "Place comments and bug reports here:\n".
106     "http://wiki.nubati.net/index.php?title=EmailDoko\n\n".
107     "The whole round would consist of the following players:\n".
108     "$PlayerA\n".
109     "$PlayerB\n".
110     "$PlayerC\n".
111     "$PlayerD\n\n".
112     "If you want to join this game, please follow this link:\n\n".
113     " ".$host."?me=";
114   
115   mymail($EmailA,"You are invited to a game of DoKo","Hello $PlayerA,\n".$message.$hashA);
116   mymail($EmailB,"You are invited to a game of DoKo","Hello $PlayerB,\n".$message.$hashB);
117   mymail($EmailC,"You are invited to a game of DoKo","Hello $PlayerC,\n".$message.$hashC);
118   mymail($EmailD,"You are invited to a game of DoKo","Hello $PlayerD,\n".$message.$hashD);
119   
120   echo "You started a new game. The emails have been sent out!";    
121 }    /* end set up a new game */
122 else if(myisset("cancle","me"))
123 {
124   $me = $_REQUEST["me"];
125   
126   /* test for valid ID */
127   $myid = DB_get_userid_by_hash($me);
128   if(!$myid)
129     {
130       echo "Can't find you in the database, please check the url.<br />\n";
131       echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
132       exit();
133     }
134   
135   DB_update_user_timestamp($myid);
136   
137   /* get some information from the DB */
138   $gameid   = DB_get_gameid_by_hash($me);
139   $myname   = DB_get_name_by_hash($me);
140   $mystatus = DB_get_status_by_hash($me);
141   $mypos    = DB_get_pos_by_hash($me);
142   
143   /* check if game really is old enough */
144   $result = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
145   $r = mysql_fetch_array($result,MYSQL_NUM);
146   if(time()-strtotime($r[0]) > 60*60*24*30)
147     {
148       $message = "Hello, \n\n".
149         "Game $gameid has been cancled since nothing happend for a while and $myname requested it.\n";
150       
151       $userids = DB_get_all_userid_by_gameid($gameid);
152       foreach($userids as $user)
153         {
154           $To = DB_get_email_by_userid($user);
155           mymail($To,$EmailName."game cancled (timed out)",$message);
156         }
157       
158       /* delete everything from the dB */
159       DB_cancel_game($me);
160       
161       echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
162     }
163   else
164     echo "<p>You need to wait longer before you can cancle a game...</p>\n";
165 }
166 else if(myisset("me"))
167 {
168   /* handle request from one specific player,
169 `  * the hash is set on a per game base
170    */
171   
172   $me = $_REQUEST["me"];
173   
174   /* test for valid ID */
175   $myid = DB_get_userid_by_hash($me);
176   if(!$myid)
177     {
178       echo "Can't find you in the database, please check the url.<br />\n";
179       echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
180       exit();
181     }
182   
183   DB_update_user_timestamp($myid);
184   
185   /* get some information from the DB */
186   $gameid   = DB_get_gameid_by_hash($me);
187   $myname   = DB_get_name_by_hash($me);
188   $mystatus = DB_get_status_by_hash($me);
189   $mypos    = DB_get_pos_by_hash($me);
190   
191   echo "<p class=\"gamenumber\"> Game $gameid </p>\n";
192        
193     switch($mystatus)
194       {
195       case 'start':
196         check_want_to_play($me);
197         DB_set_hand_status_by_hash($me,'init');
198         break;
199       case 'init':
200         if( !myisset("in","update") )
201           {
202             DB_set_hand_status_by_hash($me,'start');
203             echo "you need to answer both question";
204           }
205         else
206           {
207             if($_REQUEST["in"] == "no")
208               {
209                 $message = "Hello, \n\n".
210                   "the game has been canceled due to the request of one of the players.\n";
211                 
212                 $userids = DB_get_all_userid_by_gameid($gameid);
213                 foreach($userids as $user)
214                   {
215                     $To = DB_get_email_by_userid($user);
216                     mymail($To,$EmailName."game cancled",$message);
217                   }
218                 
219                 /* delete everything from the dB */
220                 DB_cancel_game($me);
221               }
222             else
223               {
224                 echo "thanks for joining the game... please scroll down";
225                 echo "TODO: make this page nicer<br />";
226                 echo "TODO: set card pref<br />";
227                 
228                 $mycards = DB_get_hand($me);
229                 sort($mycards);
230                 echo "<p class=\"mycards\">your cards are: <br />\n";
231                 foreach($mycards as $card) 
232                   display_card($card);
233                 echo "</p>\n";   
234                 
235                 check_for_sickness($me,$mycards);
236                 
237                 DB_set_hand_status_by_hash($me,'check');
238               }
239            }
240         break;
241         
242       case 'check':
243         echo "checking if you selected solo or nines...<br />".
244           " if you have a wedding, please send an email to the other players. <br />".
245           " if you have poverty you need to play a normal game,sorry...<br />".
246           " Please click <a href=\"$host?me=$me\">here</a> to finish the setup.<br />";
247         if(!myisset("solo","wedding","poverty","nines") )
248           {
249             /* all these variables have a pre-selected default,
250              * so we should never get here,
251              * unless a user tries to cheat ;) */
252             echo "something went wrong...please contact the admin.";
253           }
254         else
255           {
256             /* check if this sickness needs to be handled first */
257             $gametype    = DB_get_gametype_by_gameid($gameid);
258             $startplayer = DB_get_startplayer_by_gameid($gameid);
259
260             if( $_REQUEST["solo"]!="No")
261               {
262                 DB_set_solo_by_hash($me,$_REQUEST["solo"]);
263                 DB_set_sickness_by_hash($me,"solo");
264                 echo "<br />Seems like you want to play a ".$_REQUEST["solo"]." solo. Got it.<br />\n";
265                 
266                 if($gametype == "solo" && $startplayer<$mypos)
267                   {}/* do nothing */
268                 else
269                   {
270                     /* this solo comes first */
271                     DB_set_gametype_by_gameid($gameid,"solo");
272                     DB_set_startplayer_by_gameid($gameid,$mypos);
273                     DB_set_solo_by_gameid($gameid,$_REQUEST["solo"]);
274                   };
275               }
276             else if($_REQUEST["wedding"] == "yes")
277               {
278                 /* TODO: add silent solo somewhere*/
279                 echo "wedding was chosen<br />\n";
280                 DB_set_sickness_by_hash($me,"wedding");
281               }
282             else if($_REQUEST["poverty"] == "yes")
283               {
284                 echo "poverty was chosen<br />\n";
285                 DB_set_sickness_by_hash($me,"poverty");
286               }
287             else if($_REQUEST["nines"] == "yes")
288               {
289                 echo "nines was chosen<br />\n";
290                  DB_set_sickness_by_hash($me,"nines");
291               }
292           }
293
294         DB_set_hand_status_by_hash($me,'poverty');
295
296         /* check all players and set game to final result, e.g. solo, wedding, povert, redeal */
297
298         break;
299       case 'poverty':
300         /* here we need to check if there is a solo or some other form of sickness.
301          * If so, which one counts
302          * set that one in the Game table, delete other ones form Hand table 
303          * tell people about it.
304          */
305         echo "<br />checking if someone else selected solo or nines... wedding and poverty not handled at the moment<br />".
306           " Please click <a href=\"$host?me=$me\">here</a> to finish the setup.<br />";  
307         
308         /* only set this after all poverty, etc. are handeled*/
309         DB_set_hand_status_by_hash($me,'play');
310
311         /* check if the game can start  */
312         $userids = DB_get_all_userid_by_gameid($gameid);
313         $ok=1;
314         foreach($userids as $user)
315           if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
316             $ok=0;
317
318         if($ok)
319           {
320             DB_set_game_status_by_gameid($gameid,'play');
321
322             /* check what kind of game we are playing */
323             $gametype    = DB_get_gametype_by_gameid($gameid);
324             $startplayer = DB_get_startplayer_by_gameid($gameid);
325
326             /* nines? */
327             $nines = 0;
328             /* check for nines */
329             foreach($userids as $user)
330               {
331                 if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'nines')
332                   $nines = 1;
333               }
334             
335             /* gamestatus == normal, => cancel game */
336             if($nines && $gamestatus == "normal")
337               {
338                 /* TODO: set game type to nines to be able to keep statistics */
339                 
340                 $message = "Hello, \n\n".
341                   "the game has been cancled becausee someone has five or more nines.\n";
342                 
343                 $userids = DB_get_all_userid_by_gameid($gameid);
344                 foreach($userids as $user)
345                   {
346                     $To = DB_get_email_by_userid($user);
347                     mymail($To,$EmailName."game cancled",$message);
348                   }
349                 
350                 /* delete everything from the dB */
351                 DB_cancel_game($me);
352
353               }
354
355             /* poverty? */
356             $poverty = 0;
357
358             /* check players for poverty */
359             foreach($userids as $user)
360               {
361                 if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'poverty')
362                   {
363                     $poverty++;
364                     $name = DB_get_name_by_userid($user);
365                     echo "$name has a Vorbehalt. <br />";
366                   }
367               }
368             /* if gamestatus == normal, set poverty or dpovert (in case two people have poverty) */
369
370             /* wedding? */
371             $wedding = 0;
372             /* check players for wedding */
373             foreach($userids as $user)
374               {
375                 if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'wedding')
376                   {
377                     $wedding++;
378                     $name = DB_get_name_by_userid($user);
379                     echo "$name has a Vorbehalt. <br />"  ;
380                   }
381               }
382
383             /* if gamestatus == normal, set wedding  */
384             
385           }
386         
387         break;
388       case 'play':
389       case 'gameover': 
390         /* both entries here,  so that the tricks are visible for both.
391          * in case of 'play' there is a break later that skips the last part
392          */
393
394         /* figure out what kind of game we are playing, 
395          * set the global variables $TRUMP,$DIAMONDS,$HEARTS,$CLUBS,$SPADES
396          * accordingly
397          */
398         
399         $gametype = DB_get_gametype_by_gameid($gameid);
400         $GT = $gametype;
401         if($gametype=="solo")
402           {
403             $gametype = DB_get_solo_by_gameid($gameid);
404             $GT = $gametype." ".$GT;
405           }
406         else
407           $gametype="normal";
408         
409         set_gametype($gametype);
410
411         /* get some infos about the game */
412         $gamestatus = DB_get_game_status_by_gameid($gameid);
413
414         /* display useful things in divs */
415         
416         /* display local time */
417         echo "<div class=\"time\">\n Local times:<table>";
418         $users = array();
419         $users = DB_get_all_userid_by_gameid($gameid);
420         foreach($users as $user)
421           {
422             $offset = DB_get_user_timezone($user);
423             $zone   = return_timezone($offset);
424             date_default_timezone_set($zone);
425             $name   = DB_get_name_by_userid($user);
426             
427             echo "<tr> <td>$name</td> <td>".date("Y-m-d H:i:s")."</td></tr>\n";
428           };
429         echo "</table>\n</div>\n";
430
431         if($gamestatus != 'pre')
432           display_status($GT);
433
434         /* display links to the users status page */
435         $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
436         $r      = mysql_fetch_array($result,MYSQL_NUM);
437         output_link_to_user_page($r[0],$r[1]);
438           
439         display_news();
440
441         /* end display useful things*/
442
443         /* has the game started? No, then just wait here...*/
444         if($gamestatus == 'pre')
445           {
446             echo "you need to wait for the others... <br />";
447             break; /* not sure this works... the idea is that you can 
448                     * only  play a card after everyone is ready to play */
449           }
450         
451         /* display the table and the names */
452         $result = mysql_query("SELECT  User.fullname as name,".
453                               "        Hand.position as position ".
454                               "FROM Hand ".
455                               "LEFT JOIN User ON User.id=Hand.user_id ".
456                               "WHERE Hand.game_id='".$gameid."' ".
457                               "ORDER BY position ASC");
458         
459         echo "<div class=\"table\">\n".
460           "  <img src=\"pics/table.png\" alt=\"table\" />\n";
461         while($r = mysql_fetch_array($result,MYSQL_NUM))
462           {
463             $name = $r[0];
464             $pos  = $r[1];
465             
466             echo " <span class=\"table".($pos-1)."\">$name</span>\n";
467           }
468         echo  "</div>\n";
469         
470         /* get everything relevant to display the tricks */
471         $result = mysql_query("SELECT Hand_Card.card_id as card,".
472                               "       Hand.position as position,".
473                               "       Play.sequence as sequence, ".
474                               "       Trick.id, ".
475                               "       Comment.comment ".
476                               "FROM Trick ".
477                               "LEFT JOIN Play ON Trick.id=Play.trick_id ".
478                               "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
479                               "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
480                               "LEFT JOIN Comment ON Play.id=Comment.play_id ".
481                               "WHERE Trick.game_id='".$gameid."' ".
482                               "ORDER BY Trick.id,sequence ASC");
483         $trickNR = 1;
484         
485         $lasttrick = DB_get_max_trickid($gameid);
486         
487         $play = array(); /* needed to calculate winner later  */
488         $seq  = 1;          
489         $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
490         $firstcard = ""; /* first card in a trick */
491         
492         echo "\n<ul class=\"tricks\">\n";
493         echo "  <li> Hello $myname!   History: </li>\n";
494         
495         while($r = mysql_fetch_array($result,MYSQL_NUM))
496           {
497             $pos     = $r[1];
498             $seq     = $r[2];
499             $trick   = $r[3];
500             $comment = $r[4];
501
502             /* save card to be able to find the winner of the trick later */
503             $play[$pos] = $r[0]; 
504             
505             if($seq==1)
506               {
507                 /* first card in a trick, output some html */
508                 if($trick!=$lasttrick)
509                   {
510                     /* start of an old trick? */
511                     echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Trick $trickNR</a>\n".
512                       "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
513                       "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
514                   }
515                 else if($trick==$lasttrick)
516                   {
517                     /* start of a last trick? */
518                     echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Current Trick</a>\n".
519                       "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
520                       "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
521                   };
522                 
523                 /* remember first card, so that we are able to check, what cards can be played */
524                 $firstcard = $r[0];
525               };
526             
527             /* display card */
528             echo "      <div class=\"card".($pos-1)."\">\n";
529             
530             /* display comments */
531             if($comment!="")
532               echo "        <span class=\"comment\">".$comment."</span>\n";
533             
534             echo "        ";
535             display_card($r[0]);
536             
537             echo "      </div>\n"; /* end div card */
538             
539             /* end of trick? */
540             if($seq==4)
541               {
542                 $trickNR++;
543                 echo "    </div>\n  </li>\n";  /* end div table, end li table */
544               }
545           }
546
547         if($seq!=4 && $trickNR>1) 
548           echo "    </div>\n  </li>\n";  /* end div table, end li table */
549         
550         echo "</ul>\n";
551         
552         /* whos turn is it? */
553         if($seq==4)
554           {
555              $winner = get_winner($play,$gametype); /* returns the position */
556              $next = $winner;
557              $firstcard = ""; /* new trick, no first card */
558           }
559         else
560           {
561             $next = $pos+1;
562             if($next==5) $next=1;
563           }
564         
565         /* my turn?, display cards as links, ask for comments*/
566         if(DB_get_pos_by_hash($me) == $next)
567           $myturn = 1;
568         else
569           $myturn = 0;
570
571         /* do we want to play a card? */
572         if(myisset("card") && $myturn)
573           {
574             $card   = $_REQUEST["card"];
575             $handid = DB_get_handid_by_hash($me); 
576             
577             /* check if we have card and that we haven't played it yet*/
578             /* set played in hand_card to true where hand_id and card_id*/
579             $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
580                                   "hand_id='$handid' AND card_id=".DB_quote_smart($card));
581             $r = mysql_fetch_array($result,MYSQL_NUM);
582             $handcardid = $r[0];
583             
584             if($handcardid)
585               {
586                 /* mark card as played */
587                 mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
588                             DB_quote_smart($card));
589                 
590                 /* get trick id or start new trick */
591                 $a = DB_get_current_trickid($gameid);
592                 $trickid  = $a[0];
593                 $sequence = $a[1];
594                 
595                 $playid = DB_play_card($trickid,$handcardid,$sequence);
596
597                 /* check for coment */
598                 if(myisset("comment"))
599                   {
600                     DB_insert_comment($_REQUEST["comment"],$playid,$myid);
601                   };  
602
603                 /* display played card */
604                 echo "<div class=\"card\">";
605                 echo " you played  <br />";
606                 display_card($card);
607                 echo "</div>\n";
608
609                 /*check if we still have cards left, else set status to gameover */
610                 if(sizeof(DB_get_hand($me))==0)
611                   {
612                     DB_set_hand_status_by_hash($me,'gameover');
613                     $mystatus='gameover';
614                   }
615                 
616                 /* if all players are done, set game status to game over, 
617                  * get the points of the last trick and send out an email 
618                  * to all players
619                  */
620                 $userids = DB_get_all_userid_by_gameid($gameid);
621
622                 $done=1;
623                 foreach($userids as $user)
624                   if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
625                     $done=0;
626
627                 if($done)
628                   {
629                     DB_set_game_status_by_gameid($gameid,"gameover");
630                     /* get score for last trick 
631                      * all other tricks are handled a few lines further down*/
632                     $play   = DB_get_cards_by_trick($trickid);
633                     $winner = get_winner($play,$gametype); /* returns the position */
634                     /* get points of last trick and save it */
635                     $points = 0;
636                     foreach($play as $card)
637                       $points = $points + card_value($card);
638                     $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
639                     if($winnerid>0)
640                       mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
641                     else
642                       echo "ERROR during scoring";
643
644                     /* email all players */
645                     $result = mysql_query("SELECT fullname, SUM(score) FROM Score".
646                                           " LEFT JOIN Hand ON Hand.id=hand_id".
647                                           " LEFT JOIN User ON Hand.user_id=User.id".
648                                           " WHERE Hand.game_id=$gameid".
649                                           " GROUP BY fullname" );
650                     $message = "The game is over. Thanks for playing :)\n";
651                     while( $r = mysql_fetch_array($result,MYSQL_NUM))
652                       $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
653                     $message .= "\nIf your not in the list above your score is zero...\n";
654                     foreach($userids as $user)
655                       {
656                         $To = DB_get_email_by_userid($user);
657                         mymail($To,$EmailName."game over",$message);
658                       }
659                   }
660                 
661
662                 /* email next player */
663                 if(DB_get_game_status_by_gameid($gameid)=='play')
664                   {
665                     if($sequence==4)
666                       {
667                         $play   = DB_get_cards_by_trick($trickid);
668                         $winner = get_winner($play,$gametype); /* returns the position */
669
670                         /* get points of last trick and save it, last trick is handled 
671                          * a few lines further up  */
672                         $points = 0;
673                         foreach($play as $card)
674                           $points = $points + card_value($card);
675
676                         $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
677                         if($winnerid>0)
678                           mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
679                         else
680                           echo "ERROR during scoring";
681                         
682                         if($debug)
683                           echo "DEBUG: $winner got $points <br />";
684                         
685                         /* who is the next player? */
686                         $next = $winner;
687                       }
688                     else
689                       {
690                         $next = DB_get_pos_by_hash($me)+1;
691                       }
692                     if($next==5) $next=1;
693
694                     /* email next player */
695                     $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
696                     $email     = DB_get_email_by_hash($next_hash);
697
698                     $message = "It's your turn  now.\n".
699                       "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
700                     mymail($email,$EmailName."a card has been played",$message);
701                     
702                     if($debug)
703                       echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
704                         "\"> next player </a> <br />\n";
705
706                   }
707               }
708             else
709               {
710                 echo "can't find that card?! <br />\n";
711               }
712           }
713         else if(myisset("card") && !$myturn )
714           {
715             echo "please wait until it's your turn! <br />\n";
716           }
717         
718         $mycards = DB_get_hand($me);
719         $mycards = mysort($mycards,$gametype);
720         echo "<div class=\"mycards\">\n";
721         
722         if($myturn && !myisset("card"))
723           {
724             echo "Hello ".$myname.", it's your turn!  <br />\n";
725             echo "Your cards are: <br />\n";
726             echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
727
728             /* do we have to follow suite? */
729             $followsuit = 0;
730             if(have_suit($mycards,$firstcard))
731               $followsuit = 1;
732
733             foreach($mycards as $card) 
734               {
735                 if($followsuit && !same_type($card,$firstcard))
736                   display_card($card);
737                 else
738                   display_link_card($card);
739               }
740
741             echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
742             echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
743             echo "<input type=\"submit\" value=\"move\" />\n";
744             echo "</form>\n";
745          }
746         else if($mystatus=='play')
747           {
748             echo "Your cards are: <br />\n";
749             foreach($mycards as $card) 
750               display_card($card);
751           }
752         echo "</div>\n";
753
754         /* check if we need to set status to 'gameover' is done during playing of the card */
755         if($mystatus=='play')
756           break;
757         /* the following happens only when the gamestatus is 'gameover' */
758         /* check if game is over, display results */
759         if(DB_get_game_status_by_gameid($gameid)=='play')
760           {
761             echo "the game is over for you.. other people still need to play though";
762           }
763         else
764           {
765             echo "the game is over now...<br />\n";
766             
767             $result = mysql_query("SELECT fullname, SUM(score) FROM Score".
768                                   " LEFT JOIN Hand ON Hand.id=hand_id".
769                                   " LEFT JOIN User ON Hand.user_id=User.id".
770                                   " WHERE Hand.game_id=$gameid".
771                                   " GROUP BY fullname" );
772             while( $r = mysql_fetch_array($result,MYSQL_NUM))
773               echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />";
774
775             /* suggest a new game with the same people in it, just rotated once */
776             $names = DB_get_all_names_by_gameid($gameid);
777             output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
778           }
779         break;
780       default:
781         echo "error in testing the status";
782       }
783     exit();
784   } 
785 /* user status page */ 
786     else if(myisset("email","password"))
787   {
788     /* test id and password, should really be done in one step */
789     $email     = $_REQUEST["email"];
790     $password  = $_REQUEST["password"];
791
792     if(strlen($password)!=32)
793       $password = md5($password);
794
795     $ok=1;
796     $uid = DB_get_userid_by_email_and_password($email,$password);
797     if(!$uid)
798       $ok=0;
799
800     if($ok)
801       {
802         $time = DB_get_user_timestamp($uid);
803         $unixtime =strtotime($time);
804         
805         $offset = DB_get_user_timezone($uid);
806         $zone = return_timezone($offset);
807         date_default_timezone_set($zone);
808
809         echo "last login: ".date("r",$unixtime)."<br />";
810
811         DB_update_user_timestamp($uid);
812
813         echo "<p>these are the games you are playing in:<br />\n";
814         $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
815                               " LEFT JOIN Game On Hand.game_id=Game.id".
816                               " WHERE Hand.user_id='$uid' AND Game.status<>'gameover'" );
817         while( $r = mysql_fetch_array($result,MYSQL_NUM))
818           {
819             echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
820             if(time()-strtotime($r[2]) > 60*60*24*30)
821                echo " The game has been running for over a month. Do you want to cancel it? <a href=\"$host?cancle=1&me=".$r[0]."\">yes</a> (clicking here is final and can't be restored)";
822             echo "<br />";
823           }
824         echo "</p>\n";
825
826
827         echo "<p>and these are your games that are already done:<br />Game: \n";
828         $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
829         while( $r = mysql_fetch_array($result,MYSQL_NUM))
830           echo "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>, ";
831         echo "</p>\n";
832
833         $names = DB_get_all_names();
834         echo "<p>registered players:<br />\n";
835         foreach ($names as $name)
836           echo "$name, \n";
837         echo "</p>\n";
838
839         echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
840       }
841     else
842       {
843         echo "sorry email and password don't match <br />";
844       }
845     exit();
846   }
847 /* page for registration */
848 else if(myisset("register") )
849   {
850     output_register();
851   }
852 /* new user wants to register */
853  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
854   {
855         $ok=1;
856         if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
857           {
858             echo "please chose another name<br />";
859             $ok=0;
860           }
861         if(DB_get_userid_by_email($_REQUEST["Remail"]))
862           {
863             echo "this email address is already used ?!<br />";
864             $ok=0;
865           }
866         if($ok)
867           {
868             $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
869                       ",".DB_quote_smart($_REQUEST["Remail"]).
870                       ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
871                       ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
872             
873             if($r)
874               echo " added you to the database";
875             else
876               echo " something went wrong";
877           }
878   }
879 /* default login page */
880 else
881   { 
882     output_home_page();
883   }
884
885 output_footer();
886
887 DB_close();
888
889 /*
890  *Local Variables: 
891  *mode: php
892  *mode: hs-minor
893  *End:
894  */
895 ?>
896
897