LAYOUT: started work on new layout
[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 config_check();
10
11 if(DB_open()<0)
12   {
13     output_header();
14     echo "Database error, can't connect... Please wait a while and try again. ".
15       "If the problem doesn't go away feel free to contact $ADMIN_NAME at $ADMIN_EMAIL.";
16     output_footer(); 
17     exit(); 
18   }
19
20 /* start a session, if it is not already running */
21 session_start();
22
23 /* done major error checking, output header of HTML page */
24 output_header();
25
26 /* check if we want to start a new game */
27 if(myisset("logout"))
28   {
29     session_unset();
30     session_destroy();
31     $_SESSION = array();
32     echo "you are now logged out!";
33   }
34 else if(myisset("new"))
35   {
36     $names = DB_get_all_names();
37     output_form_for_new_game($names);
38   }
39 /*check if everything is ready to set up a new game */
40  else if( myisset("PlayerA", "PlayerB","PlayerC","PlayerD","dullen","schweinchen","call" ))
41   {
42     $PlayerA = $_REQUEST["PlayerA"];
43     $PlayerB = $_REQUEST["PlayerB"];
44     $PlayerC = $_REQUEST["PlayerC"];
45     $PlayerD = $_REQUEST["PlayerD"];
46
47     $dullen      = $_REQUEST["dullen"];
48     $schweinchen = $_REQUEST["schweinchen"];
49     $call        = $_REQUEST["call"];
50
51     $EmailA  = DB_get_email_by_name($PlayerA);
52     $EmailB  = DB_get_email_by_name($PlayerB);
53     $EmailC  = DB_get_email_by_name($PlayerC);
54     $EmailD  = DB_get_email_by_name($PlayerD);
55     
56     if($EmailA=="" || $EmailB=="" || $EmailC=="" || $EmailD=="")
57       {
58         echo "couldn't find one of the names, please start a new game";
59         output_footer();
60         DB_close();
61         exit();
62       }
63     
64     $useridA  = DB_get_userid_by_name($PlayerA);
65     $useridB  = DB_get_userid_by_name($PlayerB);
66     $useridC  = DB_get_userid_by_name($PlayerC);
67     $useridD  = DB_get_userid_by_name($PlayerD);
68     
69     /* create random numbers */
70     $randomNR       = create_array_of_random_numbers($useridA,$useridB,$useridC,$useridD);
71     $randomNRstring = join(":",$randomNR);
72         
73     /* create game */
74     $followup = NULL;
75     if(myisset("followup") )
76       {
77         $followup= $_REQUEST["followup"];
78         $session = DB_get_session_by_gameid($followup);
79         $ruleset = DB_get_ruleset_by_gameid($followup); /* just copy ruleset from old game, 
80                                                          this way no manipulation is possible */
81         if($session)
82           mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,NULL,'1',NULL,'pre',".
83                       "'$ruleset','$session' ,NULL)");
84         else
85           {
86             /* get max session */
87             $max = DB_get_max_session();
88             $max++;
89             mysql_query("UPDATE Game SET session='".$max."' WHERE id=".DB_quote_smart($followup));
90             mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,NULL,'1',NULL,'pre',".
91                         "'$ruleset','$max' ,NULL)");
92           }
93       }
94     else
95       {
96         /* get ruleset information or create new one */
97         $ruleset = DB_get_ruleset($dullen,$schweinchen,$call);
98         if($ruleset <0) 
99           {
100             myerror("Error defining ruleset: $ruleset");
101             output_footer();
102             DB_close();
103             exit();
104           };
105         
106         mysql_query("INSERT INTO Game VALUES (NULL, NULL, '$randomNRstring', 'normal', NULL,NULL,'1',NULL,'pre', ".
107                   "'$ruleset',NULL ,NULL)");
108       }
109     $game_id = mysql_insert_id();
110     
111     /* create hash */
112     $TIME  = (string) time(); /* to avoid collisions */
113     $hashA = md5("AGameOfDoko".$game_id.$PlayerA.$EmailA.$TIME);
114     $hashB = md5("AGameOfDoko".$game_id.$PlayerB.$EmailB.$TIME);
115     $hashC = md5("AGameOfDoko".$game_id.$PlayerC.$EmailC.$TIME);
116     $hashD = md5("AGameOfDoko".$game_id.$PlayerD.$EmailD.$TIME);
117     
118     /* create hands */
119     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridA).
120                 ", ".DB_quote_smart($hashA).", 'start','1',NULL,NULL,NULL,NULL)");
121     $hand_idA = mysql_insert_id();                                                             
122     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridB).
123                 ", ".DB_quote_smart($hashB).", 'start','2',NULL,NULL,NULL,NULL)");
124     $hand_idB = mysql_insert_id();                                                             
125     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridC).
126                 ", ".DB_quote_smart($hashC).", 'start','3',NULL,NULL,NULL,NULL)");
127     $hand_idC = mysql_insert_id();                                                             
128     mysql_query("INSERT INTO Hand VALUES (NULL,".DB_quote_smart($game_id).",".DB_quote_smart($useridD).
129                 ", ".DB_quote_smart($hashD).", 'start','4',NULL,NULL,NULL,NULL)");
130     $hand_idD = mysql_insert_id();
131     
132     /* save cards */
133     for($i=0;$i<12;$i++)
134       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idA', '".$randomNR[$i]."', 'false')");
135     for($i=12;$i<24;$i++)
136       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idB', '".$randomNR[$i]."', 'false')");
137     for($i=24;$i<36;$i++)
138       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idC', '".$randomNR[$i]."', 'false')");
139     for($i=36;$i<48;$i++)
140       mysql_query("INSERT INTO Hand_Card VALUES (NULL, '$hand_idD', '".$randomNR[$i]."', 'false')");
141     
142     /* send out email, TODO: check for error with email */
143     $message = "\n".
144       "you are invited to play a game of DoKo (that is to debug the program ;).\n".
145       "Place comments and bug reports here:\n".
146       "http://wiki.nubati.net/index.php?title=EmailDoko\n\n".
147       "The whole round would consist of the following players:\n".
148       "$PlayerA\n".
149       "$PlayerB\n".
150       "$PlayerC\n".
151       "$PlayerD\n\n".
152       "If you want to join this game, please follow this link:\n\n".
153       "".$host."?me=";
154     
155     mymail($EmailA,"You are invited to a game of DoKo","Hello $PlayerA,\n".$message.$hashA);
156     mymail($EmailB,"You are invited to a game of DoKo","Hello $PlayerB,\n".$message.$hashB);
157     mymail($EmailC,"You are invited to a game of DoKo","Hello $PlayerC,\n".$message.$hashC);
158     mymail($EmailD,"You are invited to a game of DoKo","Hello $PlayerD,\n".$message.$hashD);
159     
160     echo "You started a new game. The emails have been sent out!";    
161   }    /* end set up a new game */
162 /* cancle a game, if nothing has happend in the last N minutes */
163 else if(myisset("cancle","me"))
164   {
165     $me = $_REQUEST["me"];
166     
167     /* test for valid ID */
168     $myid = DB_get_userid_by_hash($me);
169     if(!$myid)
170       {
171         echo "Can't find you in the database, please check the url.<br />\n";
172         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
173         output_footer();
174         DB_close();
175         exit();
176       }
177     
178     DB_update_user_timestamp($myid);
179     
180     /* get some information from the DB */
181     $gameid   = DB_get_gameid_by_hash($me);
182     $myname   = DB_get_name_by_hash($me);
183
184     /* check if game really is old enough */
185     $result = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
186     $r = mysql_fetch_array($result,MYSQL_NUM);
187     if(time()-strtotime($r[0]) > 60*60*24*30) /* = 1 month */
188       {
189         $message = "Hello, \n\n".
190           "Game $gameid has been cancled since nothing happend for a while and $myname requested it.\n";
191         
192         $userids = DB_get_all_userid_by_gameid($gameid);
193         foreach($userids as $user)
194           {
195             $To = DB_get_email_by_userid($user);
196             mymail($To,$EmailName."game $gameid cancled (timed out)",$message);
197           }
198         
199         /* delete everything from the dB */
200         DB_cancel_game($me);
201         
202         echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
203       }
204     else
205       echo "<p>You need to wait longer before you can cancle a game...</p>\n";
206   }
207 /* handle request from one specific player for one game,
208  * (the hash is set on a per game base) */
209 else if(myisset("me"))
210   {
211     $me = $_REQUEST["me"];
212     
213     /* test for valid ID */
214     $myid = DB_get_userid_by_hash($me);
215     if(!$myid)
216       {
217         echo "Can't find you in the database, please check the url.<br />\n";
218         echo "perhaps the game has been cancled, check by login in <a href=\"$host\">here</a>.";
219         output_footer();
220         DB_close();
221         exit();
222       }
223
224     if(isset($_SESSION["name"]))
225       output_status($_SESSION["name"]);
226
227     /* the user had done something, update the timestamp */
228     DB_update_user_timestamp($myid);
229     
230     /* get some information from the DB */
231     $gameid   = DB_get_gameid_by_hash($me);
232     $myname   = DB_get_name_by_hash($me);
233     $mystatus = DB_get_status_by_hash($me);
234     $mypos    = DB_get_pos_by_hash($me);
235     $myhand   = DB_get_handid_by_hash($me);
236     $session  = DB_get_session_by_gameid($gameid);
237
238     /* get prefs and save them */
239     DB_get_PREF($myid);
240     /* end set pref */
241       
242     /* get rule set for this game */
243     $result = mysql_query("SELECT * FROM Rulesets".
244                           " LEFT JOIN Game ON Game.ruleset=Rulesets.id ".
245                           " WHERE Game.id='$gameid'" );
246     $r      = mysql_fetch_array($result,MYSQL_NUM);
247
248     $RULES["dullen"]      = $r[2];
249     $RULES["schweinchen"] = $r[3];
250     $RULES["call"]        = $r[4];
251
252     /* get some infos about the game */
253     $gametype   = DB_get_gametype_by_gameid($gameid);
254     $gamestatus = DB_get_game_status_by_gameid($gameid);
255     $GT         = $gametype;
256     if($gametype=="solo")
257       {
258         $gametype = DB_get_solo_by_gameid($gameid);
259         $GT  = $gametype." ".$GT;
260       }
261     
262     /* does anyone have both foxes */
263     $GAME["schweinchen"]=0; 
264     for($i=1;$i<5;$i++)
265       {
266         $hash  = DB_get_hash_from_game_and_pos($gameid,$i);
267         $cards = DB_get_all_hand($hash);
268         if( in_array("19",$cards) && in_array("20",$cards) )
269           {
270             $GAME["schweinchen"]=1;
271             $GAME["schweinchen-who"]=$hash;
272           }
273       };
274
275     /* put everyting in a form */
276     echo "<form action=\"index.php?me=$me\" method=\"post\">\n";
277
278     /* output left menu */
279
280     display_user_menu();
281
282     /* output right menu */
283
284       /* display rule set for this game */
285     echo "<div class=\"gameinfo\">\n";
286
287     if($gamestatus != 'pre')
288       echo " Gametype: $GT <br />\n";
289     
290     echo "Rules: <br />\n";
291     echo "10ofhearts : ".$RULES["dullen"]      ."<br />\n";
292     echo "schweinchen: ".$RULES["schweinchen"] ."<br />\n";
293     echo "call:        ".$RULES["call"]        ."<br />\n";
294
295     echo "<hr />\n";
296     if($mystatus == 'play' )
297       {
298         output_form_calls($me);
299         
300         echo "<br />\nA short comment:<input name=\"comment\" type=\"text\" size=\"15\" maxlength=\"100\" />\n";
301         echo "<hr />";
302       }
303
304     echo "<input type=\"submit\" value=\"submit\" />\n";
305
306     echo "</div>\n";
307
308     /* output game */
309
310     /* output extra division in case this game is part of a session */
311     if($session)
312       {
313         echo "<div class=\"session\">\n".
314           "This game is part of session $session: \n";
315         $hashes = DB_get_hashes_by_session($session,$myid);
316         $i = 1;
317         foreach($hashes as $hash)
318           {
319             if($hash == $me)
320               echo "$i ";
321             else 
322               echo "<a href=\"".$host."?me=".$hash."\">$i</a> ";
323             $i++;
324           }
325         echo "</div>\n";
326       }
327       
328     /* display the table and the names */
329     display_table();
330
331     /* mystatus gets the player through the different stages of a game.
332      * start:    yes/no
333      * init:     check values from start,
334      *           check for sickness
335      * check:    check for return values from init
336      * poverty:  handle poverty, wait here until all player have reached this state
337      *           display sickness and move on to game
338      * play:     game in progress
339      * gameover: are we revisiting a game
340      */
341     switch($mystatus)
342       {
343       case 'start':
344         if( !myisset("in") )
345           {
346             output_check_want_to_play($me);
347             break;
348           }
349         else
350           {
351             /* move on to the next stage*/
352             DB_set_hand_status_by_hash($me,'init');
353           }
354       case 'init':
355         /* first check if everything went ok  in the last step
356          * if not, send user back, if yes, check what he did
357          */
358         if( !myisset("in") )
359           {
360             echo "<p> You need to answer the <a href=\"$host?me=$me\">question</a>.</p>";
361             DB_set_hand_status_by_hash($me,'start');
362           }
363         else
364           {
365             if($_REQUEST["in"] == "no")
366               {
367                 /* cancel the game */
368                 $message = "Hello, \n\n".
369                   "the game has been canceled due to the request of one of the players.\n";
370                 
371                 $userids = DB_get_all_userid_by_gameid($gameid);
372                 foreach($userids as $user)
373                   {
374                     $To = DB_get_email_by_userid($user);
375                     mymail($To,$EmailName."game $gameid canceled",$message);
376                   }
377                 
378                 /* delete everything from the dB */
379                 DB_cancel_game($me);
380               }
381             else
382               {
383                 $mycards = DB_get_hand($me);
384                 sort($mycards);
385
386                 output_check_for_sickness($me,$mycards);
387                 
388                 echo "<p class=\"mycards\">your cards are: <br />\n";
389                 foreach($mycards as $card) 
390                   display_card($card,$PREF["cardset"]);
391                 echo "</p>\n";   
392                 
393                 /* move on to the next stage*/
394                 DB_set_hand_status_by_hash($me,'check');
395               }
396           }
397         break;
398
399     case 'check':
400       /* ok, user is in the game, saw his cards and selected his vorbehalt
401        * so first we check what he selected
402        */
403       if(!myisset("solo","wedding","poverty","nines") )
404         {
405           /* all these variables have a pre-selected default,
406            * so we should never get here,
407            * unless a user tries to cheat ;)
408            * can also happen if user reloads the page!
409            */
410           echo "<p> You need to answer the <a href=\"$host?me=$me&in=yes\">questions</a>.</p>";
411           DB_set_hand_status_by_hash($me,'init');
412         }
413       else
414         {
415           echo "Processing what you selected in the last step...<br />";
416       
417           /* check if this sickness needs to be handled first */
418           $gametype    = DB_get_gametype_by_gameid($gameid);
419           $startplayer = DB_get_startplayer_by_gameid($gameid);
420           
421           if( $_REQUEST["solo"]!="No")
422             {
423               /* user wants to play a solo */
424
425               /* store the info in the user's hand info */
426               DB_set_solo_by_hash($me,$_REQUEST["solo"]);
427               DB_set_sickness_by_hash($me,"solo");
428
429               echo "<br />Seems like you want to play a ".$_REQUEST["solo"]." solo. Got it.<br />\n";
430               
431               if($gametype == "solo" && $startplayer<$mypos)
432                 {}/* do nothing, since someone else already is playing solo */
433               else
434                 {
435                   /* this solo comes first 
436                    * store info in game table
437                    */
438                   DB_set_gametype_by_gameid($gameid,"solo");
439                   DB_set_startplayer_by_gameid($gameid,$mypos);
440                   DB_set_solo_by_gameid($gameid,$_REQUEST["solo"]);
441                 };
442             }
443           else if($_REQUEST["wedding"] == "yes")
444             {
445               /* TODO: add silent solo somewhere*/
446               echo "Ok, you don't want to play a silent solo...wedding was chosen.<br />\n";
447               DB_set_sickness_by_hash($me,"wedding");
448             }
449           else if($_REQUEST["poverty"] == "yes")
450             {
451               echo "Don't think you can win with just a few trump...? ok, poverty chosen <br />\n";
452               DB_set_sickness_by_hash($me,"poverty");
453             }
454           else if($_REQUEST["nines"] == "yes")
455             {
456               echo "What? You just don't want to play a game because you have a few nines? Well, if no one".
457                 " is playing solo, this game will be canceled.<br />\n";
458               DB_set_sickness_by_hash($me,"nines");
459             }
460           
461           echo " Ok, done with checking, please go to the <a href=\"$host?me=$me\">next step of the setup</a>.<br />";
462           
463           /* move on to the next stage*/
464           DB_set_hand_status_by_hash($me,'poverty');
465           
466           /* check if everyone has reached this stage, send out email */
467           $userids = DB_get_all_userid_by_gameid($gameid);
468           $ok = 1;
469           foreach($userids as $user)
470             {
471               $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
472               if($userstat!='poverty' && $userstat!='play')
473                 {
474                   $ok = 0;
475                   DB_set_player_by_gameid($gameid,$user);
476                 }
477             };
478           if($ok)
479             {
480               /* reset player = everyone has to do something now */
481               DB_set_player_by_gameid($gameid,NULL);
482               
483               foreach($userids as $user)
484                 {
485                   $To       = DB_get_email_by_userid($user);
486                   $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
487                   if($userhash != $me)
488                     {
489                       $message = "Everyone finish the questionary in game $gameid, ".
490                         "please visit this link now to continue: \n".
491                         " ".$host."?me=".$userhash."\n\n" ;
492                       mymail($To,$EmailName." finished setup in game $gameid",$message);
493                     }
494                 };
495             };
496         };
497
498       break;
499
500     case 'poverty':
501       /* here we need to check if there is a solo or some other form of sickness.
502        * If so, which one is the most important one
503        * set that one in the Game table
504        * tell people about it.
505        */
506       echo "<br /> Checking if someone else selected solo, nines, wedding or poverty.<br />";
507       
508       /* check if everyone has reached this stage */
509       $userids = DB_get_all_userid_by_gameid($gameid);
510       $ok = 1;
511       foreach($userids as $user)
512         {
513           $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
514           if($userstat!='poverty' && $userstat!='play')
515             $ok = 0;
516         };
517
518       if(!$ok)
519         {
520           echo "This step can only be handled after everyone finished the last step. ".
521                "Seems like this is not the case, so you need to wait a bit... ".
522                "you will get an email once that is the case, please use the link in ".
523                "that email to continue the game.<br />";
524         }
525       else
526         {
527           echo "Everyone has finished checking their cards, let's see what they said...<br />";
528
529           /* check what kind of game we are playing,  in case there are any solos this already 
530            *will have the correct information in it */
531           $gametype    = DB_get_gametype_by_gameid($gameid);
532           $startplayer = DB_get_startplayer_by_gameid($gameid);
533
534           /* check for different sickness and just output a general info */
535           $nines   = 0;
536           $poverty = 0;
537           $wedding = 0;
538           $solo    = 0;
539           foreach($userids as $user)
540             {
541               $name     = DB_get_name_by_userid($user);
542               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
543               if($usersick == 'nines')
544                 {
545                   $nines = $user;
546                   echo "$name has a Vorbehalt. <br />";
547                   break;
548                 }
549               else if($usersick == 'poverty')
550                 {
551                   $poverty++;
552                   echo "$name has a Vorbehalt. <br />";
553                 }
554               else if($usersick == 'wedding')
555                 {
556                   $wedding=$user;
557                   echo "$name has a Vorbehalt. <br />"  ;
558                 }
559               else if($usersick == 'solo')
560                 {
561                   $solo++;
562                   echo "$name has a Vorbehalt. <br />"  ;
563                 }
564             }
565
566           /* now check which sickness comes first and set the gametype to it */
567
568           if($gametype == "solo")
569             {
570               /* do nothing */
571             }
572           else if($nines)
573             {
574               /* cancel game */
575               /* TODO: should we keep statistics of this? */
576               $message = "Hello, \n\n".
577                 " the game has been canceled because ".DB_get_name_by_userid($nines).
578                 " has five or more nines and nobody is playing solo.\n\n".
579                 " To redeal either start a new game or, in case the game was part of a tournament, \n".
580                 " go to the last game and use the link at the bottom of the page to redeal.";
581               
582               $userids = DB_get_all_userid_by_gameid($gameid);
583               foreach($userids as $user)
584                 {
585                   $To = DB_get_email_by_userid($user);
586                   mymail($To,$EmailName."game $gameid canceled",$message);
587                 }
588               
589               /* delete everything from the dB */
590               DB_cancel_game($me);
591               
592               echo "The game has been canceled because ".DB_get_name_by_userid($nines).
593                 " has five or more nines and nobody is playing solo.\n";
594               output_footer();
595               DB_close();
596               exit();
597             }
598           else if($poverty==1) /* one person has poverty */
599             {
600               DB_set_gametype_by_gameid($gameid,"poverty");
601               $gametype = "poverty";
602               $who      = DB_get_sickness_by_gameid($gameid);
603               if(!$who)
604                 {
605                   $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
606                   if($firstsick == "poverty")
607                     DB_set_sickness_by_gameid($gameid,2); /* who needs to be asked first */
608                   else
609                     DB_set_sickness_by_gameid($gameid,1); /* who needs to be asked first */
610                 }
611             }
612           else if($poverty==2) /* two people have poverty */
613             {
614               DB_set_gametype_by_gameid($gameid,"dpoverty");
615               $gametype = "dpoverty";
616               $who      = DB_get_sickness_by_gameid($gameid);
617               if(!$who)
618                 {
619                   $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
620                   if($firstsick == "poverty")
621                     {
622                       $seconsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
623                       if($secondsick == "poverty")
624                         DB_set_sickness_by_gameid($gameid,30); /* who needs to be asked first */
625                       else
626                         DB_set_sickness_by_gameid($gameid,20); /* who needs to be asked first */
627                     }
628                   else
629                     DB_set_sickness_by_gameid($gameid,10); /* who needs to be asked first */
630                 }
631             }
632           else if($wedding> 0)
633             {
634               DB_set_gametype_by_gameid($gameid,"wedding");
635               DB_set_sickness_by_gameid($gameid,'-1'); /* wedding not resolved yet */
636               $gametype = "wedding";
637             };
638
639           echo "<br />\n";
640
641           /* now the gametype is set correctly (shouldn't matter that this is calculated for every user)
642            * output what kind of game we have */
643           
644           $poverty = 0;
645           foreach($userids as $user)
646             {
647               /* userids are sorted by position... 
648                * so output whatever the first one has, then whatever the next one has
649                * stop when the sickness is the same as the gametype 
650                */
651               
652               $name     = DB_get_name_by_userid($user);
653               $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
654
655               if($usersick)
656                 echo "$name has $usersick. <br />"; /*TODO: perhaps save this in a string and store in Game? */
657
658               if($usersick=="poverty")
659                 $poverty++;
660               if($usersick == "wedding" && $gametype =="wedding")
661                 break;
662               if($usersick == "poverty" && $gametype =="poverty")
663                 break;
664               if($usersick == "poverty" && $gametype =="dpoverty" && $poverty==2)
665                 break;
666               if($usersick == "solo" && $gametype =="solo")
667                 break;
668             };
669
670           /* output Schweinchen in case the rules need it */
671           if( $gametype != "solo")
672             if($GAME["schweinchen"] && $RULES["schweinchen"]=="both" )
673               echo DB_get_name_by_hash($GAME["schweinchen-who"])." has Schweinchen. <br />";
674           
675           echo "<br />\n";
676           
677           /* finished the setup, set re/contra parties if possible, go to next stage unless there is a case of poverty*/
678           switch($gametype)
679             {
680             case "solo":
681               /* are we the solo player? set us to re, else set us to contra */
682               $pos = DB_get_pos_by_hash($me);
683               if($pos == $startplayer)
684                 DB_set_party_by_hash($me,"re");
685               else
686                 DB_set_party_by_hash($me,"contra");
687               DB_set_hand_status_by_hash($me,'play');
688               break;
689
690             case "wedding":
691               /* set person with the wedding to re, do the rest during the game */
692               $usersick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
693               if($usersick == "wedding")
694                 DB_set_party_by_hash($me,"re");
695               else
696                 DB_set_party_by_hash($me,"contra");
697               
698               echo "Whoever will make the first trick will be on the re team. <br />\n";
699               echo " Ok, the game can start now, please finish <a href=\"$host?me=$me\">the setup</a>.<br />";       
700               DB_set_hand_status_by_hash($me,'play');
701               break;
702
703             case "normal":
704               $hand = DB_get_all_hand($me);
705               
706               if(in_array('3',$hand)||in_array('4',$hand))
707                 DB_set_party_by_hash($me,"re");
708               else
709                 DB_set_party_by_hash($me,"contra");
710               DB_set_hand_status_by_hash($me,'play');
711               break;
712             case "poverty":
713             case "dpoverty":
714               /* check if poverty resolved (e.g. DB.Game who set to NULL)
715                *   yes? =>trump was taken, start game; break; 
716                */
717               $who = DB_get_sickness_by_gameid($gameid);
718               if($who<0)
719                 { /* trump has been taken */
720                   DB_set_hand_status_by_hash($me,'play');
721                   break;
722                 };
723               
724               if($who>9) /*= two people still have trump on the table*/
725                 $add = 10;
726               else
727                 $add = 1;
728
729               /* check if we are being asked now
730                *    no? display wait message, e.g. player X is asked at the moment 
731                */
732               $usersick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
733               if(myisset("trump") && $_REQUEST["trump"]=="no" && ($who==$mypos || $who==$mypos*10))
734                 {
735                   /* user doesn't want to take trump */
736                   /* set next player who needs to be asked */
737                   $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
738                   $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
739                   
740                   if($firstsick=="poverty")
741                     {
742                       if($secondsick=="poverty")
743                         DB_set_sickness_by_gameid($gameid,$who+$add*3);
744                       else
745                         DB_set_sickness_by_gameid($gameid,$who+$add*2);
746                     }
747                   else
748                     DB_set_sickness_by_gameid($gameid,$who+$add);
749
750                   /* email next player */
751                   $who = DB_get_sickness_by_gameid($gameid);
752                   if($who>9) $who = $who/10;
753                   
754                   if($who<=4)
755                     {
756                       $To       = DB_get_email_by_pos_and_gameid($who,$gameid);
757                       $userhash = DB_get_hash_from_game_and_pos($gameid,$who);
758                       DB_set_player_by_gameid($gameid,$who);
759
760                       $message = "Someone has poverty, it's your turn to decide, if you want to take the trump. Please visit:".
761                         " ".$host."?me=".$userhash."\n\n" ;
762                       mymail($To,$EmailName." poverty (game $gameid)",$message);
763                     }
764
765                   /* this user is done */
766                   DB_set_hand_status_by_hash($me,'play');
767                   break;                
768                 }
769               else if(myisset("trump") && !myisset("exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
770                 {
771                   /* user wants to take trump */
772                   $trump = $_REQUEST["trump"];
773
774                   /* get hand id for user $trump */
775                   $userhand = DB_get_handid_by_gameid_and_userid($gameid,$trump);
776                   /* copy trump from player A to B */
777                   $result = mysql_query("UPDATE Hand_Card SET hand_id='$myhand' WHERE hand_id='$userhand' AND card_id<'27'" );
778                   
779                   /* add hidden button with trump in it to get to the next point */
780                   echo "<div class=\"poverty\">\n";
781                   echo "  <input type=\"hidden\" name=\"exchange\" value=\"-1\" />\n";
782                   echo "  <input type=\"hidden\" name=\"trump\" value=\"".$trump."\" />\n";
783                   echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select cards to give back\" />\n";
784                   echo "</div>\n";
785                 }
786               else if(myisset("trump","exchange") && $_REQUEST["trump"]>0 && ($who==$mypos || $who==$mypos*10))
787                 {
788                   $trump    = $_REQUEST["trump"];
789                   $exchange = $_REQUEST["exchange"];
790                   $userhand = DB_get_handid_by_gameid_and_userid($gameid,$trump);
791
792                   /* if exchange is set to a value>0, exchange that card back to user $trump */
793                   if($exchange >0)
794                     {
795                       $result = mysql_query("UPDATE Hand_Card SET hand_id='$userhand'".
796                                             " WHERE hand_id='$myhand' AND card_id='$exchange'" );
797                     };
798                   
799                   /* if number of cards == 12, set status to play for both users */
800                   $result = mysql_query("SELECT COUNT(*) FROM Hand_Card  WHERE hand_id='$myhand'" );
801                   $r      = mysql_fetch_array($result,MYSQL_NUM);
802                   if(!$r)
803                     {
804                       myerror("error in poverty");
805                       die();
806                     };
807                   if($r[0]==12)
808                     {
809                       if($gametype=="poverty" || $who<9)
810                         {
811                           DB_set_sickness_by_gameid($gameid,-1); /* done with poverty */                          
812                         }
813                       else /* reduce poverty count by one, that is go to single digits $who */
814                         {
815                           $add = 1;
816                           $who = $who/10;
817
818                           /* whom to ask next */
819                           $firstsick  = DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
820                           $secondsick = DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
821
822                           if($firstsick!="poverty")
823                             DB_set_sickness_by_gameid($gameid,$who+$add);
824                           else
825                             {
826                               if($secondsick!="poverty")
827                                 DB_set_sickness_by_gameid($gameid,$who+$add*2);
828                               else
829                                 DB_set_sickness_by_gameid($gameid,$who+$add*3);
830                             };
831
832                           /* email next player */
833                           $who = DB_get_sickness_by_gameid($gameid);
834                           if($who<=4)
835                             {
836                               $To       = DB_get_email_by_pos_and_gameid($who,$gameid);
837                               $userhash = DB_get_hash_from_game_and_pos($gameid,$who);
838                               DB_set_player_by_gameid($gameid,$who);
839
840                               $message = "Someone has poverty, it's your turn to decide, ".
841                                          "if you want to take the trump. Please visit:".
842                                          " ".$host."?me=".$userhash."\n\n" ;
843                               mymail($To,$EmailName." poverty (game $gameid)",$message);
844                             }
845                         }
846                       
847                       /* this user is done */
848                       DB_set_hand_status_by_hash($me,'play');
849                       /* and so is his partner */
850                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$trump);
851                       DB_set_hand_status_by_hash($hash,'play');
852
853                       /* set party to re, unless we had dpoverty, in that case check if we need to set re/contra*/
854                       $re_set = 0;
855                       foreach($userids as $user)
856                         {
857                           $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
858                           $party    = DB_get_party_by_hash($userhash);
859                           if($party=="re")
860                             $re_set = 1;
861                         }
862                       if($re_set)
863                         {
864                           DB_set_party_by_hash($me,"contra");
865                           DB_set_party_by_hash($hash,"contra");
866                         }
867                       else
868                         {
869                           foreach($userids as $user)
870                             {
871                               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
872                               if($userhash==$hash||$userhash==$me)
873                                 DB_set_party_by_hash($userhash,"re");
874                               else
875                                 DB_set_party_by_hash($userhash,"contra");
876                             }
877                         }
878
879
880                       break;
881                     }
882                   else
883                     {
884                       /* else show all trump, have lowest card pre-selected, have hidden setting for */
885                       echo "<div class=\"poverty\"> you need to get rid of a few cards</div>\n";
886                       
887                       set_gametype($gametype); /* this sets the $CARDS variable */
888                       $mycards = DB_get_hand($me);
889                       $mycards = mysort($mycards,$gametype);
890
891                       $type="exchange";
892                       echo "<div class=\"mycards\">Your cards are: <br />\n";
893                       foreach($mycards as $card) 
894                         display_link_card($card,$PREF["cardset"],$type);
895                       echo "  <input type=\"hidden\" name=\"trump\" value=\"".$trump."\" />\n";
896                       echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select one card to give back\" />\n";
897                       echo "</div>\n";
898                     }
899                 }
900               else if($who == $mypos || $who == $mypos*10)
901                 {
902                   echo "<div class=\"poverty\">\n";
903                   foreach($userids as $user)
904                     {
905                       $name     = DB_get_name_by_userid($user);
906                       $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
907                       
908                       if($usersick=="poverty")
909                         {
910                           $hash    = DB_get_hash_from_gameid_and_userid($gameid,$user);
911                           $cards   = DB_get_hand($hash);
912                           $nrtrump = count_trump($cards);
913                           /* count trump */
914                           if($nrtrump<4)
915                             echo "Player $name has $nrtrump trump. Do you want to take them?".
916                               "<a href=\"index.php?me=$me&amp;trump=$user\">yes</a> <br />\n";
917                         }
918                     }
919                   echo "<a href=\"index.php?me=$me&amp;trump=no\">No,way I take those trump...</a> <br />\n";
920                   echo "</div>\n";
921                   
922                   echo "Your cards are: <br />\n";
923                   $mycards = DB_get_hand($me);
924                   sort($mycards);
925                   echo "<p class=\"mycards\">your cards are: <br />\n";
926                   foreach($mycards as $card) 
927                     display_card($card,$PREF["cardset"]);
928                   echo "</p>\n";   
929                 }
930               else
931                 {
932                   $mysick = DB_get_sickness_by_userid_and_gameid($myid,$gameid);
933                   if($mysick=="poverty")
934                     echo "The others are asked if they want to take your trump, you have to wait (you'll get an email).";
935                   else
936                     echo "it's not your turn yet to decide if you want to take the trump or not.";
937                 }
938             };
939           /* check if no one wanted to take trump, in that case the gamesickness would be set to 5 or 50 */
940           $who = DB_get_sickness_by_gameid($gameid);
941           if($who==5 || $who==50)
942             {
943               $message = "Hello, \n\n".
944                 "Game $gameid has been cancled since nobody wanted to take the trump.\n";
945               
946               $userids = DB_get_all_userid_by_gameid($gameid);
947               foreach($userids as $user)
948                 {
949                   $To = DB_get_email_by_userid($user);
950                   mymail($To,$EmailName."game $gameid cancled (poverty not resolved)",$message);
951                 }
952               
953               /* delete everything from the dB */
954               DB_cancel_game($me);
955               
956               echo "<p style=\"background-color:red\";>Game $gameid has been cancled.<br /><br /></p>";
957               output_footer();
958               DB_close();
959               exit();
960             }
961           
962           /* check if all players are ready to play */
963           $ok = 1;
964           foreach($userids as $user)
965             if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='play')
966               {
967                 $ok = 0;
968                 DB_set_player_by_gameid($gameid,$user);
969               }
970           
971           if($ok)
972             {
973               /* only set this after all poverty, etc. are handled*/
974               DB_set_game_status_by_gameid($gameid,'play');
975               
976               /* email startplayer */
977               $startplayer = DB_get_startplayer_by_gameid($gameid);
978               $email       = DB_get_email_by_pos_and_gameid($startplayer,$gameid);
979               $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
980               $who         = DB_get_userid_by_email($email);
981               DB_set_player_by_gameid($gameid,$who);
982               
983               if($hash!=$me)
984                 {
985                   /* email startplayer) */
986                   $message = "It's your turn now in game $gameid.\n".
987                     "Use this link to play a card: ".$host."?me=".$hash."\n\n" ;
988                   mymail($email,$EmailName."ready, set, go... (game $gameid) ",$message);
989                 }
990               else
991                 echo " Please, <a href=\"$host?me=$me\">start</a> the game.<br />";      
992             }
993           else
994             echo "\n <br />";    
995         }
996       break;
997     case 'play':
998     case 'gameover': 
999       /* both entries here,  so that the tricks are visible for both.
1000        * in case of 'play' there is a break later that skips the last part
1001        */
1002       
1003       /* figure out what kind of game we are playing, 
1004        * set the global variables $CARDS["trump"],$CARDS["diamonds"],$CARDS["hearts"],
1005        * $CARDS["clubs"],$CARDS["spades"],$CARDS["foxes"]
1006        * accordingly
1007        */
1008       
1009       $gametype = DB_get_gametype_by_gameid($gameid);
1010       $GT       = $gametype;
1011       if($gametype=="solo")
1012         {
1013           $gametype = DB_get_solo_by_gameid($gameid);
1014           $GT       = $gametype." ".$GT;
1015         }
1016       else
1017         $gametype = "normal";
1018       
1019       set_gametype($gametype); /* this sets the $CARDS variable */
1020       
1021       /* get some infos about the game */
1022       $gamestatus = DB_get_game_status_by_gameid($gameid);
1023       
1024       /* has the game started? No, then just wait here...*/
1025       if($gamestatus == 'pre')
1026         {
1027           echo "You finished the setup, but not everyone else finished it... ".
1028                "so you need to wait for the others. Just wait for the an email... <br />";
1029           break; /* not sure this works... the idea is that you can 
1030                   * only  play a card after everyone is ready to play */
1031         }
1032
1033       /* get time from the last action of the game */
1034       $result  = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
1035       $r       = mysql_fetch_array($result,MYSQL_NUM);
1036       $gameend = time() - strtotime($r[0]);
1037
1038       /* handel comments in case player didn't play a card, allow comments a week after the end of the game */
1039       if( (!myisset("card") && $mystatus=='play') || ($mystatus=='gameover' && ($gameend < 60*60*24*7)) )
1040         if(myisset("comment"))
1041           {
1042             $comment = $_REQUEST["comment"];
1043             $playid = DB_get_current_playid($gameid);
1044             
1045             if($comment != "")
1046               DB_insert_comment($comment,$playid,$myid);
1047           };  
1048
1049       /* get everything relevant to display the tricks */
1050       $result = mysql_query("SELECT Hand_Card.card_id as card,".
1051                             "       Hand.position as position,".
1052                             "       Play.sequence as sequence, ".
1053                             "       Trick.id, ".
1054                             "       GROUP_CONCAT(CONCAT('<span>',User.fullname,': ',Comment.comment,'</span>') SEPARATOR '\n' ), ".
1055                             "       Play.create_date, ".
1056                             "       Hand.user_id ".
1057                             "FROM Trick ".
1058                             "LEFT JOIN Play ON Trick.id=Play.trick_id ".
1059                             "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
1060                             "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
1061                             "LEFT JOIN Comment ON Play.id=Comment.play_id ".
1062                             "LEFT JOIN User On User.id=Comment.user_id ".
1063                             "WHERE Trick.game_id='".$gameid."' ".
1064                             "GROUP BY Trick.id, sequence ".
1065                             "ORDER BY Trick.id, sequence  ASC");
1066       $trickNR   = 1;
1067       $lasttrick = DB_get_max_trickid($gameid);
1068       
1069       $play = array(); /* needed to calculate winner later  */
1070       $seq  = 1;          
1071       $pos  = DB_get_startplayer_by_gameid($gameid)-1; 
1072       $firstcard = ""; /* first card in a trick */
1073       
1074       echo "\n<ul class=\"tricks\">\n";
1075       echo "  <li class=\"nohighlight\"> Game $gameid: </li>\n";
1076       
1077       while($r = mysql_fetch_array($result,MYSQL_NUM))
1078         {
1079           $pos     = $r[1];
1080           $seq     = $r[2];
1081           $trick   = $r[3];
1082           $comment = $r[4];
1083           $timeplayed = strtotime($r[5]);
1084           $user    = $r[6];
1085
1086           $offset = DB_get_user_timezone($user);
1087           $zone   = return_timezone($offset);
1088           date_default_timezone_set($zone);
1089
1090           /* check if first schweinchen has been played */
1091           if($r[0] == 19 || $r[0] == 20 )
1092             $GAME["schweinchen"]++;
1093           
1094           /* save card to be able to find the winner of the trick later */
1095           $play[$seq] = array("card"=>$r[0],"pos"=>$pos); 
1096           
1097           if($seq==1)
1098             {
1099               /* first card in a trick, output some html */
1100               if($trick!=$lasttrick)
1101                 {
1102                   /* start of an old trick? */
1103                   echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">Trick $trickNR</a>\n".
1104                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1105                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1106                 }
1107               else if($trick==$lasttrick)
1108                 {
1109                   /* start of a last trick? */
1110                   echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">Trick $trickNR</a>\n".
1111                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1112                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1113                 };
1114               
1115               /* remember first card, so that we are able to check, what cards can be played */
1116               $firstcard = $r[0];
1117             };
1118           
1119           /* display card */
1120           echo "      <div class=\"card".($pos-1)."\">\n";
1121           
1122           /* display comments */
1123           if($comment!="")
1124             echo "        <span class=\"comment\">".$comment."</span>\n";
1125           
1126           echo "        ";
1127           display_card($r[0],$PREF["cardset"]);
1128           
1129           echo "      </div>\n"; /* end div card */
1130           
1131           /* end of trick? */
1132           if($seq==4)
1133             {
1134               $trickNR++;
1135               echo "    </div>\n  </li>\n";  /* end div table, end li table */
1136             }
1137         }
1138       
1139       if($seq!=4 && $trickNR>1) 
1140         echo "    </div>\n  </li>\n";  /* end div table, end li table */
1141       
1142       echo "</ul>\n";
1143       
1144       /* whos turn is it? */
1145       if($seq==4)
1146         {
1147           $winner    = get_winner($play,$gametype); /* returns the position */
1148           $next      = $winner;
1149           $firstcard = ""; /* new trick, no first card */
1150         }
1151       else
1152         {
1153           $next = $pos+1;
1154           if($next==5) $next = 1;
1155         }
1156       
1157       /* my turn?, display cards as links, ask for comments*/
1158       if(DB_get_pos_by_hash($me) == $next)
1159         $myturn = 1;
1160       else
1161         $myturn = 0;
1162
1163       /* do we want to play a card? */
1164       if(myisset("card") && $myturn)
1165         {
1166           $card   = $_REQUEST["card"];
1167           $handid = DB_get_handid_by_hash($me); 
1168           
1169           /* check if we have card and that we haven't played it yet*/
1170           /* set played in hand_card to true where hand_id and card_id*/
1171           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
1172                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1173           $r = mysql_fetch_array($result,MYSQL_NUM);
1174           $handcardid = $r[0];
1175           
1176           if($handcardid) /* everything ok, play card  */
1177             {
1178               /* update Game timestamp */
1179               DB_update_game_timestamp($gameid);
1180
1181               /* check if a call was made, must do this before we set the card status to played */
1182               if(myisset("call120") && $_REQUEST["call120"] == "yes" && can_call(120,$me))
1183                 $result = mysql_query("UPDATE Hand SET point_call='120' WHERE hash='$me' ");
1184               if(myisset("call90")  && $_REQUEST["call90"]  == "yes" && can_call(90,$me))
1185                 $result = mysql_query("UPDATE Hand SET point_call='90'  WHERE hash='$me' ");
1186               if(myisset("call60")  && $_REQUEST["call60"]  == "yes" && can_call(60,$me))
1187                 $result = mysql_query("UPDATE Hand SET point_call='60'  WHERE hash='$me' ");
1188               if(myisset("call30")  && $_REQUEST["call30"]  == "yes" && can_call(30,$me))
1189                 $result = mysql_query("UPDATE Hand SET point_call='30'  WHERE hash='$me' ");
1190               if(myisset("call0")   && $_REQUEST["call0"]   == "yes" && can_call(0,$me))
1191                 $result = mysql_query("UPDATE Hand SET point_call='0'   WHERE hash='$me' ");
1192                 
1193               /* mark card as played */
1194               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
1195                           DB_quote_smart($card));
1196
1197               /* get trick id or start new trick */
1198               $a = DB_get_current_trickid($gameid);
1199               $trickid  = $a[0];
1200               $sequence = $a[1];
1201               $tricknr  = $a[2];
1202               
1203               $playid = DB_play_card($trickid,$handcardid,$sequence);
1204
1205               /* check for schweinchen */
1206               if($card == 19 || $card == 20 )
1207                 {
1208                   $GAME["schweinchen"]++;
1209                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
1210                     DB_insert_comment("Schweinchen! ",$playid,$myid);
1211                   if($RULES["schweinchen"]=="both" )
1212                     DB_insert_comment("Schweinchen! ",$playid,$myid);
1213                   if ($debug) 
1214                     echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
1215                 }
1216
1217               /* if sequence == 4 check who one in case of wedding */
1218               if($sequence == 4 && $GT == "wedding") 
1219                 {
1220                   /* is wedding resolve */
1221                   $resolved = DB_get_sickness_by_gameid($gameid); 
1222                   if($resolved<0)
1223                     {
1224                       /* who has wedding */
1225                       $userids = DB_get_all_userid_by_gameid($gameid);
1226                       foreach($userids as $user)
1227                         {
1228                           $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1229                           if($usersick == "wedding")
1230                             $whosick = $user;
1231                         }
1232                       /* who won the trick */
1233                       $play     = DB_get_cards_by_trick($trickid);
1234                       $winner   = get_winner($play,$gametype); /* returns the position */
1235                       $winnerid = DB_get_userid_by_gameid_and_position($gameid,$winner);
1236                       /* is tricknr <=3 */
1237                       if($tricknr <=3 && $winnerid!=$whosick)
1238                         {
1239                           /* set resolved at tricknr*/
1240                           $resolved = DB_set_sickness_by_gameid($gameid,$tricknr); 
1241                           /* set partner */
1242                           $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1243                           DB_set_party_by_hash($whash,"re");
1244                         }
1245                       if($tricknr == 3 && $winnerid==$whosick)
1246                         {
1247                           /* set resolved at tricknr*/
1248                           $resolved = DB_set_sickness_by_gameid($gameid,'3'); 
1249                         }
1250                     }
1251                 }
1252
1253               /* if sequence == 4, set winner of the trick, count points and set the next player */
1254               if($sequence==4)
1255                 {
1256                   $play   = DB_get_cards_by_trick($trickid);
1257                   $winner = get_winner($play,$gametype); /* returns the position */
1258
1259                   if($winner>0)
1260                     mysql_query("UPDATE Trick SET winner='$winner' WHERE id='$trickid'");
1261                   else
1262                     echo "ERROR during scoring";
1263
1264                   if($debug)
1265                     echo "DEBUG: position $winner won the trick <br />";
1266
1267                   /* who is the next player? */
1268                   $next = $winner;
1269                 }
1270               else
1271                 {
1272                   $next = DB_get_pos_by_hash($me)+1;
1273                 }
1274               if($next==5) $next=1;
1275
1276               /* check for coment */
1277               if(myisset("comment"))
1278                 {
1279                   $comment = $_REQUEST["comment"];
1280                   if($comment != "")
1281                     DB_insert_comment($comment,$playid,$myid);
1282                 };  
1283               
1284               /* display played card */
1285               echo "<div class=\"card\">";
1286               echo " you played  <br />";
1287               /* display comments */
1288               display_card($card,$PREF["cardset"]);
1289               if($comment!="")
1290                 echo "       <br /> Your comment:<br /><span class=\"comment\">".$comment."</span>\n";
1291               echo "</div>\n";
1292               
1293               /*check if we still have cards left, else set status to gameover */
1294               if(sizeof(DB_get_hand($me))==0)
1295                 {
1296                   DB_set_hand_status_by_hash($me,'gameover');
1297                   $mystatus='gameover';
1298                 }
1299               
1300               /* if all players are done, set game status to game over, 
1301                * get the points of the last trick and send out an email 
1302                * to all players
1303                */
1304               $userids = DB_get_all_userid_by_gameid($gameid);
1305               
1306               $done=1;
1307               foreach($userids as $user)
1308                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1309                   $done=0;
1310               
1311               if($done)
1312                 DB_set_game_status_by_gameid($gameid,"gameover");
1313
1314               /* email next player, if game is still running */
1315               if(DB_get_game_status_by_gameid($gameid)=='play')
1316                 {
1317                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1318                   $email     = DB_get_email_by_hash($next_hash);
1319                   $who       = DB_get_userid_by_email($email);
1320                   DB_set_player_by_gameid($gameid,$who);
1321                   
1322                   $message = "A card has been played in game $gameid.\n\n".
1323                     "It's your turn  now.\n".
1324                     "Use this link to play a card: ".$host."?me=".$next_hash."\n\n" ;
1325                   mymail($email,$EmailName."a card has been played in game $gameid",$message);
1326                 }
1327               else /* send out final email */
1328                 {
1329                   /* individual score */
1330                   $result = mysql_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1331                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1332                                 " LEFT JOIN User ON User.id=Hand.user_id".
1333                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1334                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1335                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1336                                 " WHERE Hand.game_id='$gameid'".
1337                                 " GROUP BY User.fullname" );
1338                   $message  = "The game is over. Thanks for playing :)\n";
1339                   $message .= "Final score:\n";
1340                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1341                     $message .= "   ".$r[0]."(".$r[2].") ".$r[1]."\n";
1342
1343                   $result = mysql_query("SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1344                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1345                                 " LEFT JOIN User ON User.id=Hand.user_id".
1346                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1347                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1348                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1349                                 " WHERE Hand.game_id='$gameid'".
1350                                 " GROUP BY Hand.party" );
1351                   $message .= "\nTotals:\n";
1352                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1353                     $message .= "    ".$r[0]." ".$r[1]."\n";
1354                   
1355                   /* send out final email */
1356                   $all = array();
1357
1358                   foreach($userids as $user)
1359                     $all[] = DB_get_email_by_userid($user);
1360                   $To = implode(",",$all);
1361
1362                   $help = "\n\n (you can use reply all on this email to reach all the players.)\n";
1363                   mymail($To,$EmailName."game over (game $gameid) part 1(2)",$message.$help);
1364
1365                   foreach($userids as $user)
1366                     {
1367                       $To   = DB_get_email_by_userid($user);
1368                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1369                       
1370                       $link = "Use this link to have a look at game $gameid: ".$host."?me=".$hash."\n\n" ;
1371                       mymail($To,$EmailName."game over (game $gameid) part 2(2)",$link);
1372                     }
1373                 }
1374             }
1375           else
1376             {
1377               echo "can't find that card?! <br />\n";
1378             }
1379         }
1380       else if(myisset("card") && !$myturn )
1381         {
1382           echo "please wait until it's your turn! <br />\n";
1383         }
1384       
1385       $mycards = DB_get_hand($me);
1386       $mycards = mysort($mycards,$gametype);
1387       echo "<div class=\"mycards\">\n";
1388       
1389       if($myturn && !myisset("card") && $mystatus=='play' )
1390         {
1391           echo "Hello ".$myname.", it's your turn!  <br />\n";
1392           echo "Your cards are: <br />\n";
1393           
1394           /* do we have to follow suite? */
1395           $followsuit = 0;
1396           if(have_suit($mycards,$firstcard))
1397             $followsuit = 1;
1398           
1399           foreach($mycards as $card) 
1400             {
1401               if($followsuit && !same_type($card,$firstcard))
1402                 display_card($card,$PREF["cardset"]);
1403               else
1404                 display_link_card($card,$PREF["cardset"]);
1405             }
1406         }
1407       else if($mystatus=='play' )
1408         {         
1409           echo "Your cards are: <br />\n";
1410           foreach($mycards as $card) 
1411             display_card($card,$PREF["cardset"]);
1412         }
1413       else if($mystatus=='gameover')
1414         {
1415           /* get time from the last action of the game */
1416           $result  = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
1417           $r       = mysql_fetch_array($result,MYSQL_NUM);
1418           $gameend = time() - strtotime($r[0]);
1419           
1420           if( $gameend < 60*60*24*7 )
1421             {
1422               echo "<br />\nA short comment:<input name=\"comment\" type=\"text\" size=\"30\" maxlength=\"100\" />\n";
1423               echo "<input type=\"hidden\" name=\"me\" value=\"$me\" />\n";
1424               echo "<input type=\"submit\" value=\"submit\" />\n";
1425             }
1426
1427           $oldcards = DB_get_all_hand($me);
1428           $oldcards = mysort($oldcards,$gametype);
1429           echo "Your cards were: <br />\n";
1430           foreach($oldcards as $card) 
1431             display_card($card,$PREF["cardset"]);
1432           
1433           $userids = DB_get_all_userid_by_gameid($gameid);
1434           foreach($userids as $user)
1435             {
1436               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1437               
1438               if($userhash!=$me)
1439                 {
1440                   echo "<br />";
1441                   
1442                   $name = DB_get_name_by_userid($user);
1443                   $oldcards = DB_get_all_hand($userhash);
1444                   $oldcards = mysort($oldcards,$gametype);
1445                   echo "$name's cards were: <br />\n";
1446                   foreach($oldcards as $card)
1447                     display_card($card,$PREF["cardset"]);
1448                 }
1449             };
1450         }
1451       echo "</div>\n";
1452       
1453       /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
1454       if($mystatus=='play')
1455         break;
1456
1457       /* the following happens only when the gamestatus is 'gameover' */
1458       /* check if game is over, display results */
1459       if(DB_get_game_status_by_gameid($gameid)=='play')
1460         {
1461           echo "the game is over for you.. other people still need to play though";
1462         }
1463       else
1464         {
1465           echo "the game is over now...<br />\n";
1466           
1467           $result = mysql_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1468                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1469                                 " LEFT JOIN User ON User.id=Hand.user_id".
1470                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1471                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1472                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1473                                 " WHERE Hand.game_id='$gameid'".
1474                                 " GROUP BY User.fullname" );
1475           echo "Final Score:<br />\n".
1476             " <table>\n";;
1477           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1478             echo "  <tr><td>  ".$r[0]."</td><td>(".$r[2].")</td><td> ".$r[1]."</td></tr>";
1479           echo "</table>\n";
1480
1481
1482           $result = mysql_query("SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1483                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1484                                 " LEFT JOIN User ON User.id=Hand.user_id".
1485                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1486                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1487                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1488                                 " WHERE Hand.game_id='$gameid'".
1489                                 " GROUP BY Hand.party" );
1490           echo "Totals:<br />\n".
1491             " <table> \n";
1492           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1493             echo "  <tr><td>".$r[0]."</td><td> ".$r[1]."</td></tr>\n";
1494           echo "</table>\n";
1495           
1496           $session = DB_get_session_by_gameid($gameid);
1497           $result  = mysql_query("SELECT id,create_date FROM Game".
1498                                  " WHERE session=$session".
1499                                  " ORDER BY create_date DESC".
1500                                  " LIMIT 1");
1501           $r = -1;
1502           if($result)
1503             $r = mysql_fetch_array($result,MYSQL_NUM);
1504           
1505           if(!$session || $gameid==$r[0])
1506             {
1507               /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
1508               $names = DB_get_all_names_by_gameid($gameid);
1509               $type  = DB_get_gametype_by_gameid($gameid);
1510               
1511               if($type=="solo")
1512                 output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
1513               else
1514                 output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1515             }
1516         }
1517       break;
1518     default:
1519       myerror("error in testing the status");
1520     }
1521     echo "</form>\n";
1522     output_footer();
1523     DB_close();
1524     exit();
1525  } 
1526 /* user status page */ 
1527 else if( myisset("email","password") || isset($_SESSION["name"]) )
1528    {
1529      /* test id and password, should really be done in one step */
1530      if(!isset($_SESSION["name"]))
1531        {
1532          $email     = $_REQUEST["email"];
1533          $password  = $_REQUEST["password"];
1534        }
1535      else
1536        {
1537          $name = $_SESSION["name"];
1538          $email     = DB_get_email_by_name($name);
1539          $password  = DB_get_passwd_by_name($name);
1540        };
1541      
1542      if(myisset("forgot"))
1543        {
1544          $ok = 1;
1545
1546          $uid = DB_get_userid_by_email($email);
1547          if(!$uid)
1548            $ok = 0;
1549          
1550          if($ok)
1551            {
1552              /* check how many entries in recovery table */
1553              $number = DB_get_number_of_passwords_recovery($uid);
1554              
1555              /* if less than N recent ones, add a new one and send out email */
1556              if( $number < 5 )
1557                {
1558                  echo "Ok, I send you a new password. <br />";
1559                  if($number >1)
1560                    echo "N.B. You tried this already $number times during the last day and it will only work ".
1561                      " 5 times during a day.<br />";
1562                  echo "The new password will be valid for one day, make sure you reset it to something else.<br />";
1563                  echo "Back to the  <a href=\"$host\">main page</a>.";
1564                  
1565                  $TIME  = (string) time(); /* to avoid collisions */
1566                  $hash  = md5("Anewpassword".$email.$TIME);
1567                  $newpw = substr($hash,1,8);
1568                  
1569                  $message = "Someone (hopefully you) requested a new password. \n".
1570                    "You can use this email and the following password: \n".
1571                    "   $newpw    \n".
1572                    "to log into the server. The new password is valid for 24h, so make\n".
1573                    "sure you reset your password to something new. Your old password will\n".
1574                    " also still be valid until you set a new one\n";
1575                  mymail($email,$EmailName."recovery ",$message);
1576                  
1577                  DB_set_recovery_password($uid,md5($newpw));
1578                }
1579              else
1580                {
1581                  echo "Sorry you already tried 5 times during the last 24h.<br />".
1582                    "You need to use one of those passwords or wait to get a new one.<br />";
1583                  echo "Back to the <a href=\"$host\">main page</a>.";
1584                }
1585            }
1586          else
1587            {
1588              if($email=="")
1589                echo "You need to give me an email address! <br />".
1590                  "Please try <a href=\"$host\">again</a>.";
1591              else
1592                echo "Couldn't find a player with this email! <br />".
1593                  "Please contact Arun, if you think this is a mistake <br />".
1594                  "or else try <a href=\"$host\">again</a>.";
1595            } 
1596        }
1597      else 
1598      {
1599        /* verify password and email */
1600        if(strlen($password)!=32)
1601          $password = md5($password);
1602        
1603        $ok  = 1;
1604        $uid = DB_get_userid_by_email_and_password($email,$password);
1605        if(!$uid)
1606          $ok = 0;
1607        
1608        if($ok)
1609          {
1610            DB_get_PREF($uid);
1611
1612            if(myisset("setpref"))
1613              {
1614                $setpref=$_REQUEST["setpref"];
1615                switch($setpref)
1616                  {
1617                  case "germancards":
1618                  case "englishcards":
1619                    $result = mysql_query("SELECT * from User_Prefs".
1620                                          " WHERE user_id='$uid' AND pref_key='cardset'" );
1621                    if( mysql_fetch_array($result,MYSQL_NUM))
1622                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
1623                                            " WHERE user_id='$uid' AND pref_key='cardset'" );
1624                    else
1625                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$uid','cardset',".
1626                                            DB_quote_smart($setpref).")");
1627                    echo "Ok, changed you preferences for the cards.\n";
1628                    break;
1629                  }
1630              }
1631            else if(myisset("passwd"))
1632              {
1633                if( $_REQUEST["passwd"]=="ask" )
1634                  {
1635                    /* reset password form*/
1636                    output_password_recovery($email,$password);         
1637                  }
1638                else if($_REQUEST["passwd"]=="set")
1639                  {
1640                    /* reset password */
1641                    $ok = 1;
1642
1643                    /* check if old password matches */
1644                    $oldpasswd = md5($_REQUEST["password0"]);
1645                    if(!( ($password == $oldpasswd) || DB_check_recovery_passwords($oldpasswd,$email) ))
1646                      $ok = -1;
1647                    /* check if new passwords are types the same twice */
1648                    if($_REQUEST["password1"] != $_REQUEST["password2"] )
1649                      $ok = -2;
1650                    
1651                    switch($ok)
1652                      {
1653                      case '-2':
1654                        echo "The new passwords don't match. <br />";
1655                        break;
1656                      case '-1':
1657                        echo "The old password is not correct. <br />";
1658                        break;
1659                      case '1':
1660                        echo "Changed the password.<br />";
1661                        mysql_query("UPDATE User SET password='".md5($_REQUEST["password1"]).
1662                                    "' WHERE id=".DB_quote_smart($uid));
1663                        break;
1664                      }
1665                    /* set password */
1666                  }
1667              }
1668            else /* output default user page */
1669              {
1670                $time     = DB_get_user_timestamp($uid);
1671                $unixtime = strtotime($time);
1672                
1673                $offset   = DB_get_user_timezone($uid);
1674                $zone     = return_timezone($offset);
1675                date_default_timezone_set($zone);
1676
1677                $myname = DB_get_name_by_email($email);
1678                $_SESSION["name"] = $myname;
1679
1680                if(isset($_SESSION["name"]))
1681                  output_status($_SESSION["name"]);
1682                
1683                /* display links to settings */
1684                output_user_settings($email,$password);
1685                
1686                echo "last login: ".date("r",$unixtime)."<br />";
1687                
1688                DB_update_user_timestamp($uid);
1689                
1690                echo "<p>These are your games that haven't started yet:<br />\n";
1691                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date,Game.player from Hand".
1692                                      " LEFT JOIN Game On Hand.game_id=Game.id".
1693                                      " WHERE Hand.user_id='$uid' AND Game.status='pre'" );
1694                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1695                  {
1696                    echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1697                    if($r[3]==$uid || $r[3]==NULL)
1698                      echo "(it's <strong>your</strong> turn)\n";
1699                    else
1700                      {
1701                        $name = DB_get_name_by_userid($r[3]);
1702                        echo "(it's $name's turn)\n";
1703                      };
1704                      
1705                    if(time()-strtotime($r[2]) > 60*60*24*30)
1706                      echo " The game has been running for over a month.".
1707                        " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1708                        " (clicking here is final and can't be restored)";
1709                    echo "<br />";
1710                  }
1711                echo "</p>\n";
1712
1713                echo "<p>These are the games you are playing in:<br />\n";
1714                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date,Game.player from Hand".
1715                                      " LEFT JOIN Game On Hand.game_id=Game.id".
1716                                      " WHERE Hand.user_id='$uid' AND Game.status='play'" );
1717                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1718                  {
1719                    echo "<a href=\"".$host."?me=".$r[0]."\">game #".$r[1]." </a>";
1720                    if($r[3])
1721                      {
1722                        if($r[3]==$uid)
1723                          echo "(it's <strong>your</strong> turn)\n";
1724                        else
1725                          {
1726                            $name = DB_get_name_by_userid($r[3]);
1727                            echo "(it's $name's turn)\n";
1728                          };
1729                      }
1730                    if(time()-strtotime($r[2]) > 60*60*24*30)
1731                      echo " The game has been running for over a month.".
1732                        " Do you want to cancel it? <a href=\"$host?cancle=1&amp;me=".$r[0]."\">yes</a>".
1733                        " (clicking here is final and can't be restored)";
1734                    echo "<br />";
1735                  }
1736                echo "</p>\n";
1737                
1738                
1739                echo "<p>And these are your games that are already done:<br />Game: \n";
1740                $output = array();
1741                $result = mysql_query("SELECT hash,game_id from Hand WHERE user_id='$uid' AND status='gameover'" );
1742                while( $r = mysql_fetch_array($result,MYSQL_NUM))
1743                  $output[] = "<a href=\"".$host."?me=".$r[0]."\">#".$r[1]." </a>";
1744                echo implode(", ",$output)."</p>\n";
1745                
1746                $names = DB_get_all_names();
1747                echo "<p>Registered players:<br />\n";
1748                echo implode(", ",$names)."\n";
1749                echo "</p>\n";
1750                
1751                echo "<p>Want to start a new game? Visit <a href=\"".$host."?new\">this page.</a></p>";
1752              }
1753          }
1754        else
1755          {
1756            echo "Sorry email and password don't match. Please <a href=\"$host\">try again</a>. <br />";
1757          }
1758      };
1759      output_footer();
1760      DB_close();
1761      exit();
1762    }
1763 /* default login page */
1764  else
1765    { 
1766      $pre[0]=0;$game[0]=0;$done[0]=0;
1767      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
1768      if($r) {
1769        $pre  = mysql_fetch_array($r,MYSQL_NUM);     
1770        $game = mysql_fetch_array($r,MYSQL_NUM);     
1771        $done = mysql_fetch_array($r,MYSQL_NUM);     
1772      }
1773
1774      $r=mysql_query("SELECT AVG(datediff(mod_date,create_date)) FROM Game where status='gameover' ");
1775      if($r)
1776        $avgage= mysql_fetch_array($r,MYSQL_NUM);     
1777      else
1778        $avgage[0]=0;
1779
1780      output_home_page($pre[0],$game[0],$done[0],$avgage[0]);
1781    }
1782
1783 output_footer();
1784
1785 DB_close();
1786
1787 /*
1788  *Local Variables: 
1789  *mode: php
1790  *mode: hs-minor
1791  *End:
1792  */
1793 ?>
1794
1795