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