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