a0029f091ca82b292c67a5558770aed20af5ddd4
[e-DoKo.git] / index.php
1 <?php
2 error_reporting(E_ALL);
3
4 global $REV;
5 $REV  ="\$Rev$";
6
7 include_once("config.php");      
8 include_once("output.php");      /* html output only */
9 include_once("db.php");          /* database only */
10 include_once("functions.php");   /* the rest */
11
12 /* check if some variables are set in the config file, else set defaults */
13 if(!isset($EmailName))
14      $EmailName="[DoKo] ";
15
16 if(0)
17 {
18   output_header();
19   echo "Working on the database...please check back in a few mintues";
20   output_footer();
21   exit();
22 }
23
24 DB_open();
25 output_header();
26
27 /* check if we want to start a new game */
28 if(myisset("new"))
29   {
30     $names = DB_get_all_names();
31     output_form_for_new_game($names);
32   }
33 /*check if everything is ready to set up a new game */
34  else if( myisset("PlayerA", "PlayerB","PlayerC","PlayerD","dullen","schweinchen" ))
35   {
36     $PlayerA = $_REQUEST["PlayerA"];
37     $PlayerB = $_REQUEST["PlayerB"];
38     $PlayerC = $_REQUEST["PlayerC"];
39     $PlayerD = $_REQUEST["PlayerD"];
40
41     $dullen      = $_REQUEST["dullen"];
42     $schweinchen = $_REQUEST["schweinchen"];
43     
44     $EmailA  = DB_get_email_by_name($PlayerA);
45     $EmailB  = DB_get_email_by_name($PlayerB);
46     $EmailC  = DB_get_email_by_name($PlayerC);
47     $EmailD  = DB_get_email_by_name($PlayerD);
48     
49     if($EmailA=="" || $EmailB=="" || $EmailC=="" || $EmailD=="")
50       {
51         echo "couldn't find one of the names, please start a new game";
52         output_footer();
53         exit();
54       }
55     
56     $useridA  = DB_get_userid_by_name($PlayerA);
57     $useridB  = DB_get_userid_by_name($PlayerB);
58     $useridC  = DB_get_userid_by_name($PlayerC);
59     $useridD  = DB_get_userid_by_name($PlayerD);
60     
61     /* create random numbers */
62     $randomNR       = create_array_of_random_numbers();
63     $randomNRstring = join(":",$randomNR);
64     
65     /* get ruleset information or create new one */
66     $ruleset = DB_get_ruleset($dullen,$schweinchen);
67     if($ruleset <0) 
68       {
69         echo "Error defining ruleset: $ruleset";
70         output_footer();
71         exit();
72       };
73     
74     /* create game */
75     $followup = NULL;
76     if(myisset("followup") )
77       {
78         $followup= $_REQUEST["followup"];
79         $session = DB_get_session_by_gameid($followup);
80         $ruleset = DB_get_ruleset_by_gameid($followup); /* just copy ruleset from old game, 
81                                                          this way no manipulation is possible */
82         if($session)
83           mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre',".
84                       "'$ruleset','$session' ,NULL)");
85         else
86           {
87             /* get max session */
88             $max = DB_get_max_session();
89             $max++;
90             mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre',".
91                         "'$ruleset','$max' ,NULL)");
92             mysql_query("UPDATE Game SET session='".$max."' WHERE id=".DB_quote_smart($followup));
93           }
94       }
95     else
96       mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,'1','pre', ".
97                   "'$ruleset',NULL ,NULL)");
98     $game_id = mysql_insert_id();
99     
100     /* create hash */
101     $hashA = md5("AGameOfDoko".$game_id.$PlayerA.$EmailA);
102     $hashB = md5("AGameOfDoko".$game_id.$PlayerB.$EmailB);
103     $hashC = md5("AGameOfDoko".$game_id.$PlayerC.$EmailC);
104     $hashD = md5("AGameOfDoko".$game_id.$PlayerD.$EmailD);
105     
106     /* create hands */
107     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridA).
108                 ", ".DB_quote_smart($hashA).", 'start','1',NULL,NULL,NULL,'false','false',NULL)");
109     $hand_idA = mysql_insert_id();                                                             
110     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridB).
111                 ", ".DB_quote_smart($hashB).", 'start','2',NULL,NULL,NULL,'false','false',NULL)");
112     $hand_idB = mysql_insert_id();                                                             
113     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridC).
114                 ", ".DB_quote_smart($hashC).", 'start','3',NULL,NULL,NULL,'false','false',NULL)");
115     $hand_idC = mysql_insert_id();                                                             
116     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridD).
117                 ", ".DB_quote_smart($hashD).", 'start','4',NULL,NULL,NULL,'false','false',NULL)");
118     $hand_idD = mysql_insert_id();
119     
120     /* save cards */
121     for($i=0;$i<12;$i++)
122       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idA', '".$randomNR[$i]."', 'false')");
123     for($i=12;$i<24;$i++)
124       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idB', '".$randomNR[$i]."', 'false')");
125     for($i=24;$i<36;$i++)
126       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idC', '".$randomNR[$i]."', 'false')");
127     for($i=36;$i<48;$i++)
128       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idD', '".$randomNR[$i]."', 'false')");
129     
130     /* send out email, TODO: check for error with email */
131     $message = "\n".
132       "you are invited to play a game of DoKo (that is to debug the program ;).\n".
133       "Place comments and bug reports here:\n".
134       "http://wiki.nubati.net/index.php?title=EmailDoko\n\n".
135       "The whole round would consist of the following players:\n".
136       "$PlayerA\n".
137       "$PlayerB\n".
138       "$PlayerC\n".
139       "$PlayerD\n\n".
140       "If you want to join this game, please follow this link:\n\n".
141       " ".$host."?me=";
142     
143     mymail($EmailA,"You are invited to a game of DoKo","Hello $PlayerA,\n".$message.$hashA);
144     mymail($EmailB,"You are invited to a game of DoKo","Hello $PlayerB,\n".$message.$hashB);
145     mymail($EmailC,"You are invited to a game of DoKo","Hello $PlayerC,\n".$message.$hashC);
146     mymail($EmailD,"You are invited to a game of DoKo","Hello $PlayerD,\n".$message.$hashD);
147     
148     echo "You started a new game. The emails have been sent out!";    
149   }    /* end set up a new game */
150 else if(myisset("cancle","me"))
151   {
152     /* cancle a game, if it is older than N minutes */
153     
154     $me = $_REQUEST["me"];
155     
156     /* test for valid ID */
157     $myid = DB_get_userid_by_hash($me);
158     if(!$myid)
159       {
160         echo "Can't find you in the database, please check the url.<br />\n";
161         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
162         output_footer();
163         exit();
164       }
165     
166     DB_update_user_timestamp($myid);
167     
168     /* get some information from the DB */
169     $gameid   = DB_get_gameid_by_hash($me);
170     $myname   = DB_get_name_by_hash($me);
171     
172     /* check if game really is old enough */
173     $result = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
174     $r = mysql_fetch_array($result,MYSQL_NUM);
175     if(time()-strtotime($r[0]) > 60*60*24*30)
176       {
177         $message = "Hello, \n\n".
178           "Game $gameid has been cancled since nothing happend for a while and $myname requested it.\n";
179         
180         $userids = DB_get_all_userid_by_gameid($gameid);
181         foreach($userids as $user)
182           {
183             $To = DB_get_email_by_userid($user);
184             mymail($To,$EmailName."game cancled (timed out)",$message);
185           }
186         
187         /* delete everything from the dB */
188         DB_cancel_game($me);
189         
190         echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
191       }
192     else
193       echo "<p>You need to wait longer before you can cancle a game...</p>\n";
194   }
195 else if(myisset("me"))
196   {
197     /* handle request from one specific player,
198      * the hash is set on a per game base
199      */
200     
201     $me = $_REQUEST["me"];
202     
203     /* test for valid ID */
204     $myid = DB_get_userid_by_hash($me);
205     if(!$myid)
206       {
207         echo "Can't find you in the database, please check the url.<br />\n";
208         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
209         output_footer();
210         exit();
211       }
212     
213     DB_update_user_timestamp($myid);
214     
215     /* get some information from the DB */
216     $gameid   = DB_get_gameid_by_hash($me);
217     $myname   = DB_get_name_by_hash($me);
218     $mystatus = DB_get_status_by_hash($me);
219     $mypos    = DB_get_pos_by_hash($me);
220     
221
222     /* display rule set */
223     echo "<div class=\"ruleset\">\n";
224     $result = mysql_query("SELECT * FROM Rulesets LEFT JOIN Game ON Game.ruleset=Rulesets.id WHERE Game.id='$gameid'" );
225     $r      = mysql_fetch_array($result,MYSQL_NUM);
226
227     $RULES["dullen"]=$r[2];
228     $RULES["schweinchen"]=$r[3];
229     
230     /* get some infos about the game */
231     $gametype = DB_get_gametype_by_gameid($gameid);
232     $gamestatus = DB_get_game_status_by_gameid($gameid);
233     $GT = $gametype;
234     if($gametype=="solo")
235       {
236         $gametype = DB_get_solo_by_gameid($gameid);
237         $GT = $gametype." ".$GT;
238       }
239     else
240       $gametype="normal";
241     
242     if($gamestatus != 'pre')
243       echo " Gametype: $GT <br />\n";
244     
245     echo "Rules: <br />\n";
246     echo "10ofhearts : ".$r[2]."<br />\n";
247     echo "schweinchen: ".$r[3]."<br />\n";
248     echo "</div>\n";
249     
250     /* does anyone have both foxes */
251     $GAME["schweinchen"]=0; 
252     for($i=1;$i<5;$i++)
253       {
254         $hash  = DB_get_hash_from_game_and_pos($gameid,$i);
255         $cards = DB_get_all_hand($hash);
256         if( in_array("19",$cards) && in_array("20",$cards) )
257           {
258             $GAME["schweinchen"]=1;
259             $GAME["schweinchen-who"]=$hash;
260           }
261       };
262
263     /* mystatus gets the player through the different stages of a game.
264      * start:    yes/no
265      * init:     check values from start,
266      *           check for sickness
267      * check:    check for return values from init
268      * poverty:  handle poverty, wait here until all player have reached this state
269      *           display sickness and move on to game
270      * play:     game in progress
271      * gameover: are we revisiting a game
272      */
273     switch($mystatus)
274       {
275       case 'start':
276         check_want_to_play($me);
277         /* move on to the next stage*/
278         DB_set_hand_status_by_hash($me,'init');
279         break;
280       case 'init':
281         if( !myisset("in") )
282           {
283             echo "you need to answer the question";
284             DB_set_hand_status_by_hash($me,'start');
285           }
286         else
287           {
288             if($_REQUEST["in"] == "no")
289               {
290                 /* cancle the game */
291                 $message = "Hello, \n\n".
292                   "the game has been canceled due to the request of one of the players.\n";
293                 
294                 $userids = DB_get_all_userid_by_gameid($gameid);
295                 foreach($userids as $user)
296                   {
297                     $To = DB_get_email_by_userid($user);
298                     mymail($To,$EmailName."game canceled",$message);
299                   }
300                 
301                 /* delete everything from the dB */
302                 DB_cancel_game($me);
303               }
304             else
305               {
306                 echo "thanks for joining the game...";
307                 
308                 $mycards = DB_get_hand($me);
309                 sort($mycards);
310                 echo "<p class=\"mycards\" style=\"margin-top:8em;\">your cards are: <br />\n";
311                 foreach($mycards as $card) 
312                   display_card($card);
313                 echo "</p>\n";   
314                 
315                 check_for_sickness($me,$mycards);
316                 
317                 /* move on to the next stage*/
318                 DB_set_hand_status_by_hash($me,'check');
319               }
320           }
321         break;
322       
323     case 'check':
324       echo "checking if you selected solo or nines...<br />".
325         " Please click <a href=\"$host?me=$me\">here</a> to finish the setup.<br />";
326       if(!myisset("solo","wedding","poverty","nines") )
327         {
328           /* all these variables have a pre-selected default,
329            * so we should never get here,
330            * unless a user tries to cheat ;) */
331           echo "something went wrong...please contact the admin.";
332         }
333       else
334         {
335           /* check if this sickness needs to be handled first */
336           $gametype    = DB_get_gametype_by_gameid($gameid);
337           $startplayer = DB_get_startplayer_by_gameid($gameid);
338           
339           if( $_REQUEST["solo"]!="No")
340             {
341               /* store the info in the user's hand info */
342               DB_set_solo_by_hash($me,$_REQUEST["solo"]);
343               DB_set_sickness_by_hash($me,"solo");
344               echo "<br />Seems like you want to play a ".$_REQUEST["solo"]." solo. Got it.<br />\n";
345               
346               if($gametype == "solo" && $startplayer<$mypos)
347                 {}/* do nothing, since someone else already is playing solo */
348               else
349                 {
350                   /* this solo comes first 
351                    * store info in game table
352                    */
353                   DB_set_gametype_by_gameid($gameid,"solo");
354                   DB_set_startplayer_by_gameid($gameid,$mypos);
355                   DB_set_solo_by_gameid($gameid,$_REQUEST["solo"]);
356                 };
357             }
358           else if($_REQUEST["wedding"] == "yes")
359             {
360               /* TODO: add silent solo somewhere*/
361               echo "Ok, you don't want to play a silent solo...wedding was chosen.<br />\n";
362               DB_set_sickness_by_hash($me,"wedding");
363             }
364           else if($_REQUEST["poverty"] == "yes")
365             {
366               echo "So you got poverty. You might as well have said nothing, since this is not implemented yet,".
367                 " so you need to play a normal game...to make it a bit harder, I'll tell the other people that".
368                 " you only have a few trump... should make the game more interesting (although perhaps not for you:))<br />\n";
369               DB_set_sickness_by_hash($me,"poverty");
370             }
371           else if($_REQUEST["nines"] == "yes")
372             {
373               echo "What you just don't want to play a game because you have a few nines? Well, if no one".
374                 " is playing solo, this game will be canceled.<br />\n";
375               DB_set_sickness_by_hash($me,"nines");
376             }
377         }
378       
379       /* move on to the next stage*/
380       DB_set_hand_status_by_hash($me,'poverty');
381       
382       
383       break;
384     case 'poverty':
385       /* here we need to check if there is a solo or some other form of sickness.
386        * If so, which one counts
387        * set that one in the Game table
388        * tell people about it.
389        */
390       echo "<br />checking if someone else selected solo or nines... poverty not handled at the moment<br />".
391         " Please click <a href=\"$host?me=$me\">here</a> to finish the setup.<br />";    
392       
393       /* check if everyone has reached this stage */
394       $userids = DB_get_all_userid_by_gameid($gameid);
395       $ok=1;
396       foreach($userids as $user)
397         {
398           $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
399           if($userstat!='poverty' && $userstat!='play')
400             $ok=0;
401         };
402
403       if($ok)
404         {
405           echo "Everyone has finished checking their cards, let's see what they said...<br />";
406           /* check what kind of game we are playing */
407           $gametype    = DB_get_gametype_by_gameid($gameid);
408           $startplayer = DB_get_startplayer_by_gameid($gameid);
409           
410           /* nines? */
411           $nines = 0;
412           /* check for nines */
413           foreach($userids as $user)
414             if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'nines')
415               $nines = $user;
416           
417           /* gamestatus == normal, => cancel game */
418           if($nines && $gametype != "solo")
419             {
420               /* TODO: should we keep statistics of this? */
421               $message = "Hello, \n\n".
422                 "the game has been canceled because ".DB_get_name_by_userid($nines)." has five or more nines.\n";
423               
424               $userids = DB_get_all_userid_by_gameid($gameid);
425               foreach($userids as $user)
426                 {
427                   $To = DB_get_email_by_userid($user);
428                   mymail($To,$EmailName."game canceled",$message);
429                 }
430               
431               /* delete everything from the dB */
432               DB_cancel_game($me);
433               output_footer();
434               exit();
435             }
436
437           /* check for different sickness and just output a general info */
438           
439           /* check players for poverty */
440           $poverty = 0;
441           foreach($userids as $user)
442             {
443               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'poverty')
444                 {
445                   $poverty++;
446                   $name = DB_get_name_by_userid($user);
447                   echo "$name has a Vorbehalt. <br />";
448                 }
449             }
450
451           /* check players for wedding */
452           $wedding = 0;
453           foreach($userids as $user)
454             {
455               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'wedding')
456                 {
457                   $wedding=$user;
458                   $name = DB_get_name_by_userid($user);
459                   echo "$name has a Vorbehalt. <br />"  ;
460                 }
461             };
462
463           /* check for solo, output vorbehalt */
464           $solo = 0;
465           foreach($userids as $user)
466             {
467               if(DB_get_sickness_by_userid_and_gameid($user,$gameid) == 'solo')
468                 {
469                   $solo++;
470                   $name = DB_get_name_by_userid($user);
471                   echo "$name has a Vorbehalt. <br />"  ;
472                 }
473             }
474
475           /* now check which sickness comes first and set the gametype to it */
476
477           /* if gamestatus == normal, set poverty or dpovert (in case two people have poverty) */
478           if($poverty>0 && $gametype == "normal")
479             {
480               if($poverty==1)
481                 {
482                   DB_set_gametype_by_gameid($gameid,"poverty");
483                   $gametype = "poverty";
484                 }
485               else if($poverty==2)
486                 {
487                   DB_set_gametype_by_gameid($gameid,"dpoverty");
488                   $gametype = "dpoverty";
489                 };
490             };
491           /* if gamestatus == normal, set wedding  */
492           if($wedding> 0 && $gametype == "normal")
493             {
494               DB_set_gametype_by_gameid($gameid,"wedding");
495               $gametype = "wedding";
496             };
497           
498           /* now the gametype is set correctly (shouldn't matter that this is calculated for every user)
499            * output what kind of game we have */
500           
501           echo "<br />\n";
502
503           $poverty=0;
504           foreach($userids as $user)
505             {
506               $name = DB_get_name_by_userid($user);
507               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
508               if($usersick=="poverty")
509                 $poverty++;
510               if($usersick)
511                 echo "$name has $usersick <br />";
512               if($usersick == "wedding" && $gametype =="wedding")
513                 break;
514               if($usersick == "poverty" && $gametype =="poverty")
515                 break;
516               if($usersick == "poverty" && $gametype =="dpoverty" && $poverty==2)
517                 break;
518               if($usersick == "solo" && $gametype =="solo")
519                 break;
520                           
521             };
522
523           if( $gametype != "solo")
524             if($GAME["schweinchen"] && $RULES["schweinchen"]=="both" )
525               echo DB_get_name_by_hash($GAME["schweinchen-who"])." has Schweinchen. <br />";
526           
527           echo "<br />\n";
528           
529           /* finished the setup, set re/contra parties if possible, go to next stage unless there is a case of poverty*/
530           switch($gametype)
531             {
532             case "solo":
533               /* are we the solo player? set us to re, else set us to contra */
534               $pos = DB_get_pos_by_hash($me);
535               if($pos == $startplayer)
536                 DB_set_party_by_hash($me,"re");
537               else
538                 DB_set_party_by_hash($me,"contra");
539               DB_set_hand_status_by_hash($me,'play');
540               break;
541             case "wedding":
542               echo "Don't know who will be Re and Contra, you need to ".
543                 "figure that out at the end of the game yourself <br />\n";
544               DB_set_hand_status_by_hash($me,'play');
545               break;
546             case "normal":
547               $hand = DB_get_all_hand($me);
548               
549               if(in_array('3',$hand)||in_array('4',$hand))
550                 DB_set_party_by_hash($me,"re");
551               else
552                 DB_set_party_by_hash($me,"contra");
553               DB_set_hand_status_by_hash($me,'play');
554               break;
555             case "poverty":
556               /* figure out who has poverty */
557               /* check who was asked already 
558                *   everyone or trump was taken? 
559                *      trump was taken, start game 
560                *      trump was not taken, cancle game
561                *
562                *   not everyone, figure out who is next in the list
563                *   is the next person this one?
564                *      no, display wait message, e.g. player X is asked at the moment
565                *      yes, display trump, ask if he wants to take it
566                *        no, set player asked to true, email next player
567                *        yes, display all cards, ask for N return cards
568                *          set re/contra 
569                *        
570                */
571             case "dpoverty":
572               echo "TODO: handle double poverty here";
573               DB_set_hand_status_by_hash($me,'play');
574             };
575         }
576       else
577         {
578           echo "You need to wait for the others, the game can only start after everyone finished checking their cards.<br />";
579         };
580       
581       /* check if all players are ready to play */
582       $ok=1;
583       foreach($userids as $user)
584         if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
585           $ok=0;
586
587       if($ok)
588         {
589           /* only set this after all poverty, etc. are handled*/
590           DB_set_game_status_by_gameid($gameid,'play');
591         }
592       
593       break;
594     case 'play':
595     case 'gameover': 
596       /* both entries here,  so that the tricks are visible for both.
597        * in case of 'play' there is a break later that skips the last part
598        */
599       
600       /* figure out what kind of game we are playing, 
601        * set the global variables $CARDS["trump"],$CARDS["diamonds"],$CARDS["hearts"],
602        * $CARDS["clubs"],$CARDS["spades"],$CARDS["foxes"]
603        * accordingly
604        */
605       
606       $gametype = DB_get_gametype_by_gameid($gameid);
607       $GT = $gametype;
608       if($gametype=="solo")
609         {
610           $gametype = DB_get_solo_by_gameid($gameid);
611           $GT = $gametype." ".$GT;
612         }
613       else
614         $gametype="normal";
615       
616       set_gametype($gametype); /* this sets the $CARDS variable */
617       
618       /* get some infos about the game */
619       $gamestatus = DB_get_game_status_by_gameid($gameid);
620       
621       /* display useful things in divs */
622       
623       /* display links to the users status page */
624       $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
625       $r      = mysql_fetch_array($result,MYSQL_NUM);
626       
627       display_links($r[0],$r[1]);
628       
629       /* end display useful things*/
630       
631       /* has the game started? No, then just wait here...*/
632       if($gamestatus == 'pre')
633         {
634           echo "you need to wait for the others... <br />";
635           break; /* not sure this works... the idea is that you can 
636                   * only  play a card after everyone is ready to play */
637         }
638       
639       /* display the table and the names */
640       $result = mysql_query("SELECT  User.fullname as name,".
641                             "        Hand.position as position, ".
642                             "        User.id ".
643                             "FROM Hand ".
644                             "LEFT JOIN User ON User.id=Hand.user_id ".
645                             "WHERE Hand.game_id='".$gameid."' ".
646                             "ORDER BY position ASC");
647       
648       echo "<div class=\"table\">\n".
649         "  <img src=\"pics/table.png\" alt=\"table\" />\n";
650       while($r = mysql_fetch_array($result,MYSQL_NUM))
651         {
652           $name = $r[0];
653           $pos  = $r[1];
654           $user = $r[2];
655
656           $offset = DB_get_user_timezone($user);
657           $zone   = return_timezone($offset);
658           date_default_timezone_set($zone);
659
660           echo " <span class=\"table".($pos-1)."\">\n";
661           echo " $name <br />\n";
662           echo " local time: ".date("Y-m-d H:i:s")."\n";
663           echo " </span>\n";
664
665         }
666       echo  "</div>\n";
667
668       /* get everything relevant to display the tricks */
669       $result = mysql_query("SELECT Hand_Card.card_id as card,".
670                             "       Hand.position as position,".
671                             "       Play.sequence as sequence, ".
672                             "       Trick.id, ".
673                             "       Comment.comment ".
674                             "FROM Trick ".
675                             "LEFT JOIN Play ON Trick.id=Play.trick_id ".
676                             "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
677                             "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
678                             "LEFT JOIN Comment ON Play.id=Comment.play_id ".
679                             "WHERE Trick.game_id='".$gameid."' ".
680                             "ORDER BY Trick.id,sequence ASC");
681       $trickNR = 1;
682       
683       $lasttrick = DB_get_max_trickid($gameid);
684       
685       $play = array(); /* needed to calculate winner later  */
686       $seq  = 1;          
687       $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
688       $firstcard = ""; /* first card in a trick */
689       
690       echo "\n<ul class=\"tricks\">\n";
691       echo "  <li class=\"nohighlight\"> Game $gameid: </li>\n";
692       
693       while($r = mysql_fetch_array($result,MYSQL_NUM))
694         {
695           $pos     = $r[1];
696           $seq     = $r[2];
697           $trick   = $r[3];
698           $comment = $r[4];
699           
700           /* check if first schweinchen has been played */
701           if($r[0] == 19 || $r[0] == 20 )
702             $GAME["schweinchen"]++;
703           
704           /* save card to be able to find the winner of the trick later */
705           $play[$seq] = array("card"=>$r[0],"pos"=>$pos); 
706           
707           if($seq==1)
708             {
709               /* first card in a trick, output some html */
710               if($trick!=$lasttrick)
711                 {
712                   /* start of an old trick? */
713                   echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">Trick $trickNR</a>\n".
714                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
715                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
716                 }
717               else if($trick==$lasttrick)
718                 {
719                   /* start of a last trick? */
720                   echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">Trick $trickNR</a>\n".
721                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
722                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
723                 };
724               
725               /* remember first card, so that we are able to check, what cards can be played */
726               $firstcard = $r[0];
727             };
728           
729           /* display card */
730           echo "      <div class=\"card".($pos-1)."\">\n";
731           
732           /* display comments */
733           if($comment!="")
734             echo "        <span class=\"comment\">".$comment."</span>\n";
735           
736           echo "        ";
737           display_card($r[0]);
738           
739           echo "      </div>\n"; /* end div card */
740           
741           /* end of trick? */
742           if($seq==4)
743             {
744               $trickNR++;
745               echo "    </div>\n  </li>\n";  /* end div table, end li table */
746             }
747         }
748       
749       if($seq!=4 && $trickNR>1) 
750         echo "    </div>\n  </li>\n";  /* end div table, end li table */
751       
752       echo "</ul>\n";
753       
754       /* whos turn is it? */
755       if($seq==4)
756         {
757           $winner = get_winner($play,$gametype); /* returns the position */
758           $next = $winner;
759           $firstcard = ""; /* new trick, no first card */
760         }
761       else
762         {
763           $next = $pos+1;
764           if($next==5) $next=1;
765         }
766       
767       /* my turn?, display cards as links, ask for comments*/
768       if(DB_get_pos_by_hash($me) == $next)
769         $myturn = 1;
770       else
771         $myturn = 0;
772       
773       /* do we want to play a card? */
774       if(myisset("card") && $myturn)
775         {
776           $card   = $_REQUEST["card"];
777           $handid = DB_get_handid_by_hash($me); 
778           
779           /* check if we have card and that we haven't played it yet*/
780           /* set played in hand_card to true where hand_id and card_id*/
781           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
782                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
783           $r = mysql_fetch_array($result,MYSQL_NUM);
784           $handcardid = $r[0];
785           
786           if($handcardid)
787             {
788               $comment = "";
789
790               /* mark card as played */
791               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
792                           DB_quote_smart($card));
793               /* update Game timestamp */
794               DB_update_game_timestamp($gameid);
795
796               /* check for schweinchen */
797               //echo "schweinchen = ".$GAME["schweinchen"]." --$card-<br />";
798               if($card == 19 || $card == 20 )
799                 {
800                   $GAME["schweinchen"]++;
801                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
802                     $comment="Schweinchen! ";
803                   if($RULES["schweinchen"]=="both" )
804                     $comment="Schweinchen! ";
805                   echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
806                 }
807
808               /* get trick id or start new trick */
809               $a = DB_get_current_trickid($gameid);
810               $trickid  = $a[0];
811               $sequence = $a[1];
812               
813               $playid = DB_play_card($trickid,$handcardid,$sequence);
814               
815               /* check for coment */
816               if(myisset("comment"))
817                 {
818                   $comment.=$_REQUEST["comment"];
819                 };  
820               if($comment != "")
821                 DB_insert_comment($comment,$playid,$myid);
822
823               /* display played card */
824               echo "<div class=\"card\">";
825               echo " you played  <br />";
826               display_card($card);
827               echo "</div>\n";
828               
829               /*check if we still have cards left, else set status to gameover */
830               if(sizeof(DB_get_hand($me))==0)
831                 {
832                   DB_set_hand_status_by_hash($me,'gameover');
833                   $mystatus='gameover';
834                 }
835               
836               /* if all players are done, set game status to game over, 
837                * get the points of the last trick and send out an email 
838                * to all players
839                */
840               $userids = DB_get_all_userid_by_gameid($gameid);
841               
842               $done=1;
843               foreach($userids as $user)
844                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
845                   $done=0;
846               
847               if($done)
848                 {
849                   DB_set_game_status_by_gameid($gameid,"gameover");
850                   /* get score for last trick 
851                    * all other tricks are handled a few lines further down*/
852                   $play   = DB_get_cards_by_trick($trickid);
853                   $winner = get_winner($play,$gametype); /* returns the position */
854                   /* get points of last trick and save it */
855                   $points = 0;
856                   foreach($play as $card)
857                     $points = $points + card_value($card["card"]);
858                   $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
859                   if($winnerid>0)
860                     mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
861                   else
862                     echo "ERROR during scoring";
863                   
864                   /* email all players */
865                   /* individual score */
866                   $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
867                                         " LEFT JOIN Hand ON Hand.id=hand_id".
868                                         " LEFT JOIN User ON Hand.user_id=User.id".
869                                         " WHERE Hand.game_id=$gameid".
870                                         " GROUP BY fullname" );
871                   $message = "The game is over. Thanks for playing :)\n";
872                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
873                     $message .= " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."\n";
874                   $message .= "\nIf your not in the list above your score is zero...\n\n";
875
876                   $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
877                                         " LEFT JOIN Hand ON Hand.id=hand_id".
878                                         " LEFT JOIN User ON Hand.user_id=User.id".
879                                         " WHERE Hand.game_id=$gameid".
880                                         " GROUP BY Hand.party" );
881                   $message .= "\n";
882                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
883                     $message .= " FINAL SCORE: ".$r[0]." ".$r[1]."\n";
884
885                   foreach($userids as $user)
886                     {
887                       $To = DB_get_email_by_userid($user);
888                       mymail($To,$EmailName."game over",$message);
889                     }
890                 }
891               
892               
893               /* email next player */
894               if(DB_get_game_status_by_gameid($gameid)=='play')
895                 {
896                   if($sequence==4)
897                     {
898                       $play   = DB_get_cards_by_trick($trickid);
899                       $winner = get_winner($play,$gametype); /* returns the position */
900                       
901                       /* get points of last trick and save it, last trick is handled 
902                        * a few lines further up  */
903                       $points = 0;
904                       foreach($play as $card)
905                         $points = $points + card_value($card["card"]);
906                       
907                       $winnerid = DB_get_handid_by_gameid_and_position($gameid,$winner);
908                       if($winnerid>0)
909                         mysql_query("INSERT INTO Score VALUES (NULL, '$gameid', '$winnerid', '$points')");
910                       else
911                         echo "ERROR during scoring";
912                       
913                       if($debug)
914                         echo "DEBUG: $winner got $points <br />";
915                       
916                       /* who is the next player? */
917                       $next = $winner;
918                     }
919                   else
920                     {
921                       $next = DB_get_pos_by_hash($me)+1;
922                     }
923                   if($next==5) $next=1;
924                   
925                   /* email next player */
926                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
927                   $email     = DB_get_email_by_hash($next_hash);
928                   
929                   $message = "It's your turn  now.\n".
930                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
931                   mymail($email,$EmailName."a card has been played",$message);
932                   
933                   if($debug)
934                     echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
935                       "\"> next player </a> <br />\n";
936                   
937                 }
938             }
939           else
940             {
941               echo "can't find that card?! <br />\n";
942             }
943         }
944       else if(myisset("card") && !$myturn )
945         {
946           echo "please wait until it's your turn! <br />\n";
947         }
948       
949       $mycards = DB_get_hand($me);
950       $mycards = mysort($mycards,$gametype);
951       echo "<div class=\"mycards\">\n";
952       
953       if($myturn && !myisset("card"))
954         {
955           echo "Hello ".$myname.", it's your turn!  <br />\n";
956           echo "Your cards are: <br />\n";
957           echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
958           
959           /* do we have to follow suite? */
960           $followsuit = 0;
961           if(have_suit($mycards,$firstcard))
962             $followsuit = 1;
963           
964           foreach($mycards as $card) 
965             {
966               if($followsuit && !same_type($card,$firstcard))
967                 display_card($card);
968               else
969                 display_link_card($card);
970             }
971           
972           echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
973           echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
974           echo "<input type=\"submit\" value=\"move\" />\n";
975           echo "</form>\n";
976         }
977       else if($mystatus=='play')
978         {
979           echo "Your cards are: <br />\n";
980           foreach($mycards as $card) 
981             display_card($card);
982         }
983       else if($mystatus=='gameover')
984         {
985           $oldcards = DB_get_all_hand($me);
986           $oldcards = mysort($oldcards,$gametype);
987           echo "Your cards were: <br />\n";
988           foreach($oldcards as $card) 
989             display_card($card);
990         }
991       echo "</div>\n";
992       
993       /* check if we need to set status to 'gameover' is done during playing of the card */
994       if($mystatus=='play')
995         break;
996       /* the following happens only when the gamestatus is 'gameover' */
997       /* check if game is over, display results */
998       if(DB_get_game_status_by_gameid($gameid)=='play')
999         {
1000           echo "the game is over for you.. other people still need to play though";
1001         }
1002       else
1003         {
1004           echo "the game is over now...<br />\n";
1005           
1006           $result = mysql_query("SELECT fullname, SUM(score), Hand.party FROM Score".
1007                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1008                                 " LEFT JOIN User ON Hand.user_id=User.id".
1009                                 " WHERE Hand.game_id=$gameid".
1010                                 " GROUP BY fullname" );
1011           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1012             echo " FINAL SCORE: ".$r[0]."(".$r[2].") ".$r[1]."<br />";
1013           
1014           $result = mysql_query("SELECT Hand.party, SUM(score) FROM Score".
1015                                 " LEFT JOIN Hand ON Hand.id=hand_id".
1016                                 " LEFT JOIN User ON Hand.user_id=User.id".
1017                                 " WHERE Hand.game_id=$gameid".
1018                                 " GROUP BY Hand.party" );
1019           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1020             echo " FINAL SCORE: ".$r[0]." ".$r[1]."<br />\n";
1021
1022           
1023           $session = DB_get_session_by_gameid($gameid);
1024           $result  = mysql_query("SELECT id,create_date FROM Game".
1025                                  " WHERE session=$session".
1026                                  " ORDER BY create_date DESC".
1027                                  " LIMIT 1");
1028           $r=-1;
1029           if($result)
1030             $r = mysql_fetch_array($result,MYSQL_NUM);
1031           
1032           if(!$session || $gameid==$r[0])
1033             {
1034               /* suggest a new game with the same people in it, just rotated once */
1035               $names = DB_get_all_names_by_gameid($gameid);
1036               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1037             }
1038         }
1039       break;
1040     default:
1041       echo "error in testing the status";
1042     }
1043     output_footer();
1044   exit();
1045  } 
1046 /* user status page */ 
1047  else if(myisset("email","password"))
1048    {
1049      /* test id and password, should really be done in one step */
1050      $email     = $_REQUEST["email"];
1051      $password  = $_REQUEST["password"];
1052      
1053      if(strlen($password)!=32)
1054        $password = md5($password);
1055      
1056      $ok=1;
1057      $uid = DB_get_userid_by_email_and_password($email,$password);
1058      if(!$uid)
1059        $ok=0;
1060      
1061      if($ok)
1062        {
1063          $time = DB_get_user_timestamp($uid);
1064          $unixtime =strtotime($time);
1065          
1066          $offset = DB_get_user_timezone($uid);
1067          $zone = return_timezone($offset);
1068          date_default_timezone_set($zone);
1069          
1070          echo "last login: ".date("r",$unixtime)."<br />";
1071          
1072          DB_update_user_timestamp($uid);
1073          
1074          echo "<p>these are the games you are playing in:<br />\n";
1075          $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date from Hand".
1076                                " LEFT JOIN Game On Hand.game_id=Game.id".
1077                                " WHERE Hand.user_id='$uid' AND Game.status<>'gameover'" );
1078          while( $r = mysql_fetch_array($result,MYSQL_NUM))
1079            {
1080              echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1081              if(time()-strtotime($r[2]) > 60*60*24*30)
1082                echo " The game has been running for over a month.".
1083                  " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1084                  " (clicking here is final and can't be restored)";
1085              echo "<br />";
1086            }
1087          echo "</p>\n";
1088          
1089          
1090          echo "<p>and these are your games that are already done:<br />Game: \n";
1091          $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
1092          while( $r = mysql_fetch_array($result,MYSQL_NUM))
1093            echo "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>, ";
1094          echo "</p>\n";
1095          
1096          $names = DB_get_all_names();
1097          echo "<p>registered players:<br />\n";
1098          foreach ($names as $name)
1099            echo "$name, \n";
1100          echo "</p>\n";
1101          
1102          echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
1103        }
1104      else
1105        {
1106          echo "sorry email and password don't match <br />";
1107        }
1108      output_footer();
1109      exit();
1110    }
1111 /* page for registration */
1112  else if(myisset("register") )
1113    {
1114      output_register();
1115    }
1116 /* new user wants to register */
1117  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
1118    {
1119      $ok=1;
1120      if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
1121        {
1122          echo "please chose another name<br />";
1123          $ok=0;
1124        }
1125      if(DB_get_userid_by_email($_REQUEST["Remail"]))
1126        {
1127          echo "this email address is already used ?!<br />";
1128          $ok=0;
1129        }
1130      if($ok)
1131        {
1132          $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
1133                         ",".DB_quote_smart($_REQUEST["Remail"]).
1134                         ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
1135                         ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
1136          
1137          if($r)
1138            echo " added you to the database";
1139          else
1140            echo " something went wrong";
1141        }
1142    }
1143 /* default login page */
1144  else
1145    { 
1146      $pre=0;$game=0;$done=0;
1147      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
1148      if($r) {
1149        $pre = mysql_fetch_array($r,MYSQL_NUM);     
1150        $game = mysql_fetch_array($r,MYSQL_NUM);     
1151        $done = mysql_fetch_array($r,MYSQL_NUM);     
1152      }
1153      output_home_page($pre[0],$game[0],$done[0]);
1154    }
1155
1156 output_footer();
1157
1158 DB_close();
1159
1160 /*
1161  *Local Variables: 
1162  *mode: php
1163  *mode: hs-minor
1164  *End:
1165  */
1166 ?>
1167
1168