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