6729d5688c0058cc226cbb0dd3998a2f5fb981f0
[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       /* output vorbehalte */
1158       $mygametype =  DB_get_gametype_by_gameid($gameid);
1159       if($mygametype != "normal") /* only show when needed */
1160         {
1161           echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
1162             "    <div class=\"trick\" id=\"trick0\">\n";
1163           $show = 1;
1164           for($mypos=1;$mypos<5;$mypos++)
1165             {
1166               $usersick = DB_get_sickness_by_pos_and_gameid($mypos,$gameid);
1167               if($usersick!=NULL)
1168                 {
1169                   echo "      <div class=\"vorbehalt".($mypos-1)."\"> Vorbehalt <br />";
1170                   if($show)
1171                     echo " $usersick <br />";
1172                   echo  " </div>\n";
1173
1174                   if($mygametype == $usersick)
1175                     $show = 0;
1176                 }
1177             }
1178           echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1179         }
1180
1181       /* output tricks */
1182       while($r = mysql_fetch_array($result,MYSQL_NUM))
1183         {
1184           $pos     = $r[1];
1185           $seq     = $r[2];
1186           $trick   = $r[3];
1187           $comment = $r[4];
1188           $user    = $r[6];
1189
1190           /* check if first schweinchen has been played */
1191           if( $GAME["schweinchen"] && ($r[0] == 19 || $r[0] == 20) )
1192             $GAME["schweinchen"]++;
1193
1194           /* save card to be able to find the winner of the trick later */
1195           $play[$seq] = array("card"=>$r[0],"pos"=>$pos);
1196
1197           if($seq==1)
1198             {
1199               /* first card in a trick, output some html */
1200               if($trick!=$lasttrick)
1201                 {
1202                   /* start of an old trick? */
1203                   echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">Trick $trickNR</a>\n".
1204                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1205                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1206                 }
1207               else if($trick==$lasttrick)
1208                 {
1209                   /* start of a last trick? */
1210                   echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">Trick $trickNR</a>\n".
1211                     "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1212                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1213                 };
1214
1215               /* remember first card, so that we are able to check, what cards can be played */
1216               $firstcard = $r[0];
1217             };
1218
1219           /* display card */
1220           echo "      <div class=\"card".($pos-1)."\">\n";
1221
1222           /* display comments */
1223           if($comment!="")
1224             echo "        <span class=\"comment\">".$comment."</span>\n";
1225
1226           echo "        ";
1227           display_card($r[0],$PREF["cardset"]);
1228
1229           echo "      </div>\n"; /* end div card */
1230
1231           /* end of trick? */
1232           if($seq==4)
1233             {
1234               $trickNR++;
1235               echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1236             }
1237         }
1238
1239       /* whos turn is it? */
1240       if($seq==4)
1241         {
1242           $winner    = get_winner($play,$gametype); /* returns the position */
1243           $next      = $winner;
1244           $firstcard = ""; /* new trick, no first card */
1245         }
1246       else
1247         {
1248           $next = $pos+1;
1249           if($next==5) $next = 1;
1250         }
1251
1252       /* my turn?, display cards as links, ask for comments*/
1253       if(DB_get_pos_by_hash($me) == $next)
1254         $myturn = 1;
1255       else
1256         $myturn = 0;
1257
1258       /* do we want to play a card? */
1259       if(myisset("card") && $myturn)
1260         {
1261           $card   = $_REQUEST["card"];
1262           $handid = DB_get_handid_by_hash($me);
1263
1264           /* check if we have card and that we haven't played it yet*/
1265           /* set played in hand_card to true where hand_id and card_id*/
1266           $result = mysql_query("SELECT id FROM Hand_Card WHERE played='false' and ".
1267                                 "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1268           $r = mysql_fetch_array($result,MYSQL_NUM);
1269           $handcardid = $r[0];
1270
1271           if($handcardid) /* everything ok, play card  */
1272             {
1273               /* update Game timestamp */
1274               DB_update_game_timestamp($gameid);
1275
1276               /* check if a call was made, must do this before we set the card status to played */
1277               if(myisset("call120") && $_REQUEST["call120"] == "yes" && can_call(120,$me))
1278                 $result = mysql_query("UPDATE Hand SET point_call='120' WHERE hash='$me' ");
1279               if(myisset("call90")  && $_REQUEST["call90"]  == "yes" && can_call(90,$me))
1280                 $result = mysql_query("UPDATE Hand SET point_call='90'  WHERE hash='$me' ");
1281               if(myisset("call60")  && $_REQUEST["call60"]  == "yes" && can_call(60,$me))
1282                 $result = mysql_query("UPDATE Hand SET point_call='60'  WHERE hash='$me' ");
1283               if(myisset("call30")  && $_REQUEST["call30"]  == "yes" && can_call(30,$me))
1284                 $result = mysql_query("UPDATE Hand SET point_call='30'  WHERE hash='$me' ");
1285               if(myisset("call0")   && $_REQUEST["call0"]   == "yes" && can_call(0,$me))
1286                 $result = mysql_query("UPDATE Hand SET point_call='0'   WHERE hash='$me' ");
1287
1288               /* mark card as played */
1289               mysql_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
1290                           DB_quote_smart($card));
1291
1292               /* get trick id or start new trick */
1293               $a = DB_get_current_trickid($gameid);
1294               $trickid  = $a[0];
1295               $sequence = $a[1];
1296               $tricknr  = $a[2];
1297
1298               $playid = DB_play_card($trickid,$handcardid,$sequence);
1299
1300               /* check for schweinchen */
1301               if($GAME["schweinchen"] && ($card == 19 || $card == 20) )
1302                 {
1303                   $GAME["schweinchen"]++; // count how many have been played including this one
1304                   if($GAME["schweinchen"]==3 && $RULES["schweinchen"]=="second" )
1305                     DB_insert_comment("Schweinchen! ",$playid,$myid);
1306                   if($RULES["schweinchen"]=="both" )
1307                     DB_insert_comment("Schweinchen! ",$playid,$myid);
1308                   if ($debug)
1309                     echo "schweinchen = ".$GAME["schweinchen"]." ---<br />";
1310                 }
1311
1312               /* if sequence == 4 check who one in case of wedding */
1313               if($sequence == 4 && $GT == "wedding")
1314                 {
1315                   /* is wedding resolve */
1316                   $resolved = DB_get_sickness_by_gameid($gameid);
1317                   if($resolved<0)
1318                     {
1319                       /* who has wedding */
1320                       $userids = DB_get_all_userid_by_gameid($gameid);
1321                       foreach($userids as $user)
1322                         {
1323                           $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1324                           if($usersick == "wedding")
1325                             $whosick = $user;
1326                         }
1327                       /* who won the trick */
1328                       $play     = DB_get_cards_by_trick($trickid);
1329                       $winner   = get_winner($play,$gametype); /* returns the position */
1330                       $winnerid = DB_get_userid_by_gameid_and_position($gameid,$winner);
1331                       /* is tricknr <=3 */
1332                       if($tricknr <=3 && $winnerid!=$whosick)
1333                         {
1334                           /* set resolved at tricknr*/
1335                           $resolved = DB_set_sickness_by_gameid($gameid,$tricknr);
1336                           /* set partner */
1337                           $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1338                           DB_set_party_by_hash($whash,"re");
1339                         }
1340                       if($tricknr == 3 && $winnerid==$whosick)
1341                         {
1342                           /* set resolved at tricknr*/
1343                           $resolved = DB_set_sickness_by_gameid($gameid,'3');
1344                         }
1345                     }
1346                 }
1347
1348               /* if sequence == 4, set winner of the trick, count points and set the next player */
1349               if($sequence==4)
1350                 {
1351                   $play   = DB_get_cards_by_trick($trickid);
1352                   $winner = get_winner($play,$gametype); /* returns the position */
1353
1354                   /* check if someone caught a fox */
1355                   if(DB_get_gametype_by_gameid($gameid)!="solo")
1356                     foreach($play as $played)
1357                       {
1358                         if ( $played['card']==19 || $played['card']==20 )
1359                           if ($played['pos']!= $winner )
1360                             {
1361                               /* possible caught a fox, check party */
1362                               $uid1 = DB_get_userid_by_gameid_and_position($gameid,$winner);
1363                               $uid2 = DB_get_userid_by_gameid_and_position($gameid,$played['pos']);
1364
1365                               $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1366                               $party2 = DB_get_party_by_gameid_and_userid($gameid,$uid2);
1367
1368                               if($party1 != $party2)
1369                                 mysql_query("INSERT INTO Score".
1370                                             " VALUES( NULL,NULL,$gameid,'$party1',$uid1,$uid2,'fox')");
1371                             }
1372                       }
1373                   /* check for karlchen (jack of clubs in the last trick)*/
1374                   if(DB_get_gametype_by_gameid($gameid)!="solo" && $tricknr == 12)
1375                     foreach($play as $played)
1376                       if ( $played['card']==11 || $played['card']==12 )
1377                         if ($played['pos'] == $winner )
1378                           {
1379                             /* possible caught a fox, check party */
1380                             $uid1   = DB_get_userid_by_gameid_and_position($gameid,$winner);
1381                             $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1382
1383                             mysql_query("INSERT INTO Score".
1384                                         " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'karlchen')");
1385                           }
1386                   /* check for doppelopf (>40 points)*/
1387                   $points = 0;
1388                   foreach($play as $played)
1389                     {
1390                       $points += DB_get_card_value_by_cardid($played['card']);
1391                     }
1392                   if($points > 39)
1393                     {
1394                       $uid1   = DB_get_userid_by_gameid_and_position($gameid,$winner);
1395                       $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1396
1397                       mysql_query("INSERT INTO Score".
1398                                   " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'doko')");
1399                     }
1400
1401                   if($winner>0)
1402                     mysql_query("UPDATE Trick SET winner='$winner' WHERE id='$trickid'");
1403                   else
1404                     echo "ERROR during scoring";
1405
1406                   if($debug)
1407                     echo "DEBUG: position $winner won the trick <br />";
1408
1409                   /* who is the next player? */
1410                   $next = $winner;
1411                 }
1412               else
1413                 {
1414                   $next = DB_get_pos_by_hash($me)+1;
1415                 }
1416               if($next==5) $next=1;
1417
1418               /* check for coment */
1419               if(myisset("comment"))
1420                 {
1421                   $comment = $_REQUEST["comment"];
1422                   if($comment != "")
1423                     DB_insert_comment($comment,$playid,$myid);
1424                 };
1425
1426               /* display played card */
1427               $pos = DB_get_pos_by_hash($me);
1428               if($sequence==1)
1429                 {
1430                   echo "  <li onclick=\"hl('".($tricknr)."');\" class=\"current\"><a href=\"#\">Trick ".($tricknr)."</a>\n".
1431                     "    <div class=\"trick\" id=\"trick".($tricknr)."\">\n".
1432                     "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1433                 }
1434
1435               echo "      <div class=\"card".($pos-1)."\">\n        ";
1436
1437               /* display comments */
1438               display_card($card,$PREF["cardset"]);
1439               if($comment!="")
1440                 echo "\n        <span class=\"comment\"> ".$comment."</span>\n";
1441               echo "      </div>\n";
1442
1443               /*check if we still have cards left, else set status to gameover */
1444               if(sizeof(DB_get_hand($me))==0)
1445                 {
1446                   DB_set_hand_status_by_hash($me,'gameover');
1447                   $mystatus = 'gameover';
1448                 }
1449
1450               /* if all players are done, set game status to game over,
1451                * get the points of the last trick and send out an email
1452                * to all players
1453                */
1454               $userids = DB_get_all_userid_by_gameid($gameid);
1455
1456               $done=1;
1457               foreach($userids as $user)
1458                 if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1459                   $done=0;
1460
1461               if($done)
1462                 DB_set_game_status_by_gameid($gameid,"gameover");
1463
1464               /* email next player, if game is still running */
1465               if(DB_get_game_status_by_gameid($gameid)=='play')
1466                 {
1467                   $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1468                   $email     = DB_get_email_by_hash($next_hash);
1469                   $who       = DB_get_userid_by_email($email);
1470                   DB_set_player_by_gameid($gameid,$who);
1471
1472                   $message = "A card has been played in game ".DB_format_gameid($gameid).".\n\n".
1473                     "It's your turn  now.\n".
1474                     "Use this link to play a card: ".$HOST.$INDEX."?me=".$next_hash."\n\n" ;
1475                   if( DB_get_email_pref_by_uid($who)!="emailaddict" )
1476                     mymail($email,$EmailName."a card has been played in game ".DB_format_gameid($gameid),$message);
1477                 }
1478               else /* send out final email */
1479                 {
1480                   /* individual score */
1481                   $result = mysql_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1482                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1483                                 " LEFT JOIN User ON User.id=Hand.user_id".
1484                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1485                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1486                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1487                                 " WHERE Hand.game_id='$gameid'".
1488                                 " GROUP BY User.fullname" );
1489                   $message  = "The game is over. Thanks for playing :)\n";
1490                   $message .= "Final score:\n";
1491                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1492                     $message .= "   ".$r[0]."(".$r[2].") ".$r[1]."\n";
1493
1494                   $result = mysql_query("SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1495                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1496                                 " LEFT JOIN User ON User.id=Hand.user_id".
1497                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1498                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1499                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1500                                 " WHERE Hand.game_id='$gameid'".
1501                                 " GROUP BY Hand.party" );
1502                   $message .= "\nTotals:\n";
1503                   $re     = 0;
1504                   $contra = 0;
1505                   while( $r = mysql_fetch_array($result,MYSQL_NUM))
1506                     {
1507                       $message .= "    ".$r[0]." ".$r[1]."\n";
1508                       if($r[0] == "re")
1509                         $re = $r[1];
1510                       else if($r[0] == "contra")
1511                         $contra = $r[1];
1512                     }
1513
1514                   /*
1515                    * save score in database
1516                    *
1517                    */
1518
1519                   /* get calls from re/contra */
1520                   $call_re     = NULL;
1521                   $call_contra = NULL;
1522                   foreach($userids as $user)
1523                     {
1524                       $hash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1525                       $call  = DB_get_call_by_hash($hash);
1526                       $party = DB_get_party_by_hash($hash);
1527
1528                       if($call!=NULL)
1529                         {
1530                           $call = (int) $call;
1531
1532                           if($party=="re")
1533                             {
1534                               if($call_re==NULL)
1535                                 $call_re = $call;
1536                               else if( $call < $call_re)
1537                                 $call_re = $call;
1538                             }
1539                           else if($party=="contra")
1540                             {
1541                               if($call_contra==NULL)
1542                                 $call_contra = $call;
1543                               else if( $call < $call_re)
1544                                 $call_contra = $call;
1545                             }
1546                         }
1547                     }
1548
1549                   /* figure out who one */
1550                   $winning_party = NULL;
1551
1552                   if($call_re == NULL && $call_contra==NULL)
1553                     if($re>120)
1554                       $winning_party="re";
1555                     else
1556                       $winning_party="contra";
1557                   else
1558                     {
1559                       if($call_re)
1560                         {
1561                           $offset = 120 - $call_re;
1562                           if($call_re == 0)
1563                             $offset--; /* since we use a > in the next equation */
1564
1565                           if($re > 120+$offset)
1566                             $winning_party="re";
1567                           else if ( $call_contra == NULL )
1568                             $winning_party="contra";
1569                         }
1570
1571                       if($call_contra)
1572                         {
1573                           $offset = 120 - $call_contra;
1574                           if($call_contra == 0)
1575                             $offset--; /* since we use a > in the next equation */
1576
1577                           if($contra > 120+$offset)
1578                             $winning_party="contra";
1579                           else if ( $call_contra == NULL )
1580                             $winning_party="re";
1581                         }
1582                     }
1583
1584                   /* one point for each call of the other party in case the other party didn't win
1585                    * and one point each in case the party made more than points than one of the calls
1586                    */
1587                   if($winning_party!="contra" && $call_contra!=NULL)
1588                     {
1589                       for( $p=$call_contra;$p<=120; $p+=30 )
1590                         {
1591                           mysql_query("INSERT INTO Score".
1592                                       " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'against$p')");
1593                         }
1594
1595                       for( $p=$call_contra; $p<120; $p+=30)
1596                         {
1597                           if( $re >= $p )
1598                             mysql_query("INSERT INTO Score".
1599                                         " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'made$p')");
1600                         }
1601                     }
1602                   if($winning_party!="re" and $call_re!=NULL)
1603                     {
1604                       for( $p=$call_re;$p<=120; $p+=30 )
1605                         {
1606                           mysql_query("INSERT INTO Score".
1607                                       " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'against$p')");
1608                         }
1609
1610                       for( $p=$call_re; $p<120; $p+=30)
1611                         {
1612                           if( $contra>=$p )
1613                             mysql_query("INSERT INTO Score".
1614                                         " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'made$p')");
1615                         }
1616                     }
1617
1618                   /* point in case contra won */
1619                   if($winning_party=="contra")
1620                     {
1621                       mysql_query("INSERT INTO Score".
1622                                   " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'againstqueens')");
1623                     }
1624
1625                   /* one point each for winning and each 30 points + calls */
1626                   if($winning_party=="re")
1627                     {
1628                       foreach(array(120,150,180,210,240) as $p)
1629                         {
1630                           $offset = 0;
1631                           if($p==240 || $call_contra!=NULL)
1632                             $offset = 1;
1633
1634                           if($re>$p-$offset)
1635                             mysql_query("INSERT INTO Score".
1636                                         " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'".(240-$p)."')");
1637                         }
1638                       /* re called something and won */
1639                       foreach(array(0,30,60,90,120) as $p)
1640                         {
1641                           if($call_re!=NULL && $call_re<$p+1)
1642                             mysql_query("INSERT INTO Score".
1643                                         " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'call$p')");
1644                         }
1645                     }
1646                   else if( $winning_party=="contra")
1647                     {
1648                       foreach(array(120,150,180,210,240) as $p)
1649                         {
1650                           $offset = 0;
1651                           if($p==240 || $call_re!=NULL)
1652                             $offset = 1;
1653
1654                           if($contra>$p-$offset)
1655                             mysql_query("INSERT INTO Score".
1656                                         " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'".(240-$p)."')");
1657                         }
1658                       /* re called something and won */
1659                       foreach(array(0,30,60,90,120) as $p)
1660                         {
1661                           if($call_contra!=NULL && $call_contra<$p+1)
1662                             mysql_query("INSERT INTO Score".
1663                                         " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'call$p')");
1664                         }
1665                     }
1666
1667
1668                   /* add score points to email */
1669                   $message .= "\n";
1670                   $Tpoint = 0;
1671                   $message .= " Points Re: \n";
1672                   $queryresult = mysql_query("SELECT score FROM Score ".
1673                                              "  WHERE game_id=$gameid AND party='re'".
1674                                              " ");
1675                   while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
1676                     {
1677                       $message .= "   ".$r[0]."\n";
1678                       $Tpoint ++;
1679                     }
1680                   $message .= " Points Contra: \n";
1681                   $queryresult = mysql_query("SELECT score FROM Score ".
1682                                              "  WHERE game_id=$gameid AND party='contra'".
1683                                              " ");
1684                   while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
1685                     {
1686                       $message .= "   ".$r[0]."\n";
1687                       $Tpoint --;
1688                     }
1689                   $message .= " Total Points (from the Re point of view): $Tpoint\n";
1690                   $message .= "\n";
1691
1692                   /* send out final email */
1693                   $all = array();
1694
1695                   foreach($userids as $user)
1696                     $all[] = DB_get_email_by_userid($user);
1697                   $To = implode(",",$all);
1698
1699                   $help = "\n\n (you can use reply all on this email to reach all the players.)\n";
1700                   mymail($To,$EmailName."game over (game ".DB_format_gameid($gameid).") part 1(2)",$message.$help);
1701
1702                   foreach($userids as $user)
1703                     {
1704                       $To   = DB_get_email_by_userid($user);
1705                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1706
1707                       $link = "Use this link to have a look at game ".DB_format_gameid($gameid).": ".
1708                         $HOST.$INDEX."?me=".$hash."\n\n" ;
1709                       if( DB_get_email_pref_by_uid($user) != "emailaddict" )
1710                         mymail($To,$EmailName."game over (game ".DB_format_gameid($gameid).") part 2(2)",$link);
1711                     }
1712                 }
1713             }
1714           else
1715             {
1716               echo "can't find that card?! <br />\n";
1717             }
1718         }
1719       else if(myisset("card") && !$myturn )
1720         {
1721           echo "please wait until it's your turn! <br />\n";
1722         }
1723
1724       if($seq!=4 && $trickNR>1)
1725         echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1726
1727       /* display points in case game is over */
1728       if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
1729         {
1730           echo "  <li onclick=\"hl('13');\" class=\"current\"><a href=\"#\">Score</a>\n".
1731             "    <div class=\"trick\" id=\"trick13\">\n";
1732           /* add pic for re/contra
1733            "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";*/
1734
1735           $result = mysql_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party,Hand.position FROM Hand".
1736                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1737                                 " LEFT JOIN User ON User.id=Hand.user_id".
1738                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1739                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1740                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1741                                 " WHERE Hand.game_id='$gameid'".
1742                                 " GROUP BY User.fullname" );
1743           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1744             echo "      <div class=\"card".($r[3]-1)."\">\n".
1745                  "        <div class=\"score\">".$r[2]."<br /> ".$r[1]."</div>\n".
1746                  "      </div>\n";
1747
1748           echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1749         }
1750
1751
1752       echo "</ul>\n"; /* end ul tricks*/
1753
1754       $mycards = DB_get_hand($me);
1755       $mycards = mysort($mycards,$gametype);
1756       echo "<div class=\"mycards\">\n";
1757
1758       if($myturn && !myisset("card") && $mystatus=='play' )
1759         {
1760           echo "Hello ".$myname.", it's your turn!  <br />\n";
1761           echo "Your cards are: <br />\n";
1762
1763           /* do we have to follow suite? */
1764           $followsuit = 0;
1765           if(have_suit($mycards,$firstcard))
1766             $followsuit = 1;
1767
1768           foreach($mycards as $card)
1769             {
1770               if($followsuit && !same_type($card,$firstcard))
1771                 display_card($card,$PREF["cardset"]);
1772               else
1773                 display_link_card($card,$PREF["cardset"]);
1774             }
1775         }
1776       else if($mystatus=='play' )
1777         {
1778           echo "Your cards are: <br />\n";
1779           foreach($mycards as $card)
1780             display_card($card,$PREF["cardset"]);
1781         }
1782       else if($mystatus=='gameover')
1783         {
1784           $oldcards = DB_get_all_hand($me);
1785           $oldcards = mysort($oldcards,$gametype);
1786           echo "Your cards were: <br />\n";
1787           foreach($oldcards as $card)
1788             display_card($card,$PREF["cardset"]);
1789
1790           $userids = DB_get_all_userid_by_gameid($gameid);
1791           foreach($userids as $user)
1792             {
1793               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1794
1795               if($userhash!=$me)
1796                 {
1797                   echo "<br />";
1798
1799                   $name = DB_get_name_by_userid($user);
1800                   $oldcards = DB_get_all_hand($userhash);
1801                   $oldcards = mysort($oldcards,$gametype);
1802                   echo "$name's cards were: <br />\n";
1803                   foreach($oldcards as $card)
1804                     display_card($card,$PREF["cardset"]);
1805                 }
1806             };
1807         }
1808       echo "</div>\n";
1809
1810       /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
1811       if($mystatus=='play')
1812         break;
1813
1814       /* the following happens only when the gamestatus is 'gameover' */
1815       /* check if game is over, display results */
1816       if(DB_get_game_status_by_gameid($gameid)=='play')
1817         {
1818           echo "The game is over for you.. other people still need to play though";
1819         }
1820       else
1821         {
1822           $result = mysql_query("SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1823                                 " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1824                                 " LEFT JOIN User ON User.id=Hand.user_id".
1825                                 " LEFT JOIN Play ON Trick.id=Play.trick_id".
1826                                 " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1827                                 " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1828                                 " WHERE Hand.game_id='$gameid'".
1829                                 " GROUP BY Hand.party" );
1830           echo "<div class=\"total\"> Totals:<br />\n";
1831           while( $r = mysql_fetch_array($result,MYSQL_NUM))
1832             echo "  ".$r[0]." ".$r[1]."<br />\n";
1833
1834           echo "<div class=\"re\">\n Points Re: <br />\n";
1835           $queryresult = mysql_query("SELECT score FROM Score ".
1836                                      "  WHERE game_id=$gameid AND party='re'".
1837                                      " ");
1838           while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
1839             echo "   ".$r[0]."<br />\n";
1840           echo "</div>\n";
1841
1842           echo "<div class=\"contra\">\n Points Contra: <br />\n";
1843           $queryresult = mysql_query("SELECT score FROM Score ".
1844                                      "  WHERE game_id=$gameid AND party='contra'".
1845                                      " ");
1846           while($r = mysql_fetch_array($queryresult,MYSQL_NUM) )
1847             echo "   ".$r[0]."<br />\n";
1848           echo "</div>\n";
1849
1850           echo "</div>\n";
1851
1852
1853         }
1854       break;
1855     default:
1856       myerror("error in testing the status");
1857     }
1858     /* output left menu */
1859     display_user_menu();
1860
1861     /* output right menu */
1862
1863       /* display rule set for this game */
1864     echo "<div class=\"gameinfo\">\n";
1865
1866     if($gamestatus != 'pre')
1867       echo " Gametype: $GT <br />\n";
1868
1869     echo "Rules: <br />\n";
1870     echo "10ofhearts : ".$RULES["dullen"]      ."<br />\n";
1871     echo "schweinchen: ".$RULES["schweinchen"] ."<br />\n";
1872     echo "call:        ".$RULES["call"]        ."<br />\n";
1873
1874     echo "<hr />\n";
1875     if($gamestatus == 'play' )
1876       output_form_calls($me);
1877
1878     /* get time from the last action of the game */
1879     $result  = mysql_query("SELECT mod_date from Game WHERE id='$gameid' " );
1880     $r       = mysql_fetch_array($result,MYSQL_NUM);
1881     $gameend = time() - strtotime($r[0]);
1882
1883     if($gamestatus == 'play' || $gameend < 60*60*24*7)
1884       {
1885         echo "<br />\nA short comment:<input name=\"comment\" type=\"text\" size=\"15\" maxlength=\"100\" />\n";
1886         echo "<hr />";
1887       }
1888
1889     echo "<input type=\"submit\" value=\"submit\" />\n";
1890
1891
1892     if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
1893       {
1894         echo "<hr />\n";
1895
1896         $session = DB_get_session_by_gameid($gameid);
1897         $result  = mysql_query("SELECT id,create_date FROM Game".
1898                                " WHERE session=$session".
1899                                " ORDER BY create_date DESC".
1900                                " LIMIT 1");
1901         $r = -1;
1902         if($result)
1903           $r = mysql_fetch_array($result,MYSQL_NUM);
1904
1905         if(!$session || $gameid==$r[0])
1906           {
1907             /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
1908             $names = DB_get_all_names_by_gameid($gameid);
1909             $type  = DB_get_gametype_by_gameid($gameid);
1910
1911             if($type=="solo")
1912               output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
1913             else
1914               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
1915           }
1916       }
1917
1918     $session = DB_get_session_by_gameid($gameid);
1919     $score = generate_score_table($session);
1920
1921     //  if(size_of($score)>30)
1922       echo $score;
1923
1924     echo "</div>\n";
1925
1926
1927     echo "</form>\n";
1928     output_footer();
1929     DB_close();
1930     exit();
1931  }
1932 /* user status page */
1933 else if( myisset("email","password") || isset($_SESSION["name"]) )
1934    {
1935      /* test id and password, should really be done in one step */
1936      if(!isset($_SESSION["name"]))
1937        {
1938          $email     = $_REQUEST["email"];
1939          $password  = $_REQUEST["password"];
1940        }
1941      else
1942        {
1943          $name = $_SESSION["name"];
1944          $email     = DB_get_email_by_name($name);
1945          $password  = DB_get_passwd_by_name($name);
1946        };
1947
1948      if(myisset("forgot"))
1949        {
1950          $ok = 1;
1951
1952          $myid = DB_get_userid_by_email($email);
1953          if(!$myid)
1954            $ok = 0;
1955
1956          if($ok)
1957            {
1958              /* check how many entries in recovery table */
1959              $number = DB_get_number_of_passwords_recovery($myid);
1960
1961              /* if less than N recent ones, add a new one and send out email */
1962              if( $number < 5 )
1963                {
1964                  echo "Ok, I send you a new password. <br />";
1965                  if($number >1)
1966                    echo "N.B. You tried this already $number times during the last day and it will only work ".
1967                      " 5 times during a day.<br />";
1968                  echo "The new password will be valid for one day, make sure you reset it to something else.<br />";
1969                  echo "Back to the  <a href=\"$INDEX\">main page</a>.";
1970
1971                  $TIME  = (string) time(); /* to avoid collisions */
1972                  $hash  = md5("Anewpassword".$email.$TIME);
1973                  $newpw = substr($hash,1,8);
1974
1975                  $message = "Someone (hopefully you) requested a new password. \n".
1976                    "You can use this email and the following password: \n".
1977                    "   $newpw    \n".
1978                    "to log into the server. The new password is valid for 24h, so make\n".
1979                    "sure you reset your password to something new. Your old password will\n".
1980                    " also still be valid until you set a new one\n";
1981                  mymail($email,$EmailName."recovery ",$message);
1982
1983                  DB_set_recovery_password($myid,md5($newpw));
1984                }
1985              else
1986                {
1987                  echo "Sorry you already tried 5 times during the last 24h.<br />".
1988                    "You need to use one of those passwords or wait to get a new one.<br />";
1989                  echo "Back to the <a href=\"$INDEX\">main page</a>.";
1990                }
1991            }
1992          else
1993            {
1994              if($email=="")
1995                echo "You need to give me an email address! <br />".
1996                  "Please try <a href=\"$INDEX\">again</a>.";
1997              else
1998                echo "Couldn't find a player with this email! <br />".
1999                  "Please contact Arun, if you think this is a mistake <br />".
2000                  "or else try <a href=\"$INDEX\">again</a>.";
2001            }
2002        }
2003      else
2004      {
2005        /* verify password and email */
2006        if(strlen($password)!=32)
2007          $password = md5($password);
2008
2009        $ok  = 1;
2010        $myid = DB_get_userid_by_email_and_password($email,$password);
2011        if(!$myid)
2012          $ok = 0;
2013
2014        if($ok)
2015          {
2016            $myname = DB_get_name_by_email($email);
2017            $_SESSION["name"] = $myname;
2018            output_status();
2019
2020            DB_get_PREF($myid);
2021
2022            if(myisset("setpref"))
2023              {
2024                $setpref=$_REQUEST["setpref"];
2025                switch($setpref)
2026                  {
2027                  case "germancards":
2028                  case "englishcards":
2029                    $result = mysql_query("SELECT * from User_Prefs".
2030                                          " WHERE user_id='$myid' AND pref_key='cardset'" );
2031                    if( mysql_fetch_array($result,MYSQL_NUM))
2032                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
2033                                            " WHERE user_id='$myid' AND pref_key='cardset'" );
2034                    else
2035                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$myid','cardset',".
2036                                            DB_quote_smart($setpref).")");
2037                    echo "Ok, changed you preferences for the cards.\n";
2038                    break;
2039                  case "emailaddict":
2040                  case "emailnonaddict":
2041                    $result = mysql_query("SELECT * from User_Prefs".
2042                                          " WHERE user_id='$myid' AND pref_key='email'" );
2043                    if( mysql_fetch_array($result,MYSQL_NUM))
2044                      $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
2045                                            " WHERE user_id='$myid' AND pref_key='email'" );
2046                    else
2047                      $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$myid','email',".
2048                                            DB_quote_smart($setpref).")");
2049                    echo "Ok, changed you preferences for sending out emails.\n";
2050                    break;
2051                  }
2052              }
2053            else if(myisset("passwd"))
2054              {
2055                if( $_REQUEST["passwd"]=="ask" )
2056                  {
2057                    /* reset password form*/
2058                    output_password_recovery($email,$password);
2059                  }
2060                else if($_REQUEST["passwd"]=="set")
2061                  {
2062                    /* reset password */
2063                    $ok = 1;
2064
2065                    /* check if old password matches */
2066                    $oldpasswd = md5($_REQUEST["password0"]);
2067                    if(!( ($password == $oldpasswd) || DB_check_recovery_passwords($oldpasswd,$email) ))
2068                      $ok = -1;
2069                    /* check if new passwords are types the same twice */
2070                    if($_REQUEST["password1"] != $_REQUEST["password2"] )
2071                      $ok = -2;
2072
2073                    switch($ok)
2074                      {
2075                      case '-2':
2076                        echo "The new passwords don't match. <br />";
2077                        break;
2078                      case '-1':
2079                        echo "The old password is not correct. <br />";
2080                        break;
2081                      case '1':
2082                        echo "Changed the password.<br />";
2083                        mysql_query("UPDATE User SET password='".md5($_REQUEST["password1"]).
2084                                    "' WHERE id=".DB_quote_smart($myid));
2085                        break;
2086                      }
2087                    /* set password */
2088                  }
2089              }
2090            else /* output default user page */
2091              {
2092                /* display links to settings */
2093                output_user_settings();
2094
2095                DB_update_user_timestamp($myid);
2096
2097                display_user_menu();
2098
2099                echo "<div class=\"user\">";
2100                echo "<h4>These are all your games:</h4>\n";
2101                echo "<p>Session: <br />\n";
2102                echo "<span class=\"gamestatuspre\"> p </span> =  pre-game phase ";
2103                echo "<span class=\"gamestatusplay\">P </span> =  game in progess ";
2104                echo "<span class=\"gamestatusover\">F </span> =  game finished <br />";
2105                echo "</p>\n";
2106
2107                $output = array();
2108                $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date,Game.player,Game.status from Hand".
2109                                      " LEFT JOIN Game ON Game.id=Hand.game_id".
2110                                      " WHERE user_id='$myid'".
2111                                      " ORDER BY Game.session,Game.create_date" );
2112                $gamenrold = -1;
2113                echo "<table>\n <tr><td>\n";
2114                while( $r = mysql_fetch_array($result,MYSQL_NUM))
2115                  {
2116                    $game = DB_format_gameid($r[1]);
2117                    $gamenr = (int) $game;
2118                    if($gamenrold < $gamenr)
2119                      {
2120                        if($gamenrold!=-1)
2121                          echo "</td></tr>\n <tr> <td>$gamenr:</td><td> ";
2122                        else
2123                          echo "$gamenr:</td><td> ";
2124                        $gamenrold = $gamenr;
2125                      }
2126                    if($r[4]=='pre')
2127                      {
2128                        echo "\n   <span class=\"gamestatuspre\"><a href=\"".$INDEX."?me=".$r[0]."\">p </a></span> ";
2129
2130                      }
2131                    else if ($r[4]=='gameover')
2132                      echo "\n   <span class=\"gamestatusover\"><a href=\"".$INDEX."?me=".$r[0]."\">F </a></span> ";
2133                    else
2134                      {
2135                        echo "\n   <span class=\"gamestatusplay\"><a href=\"".$INDEX."?me=".$r[0]."\">P </a></span> ";
2136                      }
2137                    if($r[4] != 'gameover')
2138                      {
2139                        echo "</td><td>\n    ";
2140                        if($r[3])
2141                          {
2142                            if($r[3]==$myid)
2143                              echo "(it's <strong>your</strong> turn)\n";
2144                            else
2145                              {
2146                                $name = DB_get_name_by_userid($r[3]);
2147                                $gameid = $r[1];
2148                                if(DB_get_reminder($r[3],$gameid)==0)
2149                                  if(time()-strtotime($r[2]) > 60*60*24*7)
2150                                    echo "".
2151                                      "<a href=\"$INDEX?remind=1&amp;me=".$r[0]."\">Send a reminder.</a>";
2152                                echo "(it's $name's turn)\n";
2153                              };
2154                          }
2155                        if(time()-strtotime($r[2]) > 60*60*24*30)
2156                          echo "".
2157                            "<a href=\"$INDEX?cancel=1&amp;me=".$r[0]."\">Cancel?</a>".
2158                            " (clicking here is final and can't be restored)";
2159
2160                      }
2161                  }
2162                echo "</td></tr>\n</table>\n";
2163                $names = DB_get_all_names();
2164                echo "<h4>Registered players:</h4>\n<p>\n";
2165                echo implode(", ",$names)."\n";
2166                echo "</p>\n</div>";
2167              }
2168          }
2169        else
2170          {
2171            echo "<div class=\"message\">Sorry email and password don't match. Please <a href=\"$INDEX\">try again</a>. </div>";
2172          }
2173      };
2174      output_footer();
2175      DB_close();
2176      exit();
2177    }
2178 /* default login page */
2179  else
2180    {
2181      $pre[0]=0;$game[0]=0;$done[0]=0;
2182      $r=mysql_query("SELECT COUNT(id) FROM Game GROUP BY status");
2183      if($r) {
2184        $pre  = mysql_fetch_array($r,MYSQL_NUM);
2185        $game = mysql_fetch_array($r,MYSQL_NUM);
2186        $done = mysql_fetch_array($r,MYSQL_NUM);
2187      }
2188
2189      $r=mysql_query("SELECT AVG(datediff(mod_date,create_date)) FROM Game where status='gameover' ");
2190      if($r)
2191        $avgage= mysql_fetch_array($r,MYSQL_NUM);
2192      else
2193        $avgage[0]=0;
2194
2195      output_home_page($pre[0],$game[0],$done[0],$avgage[0]);
2196    }
2197
2198 output_footer();
2199
2200 DB_close();
2201
2202 /*
2203  *Local Variables:
2204  *mode: php
2205  *mode: hs-minor
2206  *End:
2207  */
2208 ?>
2209
2210