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