bugfix: names and table show up all the time now;
[e-DoKo.git] / index.php
1 <?php
2 error_reporting(E_ALL);
3
4 include_once("config.php");      
5 include_once("output.php");      /* html output only */
6 include_once("db.php");          /* database only */
7 include_once("functions.php");   /* the rest */
8
9 DB_open();
10
11 output_header();
12
13 /* check if we want to start a new game */
14 if(myisset("new"))
15   output_form_for_new_game();
16
17 /*check if everything is ready to set up a new game */
18 else if( myisset("PlayerA", "PlayerB","PlayerC","PlayerD" ))
19   {
20     $PlayerA = $_REQUEST["PlayerA"];
21     $PlayerB = $_REQUEST["PlayerB"];
22     $PlayerC = $_REQUEST["PlayerC"];
23     $PlayerD = $_REQUEST["PlayerD"];
24     
25     $EmailA  = DB_get_email_by_name($PlayerA);
26     $EmailB  = DB_get_email_by_name($PlayerB);
27     $EmailC  = DB_get_email_by_name($PlayerC);
28     $EmailD  = DB_get_email_by_name($PlayerD);
29     
30     if($EmailA=="" || $EmailB=="" || $EmailC=="" || $EmailD=="")
31       {
32         echo "couldn't find one of the names, please start a new game";
33         exit();
34       }
35     
36     $useridA  = DB_get_userid_by_name($PlayerA);
37     $useridB  = DB_get_userid_by_name($PlayerB);
38     $useridC  = DB_get_userid_by_name($PlayerC);
39     $useridD  = DB_get_userid_by_name($PlayerD);
40     
41     /* create random numbers */
42     $randomNR       = create_array_of_random_numbers();
43     $randomNRstring = join(":",$randomNR);
44     
45     /* create game */
46     $followup = NULL;
47     if(myisset("followup") )
48       {
49         $followup= $_REQUEST["followup"];
50         mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', NULL, NULL,'pre','$followup' ,NULL)");
51       }
52     else
53       mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', NULL, NULL,'pre', NULL ,NULL)");
54     $game_id = mysql_insert_id();
55     
56     /* create hash */
57     $hashA = md5("AGameOfDoko".$game_id.$PlayerA.$EmailA);
58     $hashB = md5("AGameOfDoko".$game_id.$PlayerB.$EmailB);
59     $hashC = md5("AGameOfDoko".$game_id.$PlayerC.$EmailC);
60     $hashD = md5("AGameOfDoko".$game_id.$PlayerD.$EmailD);
61     
62     /* create hands */
63     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridA).
64                 ", ".DB_quote_smart($hashA).", 'start','1',NULL,NULL,NULL,'false','false',NULL)");
65     $hand_idA = mysql_insert_id();                                                             
66     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridB).
67                 ", ".DB_quote_smart($hashB).", 'start','2',NULL,NULL,NULL,'false','false',NULL)");
68     $hand_idB = mysql_insert_id();                                                             
69     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridC).
70                 ", ".DB_quote_smart($hashC).", 'start','3',NULL,NULL,NULL,'false','false',NULL)");
71     $hand_idC = mysql_insert_id();                                                             
72     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridD).
73                 ", ".DB_quote_smart($hashD).", 'start','4',NULL,NULL,NULL,'false','false',NULL)");
74     $hand_idD = mysql_insert_id();
75     
76     /* save cards */
77     for($i=0;$i<12;$i++)
78       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idA', '".$randomNR[$i]."', 'false')");
79     for($i=12;$i<24;$i++)
80       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idB', '".$randomNR[$i]."', 'false')");
81     for($i=24;$i<36;$i++)
82       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idC', '".$randomNR[$i]."', 'false')");
83     for($i=36;$i<48;$i++)
84       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idD', '".$randomNR[$i]."', 'false')");
85
86     /* send out email, TODO: check for error with email */
87     $message = "\n".
88       "you are invited to play a game of DoKo (that is to debug the program ;).\n".
89       "Place comments and bug reports here:\n".
90       "http://wiki.nubati.net/index.php?title=EmailDoko\n\n".
91       "The whole round would consist of the following players:\n".
92       "$PlayerA\n".
93       "$PlayerB\n".
94       "$PlayerC\n".
95       "$PlayerD\n\n".
96       "If you want to join this game, please follow this link:\n\n".
97       " ".$host."?me=";
98     
99     mymail($EmailA,"You are invited to a game of DoKo","Hello $PlayerA,\n".$message.$hashA);
100     mymail($EmailB,"You are invited to a game of DoKo","Hello $PlayerB,\n".$message.$hashB);
101     mymail($EmailC,"You are invited to a game of DoKo","Hello $PlayerC,\n".$message.$hashC);
102     mymail($EmailD,"You are invited to a game of DoKo","Hello $PlayerD,\n".$message.$hashD);
103         
104   }    
105 /* end set up a new game */
106
107 else if(myisset("me"))
108   {
109     /* handle request from one specific player,
110      * the hash is set on a per game base
111      */
112     
113     $me = $_REQUEST["me"];
114
115     /* test for valid ID */
116     $myid = DB_get_userid_by_hash($me);
117     if(!$myid)
118       {
119         echo "Can't find you in the database, please check the url.<br />\n";
120         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
121         exit();
122       }
123     
124     DB_update_user_timestamp($myid);
125
126     /* get some information from the DB */
127     $gameid   = DB_get_gameid_by_hash($me);
128     $myname   = DB_get_name_by_hash($me);
129     $mystatus = DB_get_status_by_hash($me);
130     
131     switch($mystatus)
132       {
133       case 'start':
134         check_want_to_play($me);
135         DB_set_hand_status_by_hash($me,'init');
136         break;
137       case 'init':
138         if( !myisset("in","update") )
139           {
140             DB_set_hand_status_by_hash($me,'start');
141             echo "you need to answer both question";
142           }
143         else
144           {
145             if($_REQUEST["in"] == "no")
146               {
147                 echo "TODO: email everyone that the game has been canceled.<br />";
148                  /*something like need to modify for DB backend
149                  for($i=0;$i<4;$i++)
150                    {
151                      $message = "Hello ".$player[$hash[$i]]["name"].",\n\n".
152                        "the game has been canceled due to the request of one of the players.\n";
153                      mymail($player[$hash[$i]]["email"],"[DoKo-Debug] the game has been canceled",$message); 
154                    }
155                  */
156                 /* delete everything from the dB */
157                 DB_cancel_game($me);
158               }
159             else
160               {
161                 echo "thanks for joining the game... please scroll down";
162                 echo "TODO: make this page nicer<br />";
163                 echo "TODO: set card pref<br />";
164                 
165                 $mycards = DB_get_hand($me);
166                 sort($mycards);
167                 echo "<p class=\"mycards\">your cards are: <br />\n";
168                 foreach($mycards as $card) 
169                   display_card($card);
170                 echo "</p>\n";   
171                 
172                 check_for_sickness($me,$mycards);
173                 
174                 DB_set_hand_status_by_hash($me,'check');
175               }
176            }
177         break;
178         
179       case 'check':
180         echo "no checking at the moment... you need to play a normal game.".
181           " At the moment you need to reload this page to finish the setup.";
182         if(!myisset("solo","wedding","poverty","nines") )
183           {
184             /* all these variables have a pre-selected default,
185              * so we should never get here,
186              * unless a user tries to cheat ;) */
187             echo "something went wrong...please contact the admin.";
188           }
189         else
190           {
191             if( $_REQUEST["solo"]!="No")
192               {
193                 DB_set_solo_by_hash($me,$_REQUEST["solo"]);
194                 DB_set_sickness_by_hash($me,"solo");
195               }
196             else if($_REQUEST["wedding"] == "yes")
197               {
198                 echo "wedding was chosen<br />\n";
199                 DB_set_sickness_by_hash($me,"wedding");
200               }
201             else if($_REQUEST["poverty"] == "yes")
202               {
203                 echo "poverty was chosen<br />\n";
204                 DB_set_sickness_by_hash($me,"poverty");
205               }
206             else if($_REQUEST["nines"] == "yes")
207               {
208                 echo "nines was chosen<br />\n";
209                  DB_set_sickness_by_hash($me,"nines");
210               }
211           }
212         DB_set_hand_status_by_hash($me,'poverty');
213         
214         /* check all players and set game to final result, e.g. solo, wedding, povert, redeal */
215         
216         /* reset solo, etc from players who did say something, but it didn't matter? */
217         break;
218       case 'poverty':
219         /* here we need to check if there is a solo or some other form o sickness.
220          * If so, which one counts
221          * set that one in the Game table, delete other ones form Hand table 
222          * tell people about it.
223          */
224         echo "<br />poverty not handeled at the moment... you need to play a normal game<br />";
225         
226         /* only set this after all poverty, etc. are handeled*/
227         DB_set_hand_status_by_hash($me,'play');
228
229         /* check if the game can start  */
230         $userids = DB_get_all_userid_by_gameid($gameid);
231         $ok=1;
232         foreach($userids as $user)
233           if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
234             $ok=0;
235
236         if($ok)
237           {
238             /* TODO: check what kind of game we are playing */
239             DB_set_game_status_by_gameid($gameid,'play');
240           }
241         
242         break;
243       case 'play':
244       case 'gameover': 
245         /* both entries here,  so that the tricks are visible for both.
246          * in case of 'play' there is a break later that skips the last part
247          */
248
249         /* display useful things in divs */
250         
251         /* display local time */
252         echo "<div class=\"time\">\n Local times:<table>";
253         $users = array();
254         $users = DB_get_all_userid_by_gameid($gameid);
255         foreach($users as $user)
256           {
257             $offset = DB_get_user_timezone($user);
258             $zone   = return_timezone($offset);
259             date_default_timezone_set($zone);
260             $name   = DB_get_name_by_userid($user);
261             
262             echo "<tr> <td>$name</td> <td>".date("Y-m-d H:i:s")."</td></tr>\n";
263           };
264         echo "</table>\n</div>\n";
265
266         display_status();
267
268         /* display links to the users status page */
269         $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
270         $r      = mysql_fetch_array($result,MYSQL_NUM);
271         output_link_to_user_page($r[0],$r[1]);
272           
273         display_news();
274
275         /* end display useful things*/
276
277         /* has the game started? No, then just wait here...*/
278         $gamestatus = DB_get_game_status_by_gameid($gameid);
279         if($gamestatus == 'pre')
280           {
281             echo "you need to wait for the others... <br />";
282             break; /* not sure this works... the idea is that you can 
283                     * only  play a card after everyone is ready to play */
284           }
285         
286         /* display the table and the names */
287         $result = mysql_query("SELECT  User.fullname as name,".
288                               "        Hand.position as position ".
289                               "FROM Hand ".
290                               "LEFT JOIN User ON User.id=Hand.user_id ".
291                               "WHERE Hand.game_id='".$gameid."' ".
292                               "ORDER BY position ASC");
293         
294         echo "<div class=\"table\">\n".
295           "  <img src=\"pics/table.png\" alt=\"table\" />\n";
296         while($r = mysql_fetch_array($result,MYSQL_NUM))
297           {
298             $name = $r[0];
299             $pos  = $r[1];
300             
301             echo " <span class=\"table".($pos-1)."\">$name</span>\n";
302           }
303         echo  "</div>\n";
304         
305         /* get everything relevant to display the tricks */
306         $result = mysql_query("SELECT Hand_Card.card_id as card,".
307                               "       Hand.position as position,".
308                               "       Play.sequence as sequence, ".
309                               "       Trick.id, ".
310                               "       Comment.comment ".
311                               "FROM Trick ".
312                               "LEFT JOIN Play ON Trick.id=Play.trick_id ".
313                               "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
314                               "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
315                               "LEFT JOIN Comment ON Play.id=Comment.play_id ".
316                               "WHERE Trick.game_id='".$gameid."' ".
317                               "ORDER BY Trick.id,sequence ASC");
318         
319         
320         $trickNR = 1;
321         
322         $lasttrick = DB_get_max_trickid($gameid);
323         
324         $play = array(); /* needed to calculate winner later  */
325         $seq  = 1;          
326         $pos  = 0;
327         
328         echo "\n<ul class=\"tricks\">\n";
329         echo "  <li> Hello $myname!   History: </li>\n";
330         
331         while($r = mysql_fetch_array($result,MYSQL_NUM))
332           {
333             $pos     = $r[1];
334             $seq     = $r[2];
335             $trick   = $r[3];
336             $comment = $r[4];
337
338             /* save card to be able to find the winner of the trick later */
339             $play[$pos] = $r[0]; 
340             
341             if($trick!=$lasttrick && $seq==1)
342               {
343                 /* start of an old trick? */
344                 echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Trick $trickNR</a>\n".
345                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
346                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
347               }
348             else if($trick==$lasttrick && $seq==1)
349               {
350                 /* start of a last trick? */
351                 echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Current Trick</a>\n".
352                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
353                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
354               }
355             
356             /* display card */
357             echo "      <div class=\"card".($pos-1)."\">\n";
358             
359             /* display comments */
360             if($comment!="")
361               echo "        <span class=\"comment\">".$comment."</span>\n";
362             
363             echo "        ";
364             display_card($r[0]);
365             
366             echo "      </div>\n"; /* end div card */
367             
368             /* end of trick? */
369             if($seq==4)
370               {
371                 $trickNR++;
372                 echo "    </div>\n  </li>\n";  /* end div table, end li table */
373               }
374           }
375
376         if($seq!=4 && $trickNR>1) 
377           echo "    </div>\n  </li>\n";  /* end div table, end li table */
378         
379         echo "</ul>\n";
380         
381         /* whos turn is it? */
382         if($seq==4)
383           {
384              $winner = get_winner($play,"normal"); /* returns the position */
385              $next = $winner;
386           }
387         else
388           {
389             $next = $pos+1;
390             if($next==5) $next=1;
391           }
392         
393         /* my turn?, display cards as links, ask for comments*/
394         if(DB_get_pos_by_hash($me) == $next)
395           $myturn = 1;
396         else
397           $myturn = 0;
398
399         /* do we want to play a card? */
400         if(myisset("card") && $myturn)
401           {
402             $card   = $_REQUEST["card"];
403             $handid = DB_get_handid_by_hash($me); 
404             
405             /* check if we have card and that we haven't played it yet*/
406             /* set played in hand_card to true where hand_id and card_id*/
407             $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
408                                   "hand_id='$handid' AND card_id=".DB_quote_smart($card));
409             $r = mysql_fetch_array($result,MYSQL_NUM);
410             $handcardid = $r[0];
411             
412             if($handcardid)
413               {
414                 mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".DB_quote_smart($card));
415                 
416                 /* get trick id or start new trick */
417                 $a = DB_get_current_trickid($gameid);
418                 $trickid  = $a[0];
419                 $sequence = $a[1];
420                 
421                 $playid = DB_play_card($trickid,$handcardid,$sequence);
422
423                 /*check for coment */
424                 if(myisset("comment"))
425                   {
426                     DB_insert_comment($_REQUEST["comment"],$playid,$myid);
427                   };  
428
429                 echo "<div class=\"card\">";
430                 echo " you played  <br />";
431                 display_card($card);
432                 echo "</div>\n";
433                 
434
435                 /*check if we still have cards left, else set status to gameover */
436                 if(sizeof(DB_get_hand($me))==0)
437                   {
438                     DB_set_hand_status_by_hash($me,'gameover');
439                     $mystatus='gameover';
440                   }
441                 
442                 /* if all players are done, set game status to game over */
443                 $userids = DB_get_all_userid_by_gameid($gameid);
444                 $done=1;
445                 foreach($userids as $user)
446                   if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
447                     $done=0;
448
449                 if($done)
450                   DB_set_game_status_by_gameid($gameid,"gameover");
451                 
452                 /* email next player */
453                 if(DB_get_game_status_by_gameid($gameid)=='play')
454                   {
455                     if($sequence==4)
456                       {
457                         $play   = DB_get_cards_by_trick($trickid);
458                         $winner = get_winner($play,"normal"); /* returns the position */
459                         $next = $winner;
460                       }
461                     else
462                       {
463                         $next = DB_get_pos_by_hash($me)+1;
464                       }
465                     if($next==5) $next=1;
466
467                     /* email next player */
468                     $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
469                     $email     = DB_get_email_by_hash($next_hash);
470
471                     $message = "It's your turn  now.\n".
472                       "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
473                     mymail($email,"[DoKo-debug] a card has been played",$message);
474                     
475                     if($debug)
476                       echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
477                         "\"> next player </a> <br />\n";
478
479                   }
480               }
481             else
482               {
483                 echo "can't find that card?! <br />\n";
484               }
485           }
486         else if(myisset("card") && !$myturn )
487           {
488             echo "please wait until it's your turn! <br />\n";
489           }
490         
491         $mycards = DB_get_hand($me);
492         sort($mycards);
493         echo "<div class=\"mycards\">\n";
494         
495         if($myturn && !myisset("card"))
496           {
497             echo "Hello ".$myname.", it's your turn!  <br />\n";
498             echo "Your cards are: <br />\n";
499             echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
500             foreach($mycards as $card) 
501               display_link_card($card);
502
503             echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
504             echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
505             echo "<input type=\"submit\" value=\"move\" />\n";
506             echo "</form>\n";
507          }
508         else if($mystatus=='play')
509           {
510             echo "Your cards are: <br />\n";
511             foreach($mycards as $card) 
512               display_card($card);
513           }
514         echo "</div>\n";
515
516         /* check if we need to set status to 'gameover' is done during playing of the card */
517         if($mystatus=='play')
518           break;
519         /* the following happens only when the gamestatus is 'gameover' */
520         /* check if game is over, display results */
521         if(DB_get_game_status_by_gameid($gameid)=='play')
522           {
523             echo "the game is over for you.. other people still need to play though";
524           }
525         else
526           {
527             echo "the game is over now... guess the final score should be displayed here...<br />\n";
528             
529             /* suggest a new game with the same people in it, just rotated once */
530             $names = DB_get_all_names_by_gameid($gameid);
531             output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
532           }
533         break;
534       default:
535         echo "error in testing the status";
536       }
537     exit();
538   } 
539 /* user status page */ 
540     else if(myisset("email","password"))
541   {
542     /* test id and password, should really be done in one step */
543     $email     = $_REQUEST["email"];
544     $password  = $_REQUEST["password"];
545
546     if(strlen($password)!=32)
547       $password = md5($password);
548
549     $ok=1;
550     $uid = DB_get_userid_by_email_and_password($email,$password);
551     if(!$uid)
552       $ok=0;
553
554     if($ok)
555       {
556         $time = DB_get_user_timestamp($uid);
557         $unixtime =strtotime($time);
558         
559         $offset = DB_get_user_timezone($uid);
560         $zone = return_timezone($offset);
561         date_default_timezone_set($zone);
562
563         echo "last login: ".date("r",$unixtime)."<br />";
564
565         DB_update_user_timestamp($uid);
566
567         echo "<p>these are the games you are playing in:<br />\n";
568         $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status<>'gameover'" );
569         while( $r = mysql_fetch_array($result,MYSQL_NUM))
570           echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a><br />";
571         echo "</p>\n";
572
573         $names = DB_get_all_names();
574         echo "<p>registered players:<br />\n";
575         foreach ($names as $name)
576           echo "$name <br />\n";
577         echo "</p>\n";
578
579         echo "<p>Want to start a new game? remember 4 names from the list above and visit ".
580           "<a href=\"".$host."?new\">this page.</a></p>";
581       }
582     else
583       {
584         echo "sorry email and password don't match <br />";
585       }
586     exit();
587   }
588 /* page for registration */
589 else if(myisset("register") )
590   {
591     output_register();
592   }
593 /* new user wants to register */
594  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
595   {
596         $ok=1;
597         if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
598           {
599             echo "please chose another name<br />";
600             $ok=0;
601           }
602         if(DB_get_userid_by_email($_REQUEST["Remail"]))
603           {
604             echo "this email address is already used ?!<br />";
605             $ok=0;
606           }
607         if($ok)
608           {
609             $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
610                       ",".DB_quote_smart($_REQUEST["Remail"]).
611                       ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
612                       ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
613             
614             if($r)
615               echo " added you to the database";
616             else
617               echo " something went wrong";
618           }
619   }
620 /* default login page */
621 else
622   { 
623     output_home_page();
624   }
625
626 output_footer();
627
628 DB_close();
629
630 /*
631  *Local Variables: 
632  *mode: php
633  *mode: hs-minor
634  *End:
635  */
636 ?>
637
638