fixed a lot of bugs, started to work on solos, moved some stuff to output.php
[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           DB_set_game_status_by_gameid($gameid,'play');
238
239         break;
240       case 'play':
241       case 'gameover': 
242         /* both entries here,  so that the tricks are visible for both.
243          * in case of 'play' there is a break later that skips the last part
244          */
245
246         /* display useful things in divs */
247         
248         /* display local time */
249         echo "<div class=\"time\">\n Local times:<table>";
250         $users = array();
251         $users = DB_get_all_userid_by_gameid($gameid);
252         foreach($users as $user)
253           {
254             $offset = DB_get_user_timezone($user);
255             $zone   = return_timezone($offset);
256             date_default_timezone_set($zone);
257             $name   = DB_get_name_by_userid($user);
258             
259             echo "<tr> <td>$name</td> <td>".date("Y-m-d H:i:s")."</td></tr>\n";
260           };
261         echo "</table>\n</div>\n";
262
263         display_status();
264
265         /* display links to the users status page */
266         $result = mysql_query("SELECT email,password from User WHERE id='$myid'" );
267         $r      = mysql_fetch_array($result,MYSQL_NUM);
268         output_link_to_user_page($r[0],$r[1]);
269           
270         display_news();
271
272         /* end display useful things*/
273
274         /* has the game started? No, then just wait here...*/
275         $gamestatus = DB_get_game_status_by_gameid($gameid);
276         if($gamestatus == 'pre')
277           {
278             echo "you need to wait for the others... <br />";
279             break; /* not sure this works... the idea is that you can 
280                     * only  play a card after everyone is ready to play */
281           }
282         
283         /* get everything relevant to display the tricks */
284         $result = mysql_query("SELECT Hand_Card.card_id as card,".
285                               "       User.fullname as name,".
286                               "       Hand.position as position,".
287                               "       Play.sequence as sequence, ".
288                               "       Hand.hash     as hash,     ".
289                               "       Trick.id, ".
290                               "       Comment.comment ".
291                               "FROM Trick ".
292                               "LEFT JOIN Play ON Trick.id=Play.trick_id ".
293                               "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
294                               "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
295                               "LEFT JOIN User ON User.id=Hand.user_id ".
296                               "LEFT JOIN Comment ON Play.id=Comment.play_id ".
297                               "WHERE Trick.game_id='".$gameid."' ".
298                               "ORDER BY Trick.id,sequence ASC");
299         
300         
301         $trickNR = 1;
302         
303         $lasttrick = DB_get_max_trickid($gameid);
304         
305         $play = array(); /* needed to calculate winner later  */
306         $seq  = 1;          
307         $pos  = 0;
308         
309         echo "\n<ul class=\"oldtrick\">\n";
310         echo "  <li> Hello $myname!   History: </li>\n";
311         
312         while($r = mysql_fetch_array($result,MYSQL_NUM))
313           {
314             $seq     = $r[3];
315             $pos     = $r[2];
316             $trick   = $r[5];
317             $comment = $r[6];
318             
319             if($trick!=$lasttrick && $seq==1)
320               {
321                 /* start of an old trick? */
322                 echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Trick $trickNR</a>\n".
323                   "    <div class=\"table\" id=\"trick".$trickNR."\">\n".
324                   "      <img class=\"table\" src=\"pics/table".($pos-1).".png\" alt=\"table\" />\n";
325               }
326             else if($trick==$lasttrick && $seq==1)
327               {
328                 /* start of a last trick? */
329                 echo "  <li onclick=\"hl('$trickNR');\"><a href=\"#\">Current Trick</a>\n".
330                   "    <div class=\"table\" id=\"trick".$trickNR."\">\n".
331                   "      <img class=\"table\" src=\"pics/table".($pos-1).".png\" alt=\"table\" />\n";
332               }
333             
334             /* display card */
335             echo "      <div class=\"card".($pos-1)."\">\n";
336             
337             $play[$pos]=$r[0];
338             
339             if($comment!="")
340               echo "        <span class=\"comment\">";
341             else
342               echo "        <span>";
343             
344             /* print name */
345             echo $r[1];
346             
347             /* check for comment */
348             if($comment!="")
349               echo "<span>".$comment."</span>";
350             echo "</span>\n        ";
351             
352             display_card($r[0]);
353             
354             echo "      </div>\n"; /* end div card */
355             
356             /* end of trick? */
357             if($seq==4)
358               {
359                 $trickNR++;
360                 echo "    </div>\n  </li>\n";  /* end div table, end li table */
361               }
362           }
363
364         if($seq!=4 && $trickNR>1) 
365           echo "    </div>\n  </li>\n";  /* end div table, end li table */
366         
367         echo "</ul>\n";
368         
369         /* whos turn is it? */
370         if($seq==4)
371           {
372              $winner = get_winner($play,"normal"); /* returns the position */
373              $next = $winner;
374           }
375         else
376           {
377             $next = $pos+1;
378           }
379         if($next==5) $next=1;
380         
381         /* my turn?, display cards as links, ask for comments*/
382         if(DB_get_pos_by_hash($me) == $next)
383           $myturn = 1;
384         else
385           $myturn = 0;
386
387         /* do we want to play a card? */
388         if(myisset("card") && $myturn)
389           {
390             $card   = $_REQUEST["card"];
391             $handid = DB_get_handid_by_hash($me); 
392             
393             /* check if we have card and that we haven't played it yet*/
394             /* set played in hand_card to true where hand_id and card_id*/
395             $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
396                                   "hand_id='$handid' AND card_id=".DB_quote_smart($card));
397             $r = mysql_fetch_array($result,MYSQL_NUM);
398             $handcardid = $r[0];
399             
400             if($handcardid)
401               {
402                 mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".DB_quote_smart($card));
403                 
404                 /* get trick id or start new trick */
405                 $a = DB_get_current_trickid($gameid);
406                 $trickid  = $a[0];
407                 $sequence = $a[1];
408                 
409                 $playid = DB_play_card($trickid,$handcardid,$sequence);
410
411                 /*check for coment */
412                 if(myisset("comment"))
413                   {
414                     DB_insert_comment($_REQUEST["comment"],$playid,$myid);
415                   };  
416
417                 echo "<div class=\"card\">";
418                 echo " you played  <br />";
419                 display_card($card);
420                 echo "</div>\n";
421                 
422
423                 /*check if we still have cards left, else set status to gameover */
424                 if(sizeof(DB_get_hand($me))==0)
425                   {
426                     DB_set_hand_status_by_hash($me,'gameover');
427                     $mystatus='gameover';
428                   }
429                 
430                 /* if all players are done, set game status to game over */
431                 $userids = DB_get_all_userid_by_gameid($gameid);
432                 $done=1;
433                 foreach($userids as $user)
434                   if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
435                     $done=0;
436
437                 if($done)
438                   DB_set_game_status_by_gameid($gameid,"gameover");
439                 
440                 /* email next player */
441                 if(DB_get_game_status_by_gameid($gameid)=='play')
442                   {
443                     if($sequence==4)
444                       {
445                         $play   = DB_get_cards_by_trick($trickid);
446                         $winner = get_winner($play,"normal"); /* returns the position */
447                         $next = $winner;
448                       }
449                     else
450                       {
451                         $next = DB_get_pos_by_hash($me)+1;
452                       }
453                     if($next==5) $next=1;
454
455                     /* email next player */
456                     $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
457                     $email     = DB_get_email_by_hash($next_hash);
458
459                     $message = "It's your turn  now.\n".
460                       "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
461                     mymail($email,"[DoKo-debug] a card has been played",$message);
462                     
463                     if($debug)
464                       echo "DEBUG:<a href=\"index.php?me=".DB_get_hash_from_game_and_pos($gameid,$next).
465                         "\"> next player </a> <br />\n";
466
467                   }
468               }
469             else
470               {
471                 echo "couldn't find card <br />\n";
472               }
473           }
474         else if(myisset("card") && !$myturn )
475           {
476             echo "please wait until it is your turn! <br />\n";
477           }
478         
479         $mycards = DB_get_hand($me);
480         sort($mycards);
481         echo "<div class=\"mycards\">\n";
482         
483         if($myturn && !myisset("card"))
484           {
485             echo "Hello ".$myname.", it's your turn!  <br />\n";
486             echo "Your cards are: <br />\n";
487             echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
488             foreach($mycards as $card) 
489               display_link_card($card);
490
491             echo "<br />\nA short comments:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"50\" />\n";
492             echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
493             echo "<input type=\"submit\" value=\"move\" />\n";
494             echo "</form>\n";
495          }
496         else if($mystatus=='play')
497           {
498             echo "Your cards are: <br />\n";
499             foreach($mycards as $card) 
500               display_card($card);
501           }
502         echo "</div>\n";
503
504         /* check if we need to set status to 'gameover' is done during playing of the card */
505         if($mystatus=='play')
506           break;
507         /* the following happens only when the gamestatus is 'gameover' */
508         /* check if game is over, display results */
509         if(DB_get_game_status_by_gameid($gameid)=='play')
510           {
511             echo "the game is over for you.. other people still need to play though";
512           }
513         else
514           {
515             echo "the game is over now... guess the final score should be displayed here...<br />\n";
516             
517             /* suggest a new game with the same people in it, just rotated once */
518             $names = DB_get_all_names_by_gameid($gameid);
519             output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
520           }
521         break;
522       default:
523         echo "error in testing the status";
524       }
525     exit();
526   } 
527 /* user status page */ 
528     else if(myisset("email","password"))
529   {
530     /* test id and password, should really be done in one step */
531     $email     = $_REQUEST["email"];
532     $password  = $_REQUEST["password"];
533
534     if(strlen($password)!=32)
535       $password = md5($password);
536
537     $ok=1;
538     $uid = DB_get_userid_by_email_and_password($email,$password);
539     if(!$uid)
540       $ok=0;
541
542     if($ok)
543       {
544         $time = DB_get_user_timestamp($uid);
545         $unixtime =strtotime($time);
546         
547         $offset = DB_get_user_timezone($uid);
548         $zone = return_timezone($offset);
549         date_default_timezone_set($zone);
550
551         echo "last login: ".date("r",$unixtime)."<br />";
552
553         DB_update_user_timestamp($uid);
554
555         echo "<p>these are the games you are playing in:<br />\n";
556         $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status<>'gameover'" );
557         while( $r = mysql_fetch_array($result,MYSQL_NUM))
558           echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a><br />";
559         echo "</p>\n";
560
561         $names = DB_get_all_names();
562         echo "<p>registered players:<br />\n";
563         foreach ($names as $name)
564           echo "$name <br />\n";
565         echo "</p>\n";
566
567         echo "<p>Want to start a new game? remember 4 names from the list above and visit ".
568           "<a href=\"".$host."?new\">this page.</a></p>";
569       }
570     else
571       {
572         echo "sorry email and password don't match <br />";
573       }
574     exit();
575   }
576 /* page for registration */
577 else if(myisset("register") )
578   {
579     output_register();
580   }
581 /* new user wants to register */
582  else if(myisset("Rfullname","Remail","Rpassword","Rtimezone") )
583   {
584         $ok=1;
585         if(DB_get_userid_by_name($_REQUEST["Rfullname"]))
586           {
587             echo "please chose another name<br />";
588             $ok=0;
589           }
590         if(DB_get_userid_by_email($_REQUEST["Remail"]))
591           {
592             echo "this email address is already used ?!<br />";
593             $ok=0;
594           }
595         if($ok)
596           {
597             $r=mysql_query("INSERT INTO User VALUES(NULL,".DB_quote_smart($_REQUEST["Rfullname"]).
598                       ",".DB_quote_smart($_REQUEST["Remail"]).
599                       ",".DB_quote_smart(md5($_REQUEST["Rpassword"])).
600                       ",".DB_quote_smart($_REQUEST["Rtimezone"]).",NULL)"); 
601             
602             if($r)
603               echo " added you to the database";
604             else
605               echo " something went wrong";
606           }
607   }
608 /* default login page */
609 else
610   { 
611     output_home_page();
612   }
613
614 output_footer();
615
616 DB_close();
617
618 /*
619  *Local Variables: 
620  *mode: php
621  *mode: hs-minor
622  *End:
623  */
624 ?>
625
626