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