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