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