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