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