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