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